From de6d6c8714ee1daf84d20e360e1b06a11e627c38 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 27 Sep 2018 15:19:55 -0700 Subject: [PATCH 001/305] cached chunks expiration setting, fixes #181 --- src/api/java/baritone/api/Settings.java | 6 ++ src/main/java/baritone/cache/CachedChunk.java | 5 +- .../java/baritone/cache/CachedRegion.java | 90 +++++++++++++------ src/main/java/baritone/cache/CachedWorld.java | 1 + src/main/java/baritone/cache/ChunkPacker.java | 2 +- 5 files changed, 77 insertions(+), 27 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index fdbaaf45..97337d2a 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -404,6 +404,12 @@ public class Settings { */ public Setting followRadius = new Setting<>(3); + /** + * Cached chunks (regardless of if they're in RAM or saved to disk) expire and are deleted after this number of seconds + * -1 to disable + */ + public Setting cachedChunksExpirySeconds = new Setting<>(-1L); + /** * The function that is called when Baritone will log to chat. This function can be added to * via {@link Consumer#andThen(Consumer)} or it can completely be overriden via setting diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index b8d88a49..317bf377 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -106,7 +106,9 @@ public final class CachedChunk implements IBlockTypeAccess, Helper { private final Map> specialBlockLocations; - CachedChunk(int x, int z, BitSet data, IBlockState[] overview, Map> specialBlockLocations) { + public final long cacheTimestamp; + + CachedChunk(int x, int z, BitSet data, IBlockState[] overview, Map> specialBlockLocations, long cacheTimestamp) { validateSize(data); this.x = x; @@ -115,6 +117,7 @@ public final class CachedChunk implements IBlockTypeAccess, Helper { this.overview = overview; this.heightMap = new int[256]; this.specialBlockLocations = specialBlockLocations; + this.cacheTimestamp = cacheTimestamp; calculateHeightMap(); } diff --git a/src/main/java/baritone/cache/CachedRegion.java b/src/main/java/baritone/cache/CachedRegion.java index e9402bd5..200e0f16 100644 --- a/src/main/java/baritone/cache/CachedRegion.java +++ b/src/main/java/baritone/cache/CachedRegion.java @@ -17,6 +17,7 @@ package baritone.cache; +import baritone.Baritone; import baritone.api.cache.ICachedRegion; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; @@ -112,6 +113,7 @@ public final class CachedRegion implements ICachedRegion { if (!hasUnsavedChanges) { return; } + removeExpired(); try { Path path = Paths.get(directory); if (!Files.exists(path)) { @@ -129,8 +131,8 @@ public final class CachedRegion implements ICachedRegion { DataOutputStream out = new DataOutputStream(gzipOut) ) { out.writeInt(CACHED_REGION_MAGIC); - for (int z = 0; z < 32; z++) { - for (int x = 0; x < 32; x++) { + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { CachedChunk chunk = this.chunks[x][z]; if (chunk == null) { out.write(CHUNK_NOT_PRESENT); @@ -143,8 +145,8 @@ public final class CachedRegion implements ICachedRegion { } } } - for (int z = 0; z < 32; z++) { - for (int x = 0; x < 32; x++) { + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { if (chunks[x][z] != null) { for (int i = 0; i < 256; i++) { out.writeUTF(ChunkPacker.blockToString(chunks[x][z].getOverview()[i].getBlock())); @@ -152,8 +154,8 @@ public final class CachedRegion implements ICachedRegion { } } } - for (int z = 0; z < 32; z++) { - for (int x = 0; x < 32; x++) { + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { if (chunks[x][z] != null) { Map> locs = chunks[x][z].getRelativeBlocks(); out.writeShort(locs.entrySet().size()); @@ -168,10 +170,17 @@ public final class CachedRegion implements ICachedRegion { } } } + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + if (chunks[x][z] != null) { + out.writeLong(chunks[x][z].cacheTimestamp); + } + } + } } hasUnsavedChanges = false; System.out.println("Saved region successfully"); - } catch (IOException ex) { + } catch (Exception ex) { ex.printStackTrace(); } } @@ -203,42 +212,42 @@ public final class CachedRegion implements ICachedRegion { // 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]; + boolean[][] present = new boolean[32][32]; + BitSet[][] bitSets = new BitSet[32][32]; Map>[][] location = new Map[32][32]; - for (int z = 0; z < 32; z++) { - for (int x = 0; x < 32; x++) { + IBlockState[][][] overview = new IBlockState[32][32][]; + long[][] cacheTimestamp = new long[32][32]; + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { int isChunkPresent = in.read(); switch (isChunkPresent) { case CHUNK_PRESENT: byte[] bytes = new byte[CachedChunk.SIZE_IN_BYTES]; in.readFully(bytes); + bitSets[x][z] = BitSet.valueOf(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 IBlockState[256], location[x][z]); + overview[x][z] = new IBlockState[256]; + present[x][z] = true; 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 x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + if (present[x][z]) { for (int i = 0; i < 256; i++) { - tmpCached[x][z].getOverview()[i] = ChunkPacker.stringToBlock(in.readUTF()).getDefaultState(); + overview[x][z][i] = ChunkPacker.stringToBlock(in.readUTF()).getDefaultState(); } } } } - for (int z = 0; z < 32; z++) { - for (int x = 0; x < 32; x++) { - if (tmpCached[x][z] != null) { + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + if (present[x][z]) { // 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 @@ -264,21 +273,52 @@ public final class CachedRegion implements ICachedRegion { } } } + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + if (present[x][z]) { + cacheTimestamp[x][z] = in.readLong(); + } + } + } // 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]; + if (present[x][z]) { + int regionX = this.x; + int regionZ = this.z; + int chunkX = x + 32 * regionX; + int chunkZ = z + 32 * regionZ; + this.chunks[x][z] = new CachedChunk(chunkX, chunkZ, bitSets[x][z], overview[x][z], location[x][z], cacheTimestamp[x][z]); + } } } } + removeExpired(); hasUnsavedChanges = false; long end = System.nanoTime() / 1000000L; System.out.println("Loaded region successfully in " + (end - start) + "ms"); - } catch (IOException ex) { + } catch (Exception ex) { // corrupted files can cause NullPointerExceptions as well as IOExceptions ex.printStackTrace(); } } + public synchronized final void removeExpired() { + long expiry = Baritone.settings().cachedChunksExpirySeconds.get(); + if (expiry < 0) { + return; + } + long now = System.currentTimeMillis(); + long oldestAcceptableAge = now - expiry * 1000L; + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + if (this.chunks[x][z] != null && this.chunks[x][z].cacheTimestamp < oldestAcceptableAge) { + System.out.println("Removing chunk " + (x + 32 * this.x) + "," + (z + 32 * this.z) + " because it was cached " + (now - this.chunks[x][z].cacheTimestamp) / 1000L + " seconds ago, and max age is " + expiry); + this.chunks[x][z] = null; + } + } + } + } + /** * @return The region x coordinate */ diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 3901303d..db626aca 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -142,6 +142,7 @@ public final class CachedWorld implements ICachedWorld, Helper { public final void save() { if (!Baritone.settings().chunkCaching.get()) { System.out.println("Not saving to disk; chunk caching is disabled."); + allRegions().forEach(CachedRegion::removeExpired); // even if we aren't saving to disk, still delete expired old chunks from RAM return; } long start = System.nanoTime() / 1000000L; diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index 4164be3c..e29bde00 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -106,7 +106,7 @@ public final class ChunkPacker implements Helper { blocks[z << 4 | x] = Blocks.AIR.getDefaultState(); } } - return new CachedChunk(chunk.x, chunk.z, bitSet, blocks, specialBlocks); + return new CachedChunk(chunk.x, chunk.z, bitSet, blocks, specialBlocks, System.currentTimeMillis()); } public static String blockToString(Block block) { From 015462eddb4b7908dd227d30946221cbc6c3cc32 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 27 Sep 2018 15:37:22 -0700 Subject: [PATCH 002/305] beg people not to disable chunk caching --- src/api/java/baritone/api/Settings.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 97337d2a..15ae9eee 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -407,6 +407,22 @@ public class Settings { /** * Cached chunks (regardless of if they're in RAM or saved to disk) expire and are deleted after this number of seconds * -1 to disable + *

+ * I would highly suggest leaving this setting disabled (-1). + *

+ * The only valid reason I can think of enable this setting is if you are extremely low on disk space and you play on multiplayer, + * and can't take (average) 300kb saved for every 512x512 area. (note that more complicated terrain is less compressible and will take more space) + *

+ * However, simply discarding old chunks because they are old is inadvisable. Baritone is extremely good at correcting + * itself and its paths as it learns new information, as new chunks load. There is no scenario in which having an + * incorrect cache can cause Baritone to get stuck, take damage, or perform any action it wouldn't otherwise, everything + * is rechecked once the real chunk is in range. + *

+ * Having a robust cache greatly improves long distance pathfinding, as it's able to go around large scale obstacles + * before they're in render distance. In fact, when the chunkCaching setting is disabled and Baritone starts anew + * every time, or when you enter a completely new and very complicated area, it backtracks far more often because it + * has to build up that cache from scratch. But after it's gone through an area just once, the next time will have zero + * backtracking, since the entire area is now known and cached. */ public Setting cachedChunksExpirySeconds = new Setting<>(-1L); From 2f602f87181177b94d289b7df40acf31dae6058a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 27 Sep 2018 16:11:55 -0700 Subject: [PATCH 003/305] no stop dont --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index ee58fd60..8ba5a8d2 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -31,7 +31,10 @@ import baritone.cache.ChunkPacker; import baritone.cache.Waypoint; import baritone.cache.WorldProvider; import baritone.pathing.calc.AbstractNodeCostSearch; -import baritone.pathing.movement.*; +import baritone.pathing.movement.CalculationContext; +import baritone.pathing.movement.Movement; +import baritone.pathing.movement.MovementHelper; +import baritone.pathing.movement.Moves; import net.minecraft.block.Block; import net.minecraft.client.multiplayer.ChunkProviderClient; import net.minecraft.entity.Entity; @@ -198,7 +201,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { event.cancel(); return; } - if (msg.equals("cancel")) { + if (msg.equals("cancel") || msg.equals("stop")) { MineBehavior.INSTANCE.cancel(); FollowBehavior.INSTANCE.cancel(); PathingBehavior.INSTANCE.cancel(); From c383186808c2a75aa3bb7d57c93ef28f60d66c1f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 28 Sep 2018 18:55:04 -0700 Subject: [PATCH 004/305] sprint through descend then ascend in the same direction, fixes #115 --- .../baritone/pathing/path/PathExecutor.java | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index e8e74c7d..1d6da5a6 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -20,10 +20,14 @@ package baritone.pathing.path; import baritone.Baritone; import baritone.api.event.events.TickEvent; import baritone.api.pathing.movement.ActionCosts; -import baritone.pathing.movement.*; +import baritone.pathing.movement.CalculationContext; +import baritone.pathing.movement.Movement; +import baritone.pathing.movement.MovementHelper; +import baritone.pathing.movement.MovementState; import baritone.pathing.movement.movements.*; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; +import baritone.utils.InputOverrideHandler; import baritone.utils.Utils; import baritone.utils.pathing.BetterBlockPos; import net.minecraft.init.Blocks; @@ -320,10 +324,18 @@ public class PathExecutor implements Helper { } Movement next = path.movements().get(pathPosition + 1); + if (next instanceof MovementAscend && current.getDirection().up().equals(next.getDirection().down())) { + // a descend then an ascend in the same direction + if (!player().isSprinting()) { + player().setSprinting(true); + } + pathPosition++; + logDebug("Skipping descend to straight ascend"); + return; + } if (canSprintInto(current, next)) { if (playerFeet().equals(current.getDest())) { pathPosition++; - clearKeys(); } if (!player().isSprinting()) { player().setSprinting(true); @@ -332,6 +344,19 @@ public class PathExecutor implements Helper { } //logDebug("Turning off sprinting " + movement + " " + next + " " + movement.getDirection() + " " + next.getDirection().down() + " " + next.getDirection().down().equals(movement.getDirection())); } + if (current instanceof MovementAscend && pathPosition != 0) { + Movement prev = path.movements().get(pathPosition - 1); + if (prev instanceof MovementDescend && prev.getDirection().up().equals(current.getDirection().down())) { + BlockPos center = current.getSrc().up(); + if (player().posY >= center.getY()) { // playerFeet adds 0.1251 to account for soul sand + Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.JUMP, false); + if (!player().isSprinting()) { + player().setSprinting(true); + } + return; + } + } + } player().setSprinting(false); } From 4b76af2487bbbbee1e7ce844501dc84fab29dba3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 29 Sep 2018 07:30:56 -0700 Subject: [PATCH 005/305] update settings link --- FEATURES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FEATURES.md b/FEATURES.md index 172b2f87..71cb7f6c 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -19,7 +19,7 @@ Baritone uses a modified version of A*. - **Backtrack cost favoring** While calculating the next segment, Baritone favors backtracking its current segment slightly, as a tiebreaker. This allows it to splice and jump onto the next segment as early as possible, if the next segment begins with a backtrack of the current one. Example # Configuring Baritone -All the settings and documentation are here. +All the settings and documentation are here. To change a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `pathTimeoutMS 250`). It's case insensitive. # Goals From 229739575c3b2fd0c97102e4fe84e31ffa252268 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 29 Sep 2018 07:32:58 -0700 Subject: [PATCH 006/305] BaritoneAutoTest overrides width and height on its own --- Dockerfile | 2 -- 1 file changed, 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index ac36eea5..883d6efd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,8 +17,6 @@ RUN apt install -qq --force-yes unzip wget ADD . /code -RUN echo "\nrunClient {\nargs \"--width\",\"128\",\"--height\",\"128\"\n}" >> /code/build.gradle - # this .deb is specially patched to support lwjgl # source: https://github.com/tectonicus/tectonicus/issues/60#issuecomment-154239173 RUN dpkg -i /code/scripts/xvfb_1.16.4-1_amd64.deb From bcb95c55c9916a417f7bdb7adf2645c80185473b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 29 Sep 2018 07:43:34 -0700 Subject: [PATCH 007/305] allow a bit more time, it's a little flaky on travis right now --- src/main/java/baritone/utils/BaritoneAutoTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index faad6153..53cd55fe 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -41,7 +41,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { private static final long TEST_SEED = -928872506371745L; private static final BlockPos STARTING_POSITION = new BlockPos(0, 65, 0); private static final Goal GOAL = new GoalBlock(69, 121, 420); - private static final int MAX_TICKS = 3500; + private static final int MAX_TICKS = 3700; /** * Called right after the {@link GameSettings} object is created in the {@link Minecraft} instance. From b12c2ea62f5f1eefe149d8c96afcf4ebdf42fc3b Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 29 Sep 2018 23:52:01 -0500 Subject: [PATCH 008/305] UTILIZE Service Loaders https://i.imgur.com/kAm0xd3.png --- src/api/java/baritone/api/BaritoneAPI.java | 62 ++++++----------- .../java/baritone/api/IBaritoneProvider.java | 42 ++++++++++++ src/main/java/baritone/Baritone.java | 12 ---- src/main/java/baritone/BaritoneProvider.java | 67 +++++++++++++++++++ .../services/baritone.api.IBaritoneProvider | 1 + 5 files changed, 129 insertions(+), 55 deletions(-) create mode 100644 src/api/java/baritone/api/IBaritoneProvider.java create mode 100644 src/main/java/baritone/BaritoneProvider.java create mode 100644 src/main/resources/META-INF/services/baritone.api.IBaritoneProvider diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index aa9491db..821c4fab 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -20,6 +20,9 @@ package baritone.api; import baritone.api.behavior.*; import baritone.api.cache.IWorldProvider; +import java.util.Iterator; +import java.util.ServiceLoader; + /** * API exposure for various things implemented in Baritone. *

@@ -30,35 +33,36 @@ import baritone.api.cache.IWorldProvider; */ public class BaritoneAPI { - // General - private static final Settings settings = new Settings(); - private static IWorldProvider worldProvider; + private static IBaritoneProvider baritone; + private static Settings settings; - // Behaviors - private static IFollowBehavior followBehavior; - private static ILookBehavior lookBehavior; - private static IMemoryBehavior memoryBehavior; - private static IMineBehavior mineBehavior; - private static IPathingBehavior pathingBehavior; + static { + ServiceLoader baritoneLoader = ServiceLoader.load(IBaritoneProvider.class); + Iterator instances = baritoneLoader.iterator(); + if (instances.hasNext()) + baritone = instances.next(); + + settings = new Settings(); + } public static IFollowBehavior getFollowBehavior() { - return followBehavior; + return baritone.getFollowBehavior(); } public static ILookBehavior getLookBehavior() { - return lookBehavior; + return baritone.getLookBehavior(); } public static IMemoryBehavior getMemoryBehavior() { - return memoryBehavior; + return baritone.getMemoryBehavior(); } public static IMineBehavior getMineBehavior() { - return mineBehavior; + return baritone.getMineBehavior(); } public static IPathingBehavior getPathingBehavior() { - return pathingBehavior; + return baritone.getPathingBehavior(); } public static Settings getSettings() { @@ -66,34 +70,6 @@ public class BaritoneAPI { } public static IWorldProvider getWorldProvider() { - return worldProvider; + return baritone.getWorldProvider(); } - - /** - * FOR INTERNAL USE ONLY - */ - public static void registerProviders( - IWorldProvider worldProvider - ) { - BaritoneAPI.worldProvider = worldProvider; - } - - /** - * FOR INTERNAL USE ONLY - */ - // @formatter:off - public static void registerDefaultBehaviors( - IFollowBehavior followBehavior, - ILookBehavior lookBehavior, - IMemoryBehavior memoryBehavior, - IMineBehavior mineBehavior, - IPathingBehavior pathingBehavior - ) { - BaritoneAPI.followBehavior = followBehavior; - BaritoneAPI.lookBehavior = lookBehavior; - BaritoneAPI.memoryBehavior = memoryBehavior; - BaritoneAPI.mineBehavior = mineBehavior; - BaritoneAPI.pathingBehavior = pathingBehavior; - } - // @formatter:on } diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java new file mode 100644 index 00000000..a1ad99a2 --- /dev/null +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -0,0 +1,42 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api; + +import baritone.api.behavior.*; +import baritone.api.cache.IWorldProvider; + +/** + * @author Brady + * @since 9/29/2018 + */ +public interface IBaritoneProvider { + + IFollowBehavior getFollowBehavior(); + + ILookBehavior getLookBehavior(); + + IMemoryBehavior getMemoryBehavior(); + + IMineBehavior getMineBehavior(); + + IPathingBehavior getPathingBehavior(); + + Settings getSettings(); + + IWorldProvider getWorldProvider(); +} diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 4a764bcc..b7904d00 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -88,8 +88,6 @@ public enum Baritone { // We might want to change this... this.settings = BaritoneAPI.getSettings(); - BaritoneAPI.registerProviders(WorldProvider.INSTANCE); - this.behaviors = new ArrayList<>(); { registerBehavior(PathingBehavior.INSTANCE); @@ -98,16 +96,6 @@ public enum Baritone { registerBehavior(LocationTrackingBehavior.INSTANCE); registerBehavior(FollowBehavior.INSTANCE); registerBehavior(MineBehavior.INSTANCE); - - // TODO: Clean this up - // Maybe combine this call in someway with the registerBehavior calls? - BaritoneAPI.registerDefaultBehaviors( - FollowBehavior.INSTANCE, - LookBehavior.INSTANCE, - MemoryBehavior.INSTANCE, - MineBehavior.INSTANCE, - PathingBehavior.INSTANCE - ); } if (BaritoneAutoTest.ENABLE_AUTO_TEST) { registerEventListener(BaritoneAutoTest.INSTANCE); diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java new file mode 100644 index 00000000..039d09a5 --- /dev/null +++ b/src/main/java/baritone/BaritoneProvider.java @@ -0,0 +1,67 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone; + +import baritone.api.IBaritoneProvider; +import baritone.api.Settings; +import baritone.api.behavior.*; +import baritone.api.cache.IWorldProvider; +import baritone.behavior.*; +import baritone.cache.WorldProvider; + +/** + * @author Brady + * @since 9/29/2018 + */ +public final class BaritoneProvider implements IBaritoneProvider { + + @Override + public IFollowBehavior getFollowBehavior() { + return FollowBehavior.INSTANCE; + } + + @Override + public ILookBehavior getLookBehavior() { + return LookBehavior.INSTANCE; + } + + @Override + public IMemoryBehavior getMemoryBehavior() { + return MemoryBehavior.INSTANCE; + } + + @Override + public IMineBehavior getMineBehavior() { + return MineBehavior.INSTANCE; + } + + @Override + public IPathingBehavior getPathingBehavior() { + return PathingBehavior.INSTANCE; + } + + @Override + public Settings getSettings() { + return Baritone.settings(); + } + + @Override + public IWorldProvider getWorldProvider() { + return WorldProvider.INSTANCE; + } +} diff --git a/src/main/resources/META-INF/services/baritone.api.IBaritoneProvider b/src/main/resources/META-INF/services/baritone.api.IBaritoneProvider new file mode 100644 index 00000000..934db7d3 --- /dev/null +++ b/src/main/resources/META-INF/services/baritone.api.IBaritoneProvider @@ -0,0 +1 @@ +baritone.BaritoneProvider \ No newline at end of file From 3184eaf595015da9eb37bfc2c47360e55fb06fb1 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 29 Sep 2018 23:59:32 -0500 Subject: [PATCH 009/305] Remove IBaritoneProvider#getSettings --- src/api/java/baritone/api/IBaritoneProvider.java | 2 -- src/main/java/baritone/BaritoneProvider.java | 6 ------ 2 files changed, 8 deletions(-) diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index a1ad99a2..03b457bb 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -36,7 +36,5 @@ public interface IBaritoneProvider { IPathingBehavior getPathingBehavior(); - Settings getSettings(); - IWorldProvider getWorldProvider(); } diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index 039d09a5..370a398e 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -18,7 +18,6 @@ package baritone; import baritone.api.IBaritoneProvider; -import baritone.api.Settings; import baritone.api.behavior.*; import baritone.api.cache.IWorldProvider; import baritone.behavior.*; @@ -55,11 +54,6 @@ public final class BaritoneProvider implements IBaritoneProvider { return PathingBehavior.INSTANCE; } - @Override - public Settings getSettings() { - return Baritone.settings(); - } - @Override public IWorldProvider getWorldProvider() { return WorldProvider.INSTANCE; From 866648192b17bb077f889ebe1cb3205b7f6df00d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 30 Sep 2018 07:58:44 -0700 Subject: [PATCH 010/305] readd width and height override --- Dockerfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 883d6efd..b36b3770 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,7 +15,9 @@ RUN apt install -qq --force-yes mesa-utils libgl1-mesa-glx libxcursor1 libxrandr RUN apt install -qq --force-yes unzip wget -ADD . /code +COPY . /code + +RUN echo "\nrunClient {\nargs \"--width\",\"128\",\"--height\",\"128\"\n}" >> /code/build.gradle # this .deb is specially patched to support lwjgl # source: https://github.com/tectonicus/tectonicus/issues/60#issuecomment-154239173 From d58ad6f68f1bbe6503ace5cd709888adcae4fc9f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 30 Sep 2018 08:03:33 -0700 Subject: [PATCH 011/305] finalize --- src/api/java/baritone/api/BaritoneAPI.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index 821c4fab..dec7ec13 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -31,16 +31,15 @@ import java.util.ServiceLoader; * @author Brady * @since 9/23/2018 */ -public class BaritoneAPI { +public final class BaritoneAPI { - private static IBaritoneProvider baritone; - private static Settings settings; + private final static IBaritoneProvider baritone; + private final static Settings settings; static { ServiceLoader baritoneLoader = ServiceLoader.load(IBaritoneProvider.class); Iterator instances = baritoneLoader.iterator(); - if (instances.hasNext()) - baritone = instances.next(); + baritone = instances.next(); settings = new Settings(); } From 09ac3c615cbfa10ced9c18a8befe610d9546e2ef Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 30 Sep 2018 09:14:23 -0700 Subject: [PATCH 012/305] more time maybe --- src/main/java/baritone/utils/BaritoneAutoTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index 53cd55fe..27b9bfb3 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -41,7 +41,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { private static final long TEST_SEED = -928872506371745L; private static final BlockPos STARTING_POSITION = new BlockPos(0, 65, 0); private static final Goal GOAL = new GoalBlock(69, 121, 420); - private static final int MAX_TICKS = 3700; + private static final int MAX_TICKS = 4000; /** * Called right after the {@link GameSettings} object is created in the {@link Minecraft} instance. From 08b9eab9f3a3fc8f39837547a2cf1c0a24405c0d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 30 Sep 2018 21:32:13 -0700 Subject: [PATCH 013/305] draw most recent node considered even if there is no valid best --- src/main/java/baritone/behavior/PathingBehavior.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 377af7f3..c212ac5d 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -24,10 +24,11 @@ import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.RenderEvent; import baritone.api.event.events.TickEvent; import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalXZ; +import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.calc.IPathFinder; -import baritone.api.pathing.goals.GoalXZ; import baritone.pathing.movement.MovementHelper; import baritone.pathing.path.IPath; import baritone.pathing.path.PathExecutor; @@ -35,7 +36,6 @@ import baritone.utils.BlockBreakHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.PathRenderer; -import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.utils.pathing.BetterBlockPos; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; @@ -420,11 +420,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(currentlyRunning -> { currentlyRunning.bestPathSoFar().ifPresent(p -> { PathRenderer.drawPath(p, 0, player(), partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20); - currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { + }); + currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { - PathRenderer.drawPath(mr, 0, player(), partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); - PathRenderer.drawManySelectionBoxes(player(), Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); - }); + PathRenderer.drawPath(mr, 0, player(), partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); + PathRenderer.drawManySelectionBoxes(player(), Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); }); }); //long end = System.nanoTime(); From 13aaec07cd4240b7623427aaba1990c013cfdaa2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 30 Sep 2018 21:32:13 -0700 Subject: [PATCH 014/305] draw most recent node considered even if there is no valid best --- src/main/java/baritone/behavior/PathingBehavior.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 377af7f3..c212ac5d 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -24,10 +24,11 @@ import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.RenderEvent; import baritone.api.event.events.TickEvent; import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalXZ; +import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.calc.IPathFinder; -import baritone.api.pathing.goals.GoalXZ; import baritone.pathing.movement.MovementHelper; import baritone.pathing.path.IPath; import baritone.pathing.path.PathExecutor; @@ -35,7 +36,6 @@ import baritone.utils.BlockBreakHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.PathRenderer; -import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.utils.pathing.BetterBlockPos; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; @@ -420,11 +420,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(currentlyRunning -> { currentlyRunning.bestPathSoFar().ifPresent(p -> { PathRenderer.drawPath(p, 0, player(), partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20); - currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { + }); + currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { - PathRenderer.drawPath(mr, 0, player(), partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); - PathRenderer.drawManySelectionBoxes(player(), Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); - }); + PathRenderer.drawPath(mr, 0, player(), partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); + PathRenderer.drawManySelectionBoxes(player(), Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); }); }); //long end = System.nanoTime(); From b1e1cc43e0327a771f5127cdcd8a3e1e0222cf58 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 30 Sep 2018 21:43:07 -0700 Subject: [PATCH 015/305] simplify properly even when obfuscated --- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index c212ac5d..f903dfbd 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -343,7 +343,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // TODO simplify each individual goal in a GoalComposite if (pos != null && world().getChunk(pos) instanceof EmptyChunk) { - logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance"); + logDebug("Simplifying " + goal.toString().split("\\{")[0] + " to GoalXZ due to distance"); goal = new GoalXZ(pos.getX(), pos.getZ()); } } From f56766be26d62ed077a7a5f04c5c74b499cbc273 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 09:51:43 -0700 Subject: [PATCH 016/305] maybe it just needs more time --- src/main/java/baritone/utils/BaritoneAutoTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index 53cd55fe..27b9bfb3 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -41,7 +41,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { private static final long TEST_SEED = -928872506371745L; private static final BlockPos STARTING_POSITION = new BlockPos(0, 65, 0); private static final Goal GOAL = new GoalBlock(69, 121, 420); - private static final int MAX_TICKS = 3700; + private static final int MAX_TICKS = 4000; /** * Called right after the {@link GameSettings} object is created in the {@link Minecraft} instance. From 109cffc3de6e53771505f99a98a676737008c94d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 09:57:47 -0700 Subject: [PATCH 017/305] rearrange blockstate lookups --- .../baritone/pathing/movement/movements/MovementDiagonal.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index d75515d3..7519f801 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -85,9 +85,7 @@ public class MovementDiagonal extends Movement { return COST_INF; } IBlockState pb0 = BlockStateInterface.get(x, y, destZ); - IBlockState pb1 = BlockStateInterface.get(x, y + 1, destZ); IBlockState pb2 = BlockStateInterface.get(destX, y, z); - IBlockState pb3 = BlockStateInterface.get(destX, y + 1, z); double optionA = MovementHelper.getMiningDurationTicks(context, x, y, destZ, pb0, false); double optionB = MovementHelper.getMiningDurationTicks(context, destX, y, z, pb2, false); if (optionA != 0 && optionB != 0) { @@ -95,11 +93,13 @@ public class MovementDiagonal extends Movement { // so no need to check pb1 as well, might as well return early here return COST_INF; } + IBlockState pb1 = BlockStateInterface.get(x, y + 1, destZ); optionA += MovementHelper.getMiningDurationTicks(context, x, y + 1, destZ, pb1, true); if (optionA != 0 && optionB != 0) { // same deal, if pb1 makes optionA nonzero and option B already was nonzero, pb3 can't affect the result return COST_INF; } + IBlockState pb3 = BlockStateInterface.get(destX, y + 1, z); if (optionA == 0) { // at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction if (MovementHelper.avoidWalkingInto(pb2.getBlock()) || MovementHelper.avoidWalkingInto(pb3.getBlock())) { From 76365a4564c58a3620753fe50e71c4ce6f5d16c8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 10:05:04 -0700 Subject: [PATCH 018/305] sprint on soul sand, fixes #120 --- .../baritone/api/pathing/movement/ActionCosts.java | 14 +++++++------- .../movement/movements/MovementDiagonal.java | 9 ++++++--- .../movement/movements/MovementTraverse.java | 9 ++++++--- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/api/java/baritone/api/pathing/movement/ActionCosts.java b/src/api/java/baritone/api/pathing/movement/ActionCosts.java index e1f72dfa..683b1b10 100644 --- a/src/api/java/baritone/api/pathing/movement/ActionCosts.java +++ b/src/api/java/baritone/api/pathing/movement/ActionCosts.java @@ -23,21 +23,21 @@ public interface ActionCosts { * These costs are measured roughly in ticks btw */ double WALK_ONE_BLOCK_COST = 20 / 4.317; // 4.633 - double WALK_ONE_IN_WATER_COST = 20 / 2.2; + double WALK_ONE_IN_WATER_COST = 20 / 2.2; // 9.091 double WALK_ONE_OVER_SOUL_SAND_COST = WALK_ONE_BLOCK_COST * 2; // 0.4 in BlockSoulSand but effectively about half - double SPRINT_ONE_OVER_SOUL_SAND_COST = WALK_ONE_OVER_SOUL_SAND_COST * 0.75; - double LADDER_UP_ONE_COST = 20 / 2.35; - double LADDER_DOWN_ONE_COST = 20 / 3.0; - double SNEAK_ONE_BLOCK_COST = 20 / 1.3; + double LADDER_UP_ONE_COST = 20 / 2.35; // 8.511 + double LADDER_DOWN_ONE_COST = 20 / 3.0; // 6.667 + double SNEAK_ONE_BLOCK_COST = 20 / 1.3; // 15.385 double SPRINT_ONE_BLOCK_COST = 20 / 5.612; // 3.564 + double SPRINT_MULTIPLIER = SPRINT_ONE_BLOCK_COST / WALK_ONE_BLOCK_COST; // 0.769 /** * To walk off an edge you need to walk 0.5 to the edge then 0.3 to start falling off */ - double WALK_OFF_BLOCK_COST = WALK_ONE_BLOCK_COST * 0.8; + double WALK_OFF_BLOCK_COST = WALK_ONE_BLOCK_COST * 0.8; // 3.706 /** * To walk the rest of the way to be centered on the new block */ - double CENTER_AFTER_FALL_COST = WALK_ONE_BLOCK_COST - WALK_OFF_BLOCK_COST; + double CENTER_AFTER_FALL_COST = WALK_ONE_BLOCK_COST - WALK_OFF_BLOCK_COST; // 0.927 /** * don't make this Double.MAX_VALUE because it's added to other things, maybe other COST_INFs, diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 7519f801..454421c4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -117,19 +117,22 @@ public class MovementDiagonal extends Movement { return COST_INF; } } + boolean water = false; if (BlockStateInterface.isWater(BlockStateInterface.getBlock(x, y, z)) || BlockStateInterface.isWater(destInto.getBlock())) { // 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; + water = true; } 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 + if (context.canSprint() && !water) { + // If we aren't edging around anything, and we aren't in water // We can sprint =D - multiplier = SPRINT_ONE_BLOCK_COST; + // Don't check for soul sand, since we can sprint on that too + multiplier *= SPRINT_MULTIPLIER; } return multiplier * SQRT_2; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index a16a50a1..72bfa526 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -67,8 +67,10 @@ public class MovementTraverse extends Movement { Block srcDown = BlockStateInterface.getBlock(x, y - 1, z); if (MovementHelper.canWalkOn(destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge double WC = WALK_ONE_BLOCK_COST; + boolean water = false; if (BlockStateInterface.isWater(pb0.getBlock()) || BlockStateInterface.isWater(pb1.getBlock())) { WC = WALK_ONE_IN_WATER_COST; + water = true; } else { if (destOn.getBlock() == Blocks.SOUL_SAND) { WC += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2; @@ -83,10 +85,11 @@ public class MovementTraverse extends Movement { } double hardness2 = MovementHelper.getMiningDurationTicks(context, destX, y, destZ, pb1, false); if (hardness1 == 0 && hardness2 == 0) { - 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 + if (!water && context.canSprint()) { + // If there's nothing in the way, and this isn't water, and we aren't sneak placing // We can sprint =D - WC = SPRINT_ONE_BLOCK_COST; + // Don't check for soul sand, since we can sprint on that too + WC *= SPRINT_MULTIPLIER; } return WC; } From f338cdd2e5e5ce22268985a2316aec3fc8867c0c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 14:26:08 -0700 Subject: [PATCH 019/305] clear all keys including sprint in the next movement, fixes #194 --- src/main/java/baritone/pathing/path/PathExecutor.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 1d6da5a6..8852e279 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -336,6 +336,7 @@ public class PathExecutor implements Helper { if (canSprintInto(current, next)) { if (playerFeet().equals(current.getDest())) { pathPosition++; + clearKeys(); } if (!player().isSprinting()) { player().setSprinting(true); From b55a102d37008e1b7197003152797d01ccf4210c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 14:26:55 -0700 Subject: [PATCH 020/305] take depth strider into acocunt for water speed, fixes #101 --- .../pathing/movement/CalculationContext.java | 15 ++++++++++++++- .../movement/movements/MovementDiagonal.java | 2 +- .../movement/movements/MovementTraverse.java | 4 ++-- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 3149cfe9..ee4cb188 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -18,8 +18,10 @@ package baritone.pathing.movement; import baritone.Baritone; +import baritone.api.pathing.movement.ActionCosts; import baritone.utils.Helper; import baritone.utils.ToolSet; +import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; @@ -40,6 +42,7 @@ public class CalculationContext implements Helper { private final boolean allowBreak; private final int maxFallHeightNoWater; private final int maxFallHeightBucket; + private final double waterWalkSpeed; public CalculationContext() { this(new ToolSet()); @@ -54,13 +57,19 @@ public class CalculationContext implements Helper { this.allowBreak = Baritone.settings().allowBreak.get(); this.maxFallHeightNoWater = Baritone.settings().maxFallHeightNoWater.get(); this.maxFallHeightBucket = Baritone.settings().maxFallHeightBucket.get(); + int depth = EnchantmentHelper.getDepthStriderModifier(player()); + if (depth > 3) { + depth = 3; + } + float mult = depth / 3.0F; + this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - mult) + ActionCosts.WALK_ONE_BLOCK_COST * mult; // 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. } public ToolSet getToolSet() { - return this.toolSet; + return toolSet; } public boolean hasWaterBucket() { @@ -91,4 +100,8 @@ public class CalculationContext implements Helper { return maxFallHeightBucket; } + public double waterWalkSpeed() { + return waterWalkSpeed; + } + } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 454421c4..a1e68dfe 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -122,7 +122,7 @@ public class MovementDiagonal extends Movement { // 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; + multiplier = context.waterWalkSpeed(); water = true; } if (optionA != 0 || optionB != 0) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 72bfa526..26952b02 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -69,7 +69,7 @@ public class MovementTraverse extends Movement { double WC = WALK_ONE_BLOCK_COST; boolean water = false; if (BlockStateInterface.isWater(pb0.getBlock()) || BlockStateInterface.isWater(pb1.getBlock())) { - WC = WALK_ONE_IN_WATER_COST; + WC = context.waterWalkSpeed(); water = true; } else { if (destOn.getBlock() == Blocks.SOUL_SAND) { @@ -116,7 +116,7 @@ public class MovementTraverse extends Movement { } double hardness2 = MovementHelper.getMiningDurationTicks(context, destX, y + 1, destZ, pb1, true); - double WC = throughWater ? WALK_ONE_IN_WATER_COST : WALK_ONE_BLOCK_COST; + double WC = throughWater ? context.waterWalkSpeed() : WALK_ONE_BLOCK_COST; for (int i = 0; i < 4; i++) { int againstX = destX + HORIZONTALS[i].getXOffset(); int againstZ = destZ + HORIZONTALS[i].getZOffset(); From 6db31cbe74cb1749dcd6ebc91212d298f800a41a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 14:37:01 -0700 Subject: [PATCH 021/305] now that that's fixed, we can tighten the maximum time again --- src/main/java/baritone/utils/BaritoneAutoTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index 27b9bfb3..faad6153 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -41,7 +41,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { private static final long TEST_SEED = -928872506371745L; private static final BlockPos STARTING_POSITION = new BlockPos(0, 65, 0); private static final Goal GOAL = new GoalBlock(69, 121, 420); - private static final int MAX_TICKS = 4000; + private static final int MAX_TICKS = 3500; /** * Called right after the {@link GameSettings} object is created in the {@link Minecraft} instance. From 41ffd4455dce9e63b3fc697df3204ece01fe9145 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 14:50:20 -0700 Subject: [PATCH 022/305] don't cancel for any reason while doing a water bucket fall, fixes #98, fixes #123 --- src/main/java/baritone/pathing/movement/Movement.java | 8 ++++++++ .../baritone/pathing/movement/movements/MovementFall.java | 5 +++++ src/main/java/baritone/pathing/path/PathExecutor.java | 7 ++++--- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 21341fa4..b952e547 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -187,6 +187,14 @@ public abstract class Movement implements Helper, MovementHelper { return true; } + public boolean safeToCancel() { + return safeToCancel(currentState); + } + + protected boolean safeToCancel(MovementState currentState) { + return false; + } + public boolean isFinished() { return (currentState.getStatus() != MovementStatus.RUNNING && currentState.getStatus() != MovementStatus.PREPPING diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 0f165f6f..1cfd451f 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -111,6 +111,11 @@ public class MovementFall extends Movement { return state; } + @Override + public boolean safeToCancel(MovementState state) { + return state.getStatus() != MovementStatus.RUNNING; + } + private static BetterBlockPos[] buildPositionsToBreak(BetterBlockPos src, BetterBlockPos dest) { BetterBlockPos[] toBreak; int diffX = src.getX() - dest.getX(); diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 8852e279..8dcdb159 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -221,12 +221,13 @@ public class PathExecutor implements Helper { System.out.println("Recalculating break and place took " + (end - start) + "ms"); } Movement movement = path.movements().get(pathPosition); + boolean canCancel = movement.safeToCancel(); 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 currentMovementOriginalCostEstimate = 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) { + if (path.movements().get(pathPosition + i).calculateCostWithoutCaching() >= ActionCosts.COST_INF && canCancel) { logDebug("Something has changed in the world and a future movement has become impossible. Cancelling."); cancel(); return true; @@ -234,12 +235,12 @@ public class PathExecutor implements Helper { } } double currentCost = movement.recalculateCost(); - if (currentCost >= ActionCosts.COST_INF) { + if (currentCost >= ActionCosts.COST_INF && canCancel) { logDebug("Something has changed in the world and this movement has become impossible. Cancelling."); cancel(); return true; } - if (!movement.calculatedWhileLoaded() && currentCost - currentMovementOriginalCostEstimate > Baritone.settings().maxCostIncrease.get()) { + if (!movement.calculatedWhileLoaded() && currentCost - currentMovementOriginalCostEstimate > Baritone.settings().maxCostIncrease.get() && canCancel) { logDebug("Original cost " + currentMovementOriginalCostEstimate + " current cost " + currentCost + ". Cancelling."); cancel(); return true; From 023822b5d96a571014e7d721343409e14d03de9d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 15:11:52 -0700 Subject: [PATCH 023/305] stop breaking block on cancel, even if not requested by player --- src/main/java/baritone/pathing/path/PathExecutor.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 8dcdb159..d73cd9ad 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -25,10 +25,7 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.pathing.movement.movements.*; -import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; -import baritone.utils.InputOverrideHandler; -import baritone.utils.Utils; +import baritone.utils.*; import baritone.utils.pathing.BetterBlockPos; import net.minecraft.init.Blocks; import net.minecraft.util.Tuple; @@ -386,6 +383,7 @@ public class PathExecutor implements Helper { private void cancel() { clearKeys(); + BlockBreakHelper.stopBreakingBlock(); pathPosition = path.length() + 3; failed = true; } From 1cc03e3aca26d0c04ed64b1069c327eda725a2cc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 15:20:52 -0700 Subject: [PATCH 024/305] it doesn't actually have to be falling, it just has to be solid --- .../pathing/movement/movements/MovementAscend.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 6d313c48..d01dd9e1 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -101,14 +101,15 @@ public class MovementAscend extends Movement { // 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 - if (!(BlockStateInterface.getBlock(x, y + 1, z) instanceof BlockFalling) || !((srcUp2 = BlockStateInterface.get(x, y + 2, z)).getBlock() instanceof BlockFalling)) { - // if both of those are BlockFalling, that means that by standing on src + if (MovementHelper.canWalkThrough(x, y + 1, z) || !((srcUp2 = BlockStateInterface.get(x, y + 2, z)).getBlock() instanceof BlockFalling)) { + // if the lower one is can't walk through and the upper one is falling, that means that by standing on src // (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 + // as in, if we have a block, then two BlockFallings on top of it + // and that block is x, y+1, z, and we'd have to clear it to even start this movement + // we don't need to worry about those BlockFallings because we've already cleared them return COST_INF; } // you may think we only need to check srcUp2, not srcUp From 8f146d1a2b6af0839cb8b89bcd96370db41295a1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 15:35:18 -0700 Subject: [PATCH 025/305] increase degree of backtrack cost favoring --- src/api/java/baritone/api/Settings.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 15ae9eee..c14e2817 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -149,7 +149,7 @@ public class Settings { * * @see Issue #18 */ - public Setting backtrackCostFavoringCoefficient = new Setting<>(0.9); + public Setting backtrackCostFavoringCoefficient = new Setting<>(0.1); /** * Don't repropagate cost improvements below 0.01 ticks. They're all just floating point inaccuracies, From 07eee481cbd5427f4dbe3c753de7dab91f45d593 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 15:42:16 -0700 Subject: [PATCH 026/305] fix failure on repeated descend --- .../java/baritone/pathing/path/PathExecutor.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index d73cd9ad..523b98b0 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -111,7 +111,7 @@ public class PathExecutor implements Helper { for (int j = pathPosition; j <= previousPos; j++) { path.movements().get(j).reset(); } - clearKeys(); + onChangeInPathPosition(); return false; } } @@ -122,7 +122,7 @@ public class PathExecutor implements Helper { } System.out.println("Double skip sundae"); pathPosition = i - 1; - clearKeys(); + onChangeInPathPosition(); return false; } } @@ -251,8 +251,7 @@ public class PathExecutor implements Helper { if (movementStatus == SUCCESS) { //System.out.println("Movement done, next path"); pathPosition++; - ticksOnCurrent = 0; - clearKeys(); + onChangeInPathPosition(); onTick(event); return true; } else { @@ -328,13 +327,14 @@ public class PathExecutor implements Helper { player().setSprinting(true); } pathPosition++; + // okay to skip clearKeys and / or onChangeInPathPosition here since this isn't possible to repeat, since it's asymmetric logDebug("Skipping descend to straight ascend"); return; } if (canSprintInto(current, next)) { if (playerFeet().equals(current.getDest())) { pathPosition++; - clearKeys(); + onChangeInPathPosition(); } if (!player().isSprinting()) { player().setSprinting(true); @@ -376,6 +376,11 @@ public class PathExecutor implements Helper { return false; } + private void onChangeInPathPosition() { + clearKeys(); + ticksOnCurrent = 0; + } + private static void clearKeys() { // i'm just sick and tired of this snippet being everywhere lol Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys(); From 4e11d92d19561d77c4c9175a0d400a581efec8c4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 19:23:13 -0700 Subject: [PATCH 027/305] fix parkour cost calculation --- .../baritone/pathing/movement/movements/MovementParkour.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 43391b01..7124b5f3 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -122,7 +122,7 @@ public class MovementParkour extends Movement { continue; } if (MovementHelper.canPlaceAgainst(againstX, y - 1, againstZ)) { - return new MoveResult(destX, y, destZ, costFromJumpDistance(i) + context.placeBlockCost()); + return new MoveResult(destX, y, destZ, costFromJumpDistance(4) + context.placeBlockCost()); } } return IMPOSSIBLE; @@ -137,7 +137,7 @@ public class MovementParkour extends Movement { case 4: return SPRINT_ONE_BLOCK_COST * 4; default: - throw new IllegalStateException("LOL"); + throw new IllegalStateException("LOL " + dist); } } From f0c3e59a6fc085e0c6fd734e2f4c162895f26be6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Oct 2018 22:50:51 -0700 Subject: [PATCH 028/305] move from todo to issue --- src/main/java/baritone/behavior/PathingBehavior.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index f903dfbd..8e115240 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -341,7 +341,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, pos = ((IGoalRenderPos) goal).getGoalPos(); } - // TODO simplify each individual goal in a GoalComposite if (pos != null && world().getChunk(pos) instanceof EmptyChunk) { logDebug("Simplifying " + goal.toString().split("\\{")[0] + " to GoalXZ due to distance"); goal = new GoalXZ(pos.getX(), pos.getZ()); From 2867e0626fb5e02da78519f2746cf0dc7d8b4687 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 2 Oct 2018 09:59:07 -0700 Subject: [PATCH 029/305] reenable diagonal through water --- .../baritone/pathing/movement/movements/MovementDiagonal.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index a1e68dfe..58027a8d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -102,7 +102,7 @@ public class MovementDiagonal extends Movement { IBlockState pb3 = BlockStateInterface.get(destX, y + 1, z); if (optionA == 0) { // at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction - if (MovementHelper.avoidWalkingInto(pb2.getBlock()) || MovementHelper.avoidWalkingInto(pb3.getBlock())) { + if ((MovementHelper.avoidWalkingInto(pb2.getBlock()) && pb2.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb3.getBlock()) && pb3.getBlock() != Blocks.WATER)) { return COST_INF; } } @@ -113,7 +113,7 @@ public class MovementDiagonal extends Movement { } if (optionB == 0) { // and now that option B is fully calculated, see if we can edge around that way - if (MovementHelper.avoidWalkingInto(pb0.getBlock()) || MovementHelper.avoidWalkingInto(pb1.getBlock())) { + if ((MovementHelper.avoidWalkingInto(pb0.getBlock()) && pb0.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb1.getBlock()) && pb1.getBlock() != Blocks.WATER)) { return COST_INF; } } From 24be1d0ff3a48583d310931dc9efb49e7db778e3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 2 Oct 2018 10:01:54 -0700 Subject: [PATCH 030/305] lookahead a little more --- src/api/java/baritone/api/Settings.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index c14e2817..cbbe5839 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -191,7 +191,7 @@ public class Settings { /** * Start planning the next path once the remaining movements tick estimates sum up to less than this value */ - public Setting planningTickLookAhead = new Setting<>(100); + public Setting planningTickLookAhead = new Setting<>(150); /** * Default size of the Long2ObjectOpenHashMap used in pathing From 6fd7b2a7f384cb309321590171a024f8e89dd00d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 2 Oct 2018 10:17:56 -0700 Subject: [PATCH 031/305] fix proguard for service provider --- scripts/build.sh | 4 ---- scripts/proguard.pro | 11 ++++++++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/scripts/build.sh b/scripts/build.sh index a224a884..e2f9b01f 100644 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -11,10 +11,6 @@ echo "-libraryjars '$(java -verbose 2>/dev/null | sed -ne '1 s/\[Opened \(.*\)\] tail api.pro # debug, print out what the previous two commands generated cat api.pro | grep -v "\-keep class baritone.api" > standalone.pro # standalone doesn't keep baritone api -#wget -nv https://www.dropbox.com/s/zmc2l3jnwdvzvak/tempLibraries.zip?dl=1 # i'm sorry -#mv tempLibraries.zip?dl=1 tempLibraries.zip -#unzip tempLibraries.zip - #instead of downloading these jars from my dropbox in a zip, just assume gradle's already got them for us mkdir -p tempLibraries cat ../../scripts/proguard.pro | grep tempLibraries | grep .jar | cut -d "/" -f 2- | cut -d "'" -f -1 | xargs -n1 -I{} bash -c "find ~/.gradle -name {}" | tee /dev/stderr | xargs -n1 -I{} cp {} tempLibraries diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 28120808..b0f4a5f9 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -16,10 +16,8 @@ -flattenpackagehierarchy -repackageclasses 'baritone' -#-keep class baritone.behavior.** { *; } -keep class baritone.api.** { *; } -#-keep class baritone.* { *; } -#-keep class baritone.pathing.goals.** { *; } +-keep class baritone.BaritoneProvider # setting names are reflected from field names, so keep field names -keepclassmembers class baritone.api.Settings { @@ -58,8 +56,15 @@ -libraryjars 'tempLibraries/librarylwjglopenal-20100824.jar' -libraryjars 'tempLibraries/log4j-api-2.8.1.jar' -libraryjars 'tempLibraries/log4j-core-2.8.1.jar' + +# linux / travis -libraryjars 'tempLibraries/lwjgl-2.9.4-nightly-20150209.jar' -libraryjars 'tempLibraries/lwjgl_util-2.9.4-nightly-20150209.jar' + +# mac +#-libraryjars 'tempLibraries/lwjgl_util-2.9.2-nightly-20140822.jar' +#-libraryjars 'tempLibraries/lwjgl-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' From 85e4a57c761ec7f7142911b61ac379d465874e12 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 2 Oct 2018 10:19:14 -0700 Subject: [PATCH 032/305] no longer needed since goal is in api which in unobfed --- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 8e115240..9c09533f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -342,7 +342,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } if (pos != null && world().getChunk(pos) instanceof EmptyChunk) { - logDebug("Simplifying " + goal.toString().split("\\{")[0] + " to GoalXZ due to distance"); + logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance"); goal = new GoalXZ(pos.getX(), pos.getZ()); } } From 7e7b9f4fdb3d98aff15dc492131f2a127b082bdd Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 2 Oct 2018 15:25:58 -0500 Subject: [PATCH 033/305] Make MemoryBehavior store data by world --- .../api/behavior/IMemoryBehavior.java | 9 ++++ .../baritone/behavior/MemoryBehavior.java | 54 ++++++++++++------- 2 files changed, 45 insertions(+), 18 deletions(-) diff --git a/src/api/java/baritone/api/behavior/IMemoryBehavior.java b/src/api/java/baritone/api/behavior/IMemoryBehavior.java index ea5e9007..6b6df1dd 100644 --- a/src/api/java/baritone/api/behavior/IMemoryBehavior.java +++ b/src/api/java/baritone/api/behavior/IMemoryBehavior.java @@ -20,6 +20,8 @@ package baritone.api.behavior; import baritone.api.behavior.memory.IRememberedInventory; import net.minecraft.util.math.BlockPos; +import java.util.Map; + /** * @author Brady * @since 9/23/2018 @@ -33,4 +35,11 @@ public interface IMemoryBehavior extends IBehavior { * @return The remembered inventory */ IRememberedInventory getInventoryByPos(BlockPos pos); + + /** + * Gets the map of all block positions to their remembered inventories. + * + * @return Map of block positions to their respective remembered inventories + */ + Map getRememberedInventories(); } diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index b0980322..6570cbc2 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -19,9 +19,11 @@ package baritone.behavior; import baritone.api.behavior.IMemoryBehavior; import baritone.api.behavior.memory.IRememberedInventory; +import baritone.api.cache.IWorldData; import baritone.api.event.events.PacketEvent; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.type.EventState; +import baritone.cache.WorldProvider; import baritone.utils.Helper; import net.minecraft.item.ItemStack; import net.minecraft.network.Packet; @@ -43,15 +45,7 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H public static MemoryBehavior INSTANCE = new MemoryBehavior(); - /** - * Possible future inventories that we will be able to remember - */ - private final List futureInventories = new ArrayList<>(); - - /** - * The current remembered inventories - */ - private final Map rememberedInventories = new HashMap<>(); + private final Map worldDataContainers = new HashMap<>(); private MemoryBehavior() {} @@ -78,7 +72,7 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H TileEntityLockable lockable = (TileEntityLockable) tileEntity; int size = lockable.getSizeInventory(); - this.futureInventories.add(new FutureInventory(System.nanoTime() / 1000000L, size, lockable.getGuiID(), tileEntity.getPos())); + this.getCurrentContainer().futureInventories.add(new FutureInventory(System.nanoTime() / 1000000L, size, lockable.getGuiID(), tileEntity.getPos())); } } @@ -96,17 +90,19 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H if (p instanceof SPacketOpenWindow) { 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); + WorldDataContainer container = this.getCurrentContainer(); - this.futureInventories.stream() + // Remove any entries that were created over a second ago, this should make up for INSANE latency + container.futureInventories.removeIf(i -> System.nanoTime() / 1000000L - i.time > 1000); + + container.futureInventories.stream() .filter(i -> i.type.equals(packet.getGuiId()) && i.slots == packet.getSlotCount()) .findFirst().ifPresent(matched -> { // Remove the future inventory - this.futureInventories.remove(matched); + container.futureInventories.remove(matched); // Setup the remembered inventory - RememberedInventory inventory = this.rememberedInventories.computeIfAbsent(matched.pos, pos -> new RememberedInventory()); + RememberedInventory inventory = container.rememberedInventories.computeIfAbsent(matched.pos, pos -> new RememberedInventory()); inventory.windowId = packet.getWindowId(); inventory.size = packet.getSlotCount(); }); @@ -119,7 +115,7 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H } private Optional getInventoryFromWindow(int windowId) { - return this.rememberedInventories.values().stream().filter(i -> i.windowId == windowId).findFirst(); + return this.getCurrentContainer().rememberedInventories.values().stream().filter(i -> i.windowId == windowId).findFirst(); } private void updateInventory() { @@ -129,9 +125,31 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H }); } + private WorldDataContainer getCurrentContainer() { + return this.worldDataContainers.computeIfAbsent(WorldProvider.INSTANCE.getCurrentWorld(), data -> new WorldDataContainer()); + } + @Override public final RememberedInventory getInventoryByPos(BlockPos pos) { - return this.rememberedInventories.get(pos); + return this.getCurrentContainer().rememberedInventories.get(pos); + } + + @Override + public final Map getRememberedInventories() { + return Collections.unmodifiableMap(this.getCurrentContainer().rememberedInventories); + } + + private static final class WorldDataContainer { + + /** + * Possible future inventories that we will be able to remember + */ + private final List futureInventories = new ArrayList<>(); + + /** + * The current remembered inventories + */ + private final Map rememberedInventories = new HashMap<>(); } /** @@ -170,7 +188,7 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H /** * An inventory that we are aware of. *

- * Associated with a {@link BlockPos} in {@link MemoryBehavior#rememberedInventories}. + * Associated with a {@link BlockPos} in {@link WorldDataContainer#rememberedInventories}. */ public static class RememberedInventory implements IRememberedInventory { From 02a04773c6aadf4b94acb6adacff15f2b60b066f Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 2 Oct 2018 15:27:25 -0500 Subject: [PATCH 034/305] bad javadocs --- .../java/baritone/api/IBaritoneProvider.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index 03b457bb..52dae153 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -26,15 +26,45 @@ import baritone.api.cache.IWorldProvider; */ public interface IBaritoneProvider { + /** + * @see IFollowBehavior + * + * @return The {@link IFollowBehavior} instance + */ IFollowBehavior getFollowBehavior(); + /** + * @see ILookBehavior + * + * @return The {@link ILookBehavior} instance + */ ILookBehavior getLookBehavior(); + /** + * @see IMemoryBehavior + * + * @return The {@link IMemoryBehavior} instance + */ IMemoryBehavior getMemoryBehavior(); + /** + * @see IMineBehavior + * + * @return The {@link IMineBehavior} instance + */ IMineBehavior getMineBehavior(); + /** + * @see IPathingBehavior + * + * @return The {@link IPathingBehavior} instance + */ IPathingBehavior getPathingBehavior(); + /** + * @see IWorldProvider + * + * @return The {@link IWorldProvider} instance + */ IWorldProvider getWorldProvider(); } From feeeae59180c533da54aa423534f6007f25c1a2e Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 2 Oct 2018 15:28:20 -0500 Subject: [PATCH 035/305] Add autotest directory to gitignore If you're not using "autotest" as ur auto test "testing" directory, you SHOULD. --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 564974df..74dc7ea2 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ **/*.swp run/ +autotest/ # Gradle build/ From da137f35de575bd91e7d5aba111d7576f724b4e4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 2 Oct 2018 14:04:24 -0700 Subject: [PATCH 036/305] fix parkour jumps ending on lilypads, fixes #203 --- .../baritone/pathing/movement/movements/MovementParkour.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 7124b5f3..4d2ef63d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -162,7 +162,7 @@ public class MovementParkour extends Movement { } MovementHelper.moveTowards(state, dest); if (playerFeet().equals(dest)) { - if (player().posY - playerFeet().getY() < 0.01) { + if (player().posY - playerFeet().getY() < 0.094) { // lilypads state.setStatus(MovementState.MovementStatus.SUCCESS); } } else if (!playerFeet().equals(src)) { From baf27363aaf736c82ddaac04a7f2ade36464ec18 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 2 Oct 2018 15:02:27 -0700 Subject: [PATCH 037/305] fix movement ascend x z cardinal asymmetry, fixes #204 --- .../baritone/pathing/movement/movements/MovementAscend.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index d01dd9e1..b5e21eea 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -71,7 +71,7 @@ public class MovementAscend extends Movement { return COST_INF;// the only thing we can ascend onto from a bottom slab is another bottom slab } boolean hasToPlace = false; - if (!MovementHelper.canWalkOn(destX, y, z, toPlace)) { + if (!MovementHelper.canWalkOn(destX, y, destZ, toPlace)) { if (!context.hasThrowaway()) { return COST_INF; } From 3fdc4d6ee0db66ee4240d58dcf1c77c4e20336cd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 2 Oct 2018 15:34:46 -0700 Subject: [PATCH 038/305] parkour jumping onto a vine, sort of --- .../pathing/movement/movements/MovementParkour.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 4d2ef63d..9272b7fc 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -28,6 +28,7 @@ import baritone.utils.InputOverrideHandler; import baritone.utils.Utils; import baritone.utils.pathing.BetterBlockPos; import baritone.utils.pathing.MoveResult; +import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; @@ -162,6 +163,12 @@ public class MovementParkour extends Movement { } MovementHelper.moveTowards(state, dest); if (playerFeet().equals(dest)) { + Block d = BlockStateInterface.getBlock(dest); + if (d == Blocks.VINE || d == Blocks.LADDER) { + // it physically hurt me to add support for parkour jumping onto a vine + // but i did it anyway + return state.setStatus(MovementState.MovementStatus.SUCCESS); + } if (player().posY - playerFeet().getY() < 0.094) { // lilypads state.setStatus(MovementState.MovementStatus.SUCCESS); } From 38895beb5dfc8cfaf6904c8c42fc0899891474a5 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 2 Oct 2018 17:15:00 -0700 Subject: [PATCH 039/305] remove width and height override part 2: electric boogaloo --- Dockerfile | 2 -- 1 file changed, 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index b36b3770..7f5b0199 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,8 +17,6 @@ RUN apt install -qq --force-yes unzip wget COPY . /code -RUN echo "\nrunClient {\nargs \"--width\",\"128\",\"--height\",\"128\"\n}" >> /code/build.gradle - # this .deb is specially patched to support lwjgl # source: https://github.com/tectonicus/tectonicus/issues/60#issuecomment-154239173 RUN dpkg -i /code/scripts/xvfb_1.16.4-1_amd64.deb From 04d210bd8bd6279dfe0fd8cec2b4687aba147f5d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Oct 2018 07:43:45 -0700 Subject: [PATCH 040/305] no need to calculate the hash on contstruction anymore --- .../baritone/behavior/PathingBehavior.java | 22 ++++++++++--------- .../utils/pathing/BetterBlockPos.java | 11 +++++----- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 9c09533f..f10a15cd 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -352,7 +352,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } else { timeout = Baritone.settings().planAheadTimeoutMS.get(); } - Optional> favoredPositions = previous.map(IPath::positions).map(Collection::stream).map(x -> x.map(y -> y.hashCode)).map(x -> x.collect(Collectors.toList())).map(HashSet::new); // <-- okay this is EPIC + Optional> favoredPositions = previous.map(IPath::positions).map(Collection::stream).map(x -> x.map(BetterBlockPos::longHash)).map(x -> x.collect(Collectors.toList())).map(HashSet::new); // <-- okay this is EPIC try { IPathFinder pf = new AStarPathFinder(start, goal, favoredPositions); return pf.calculate(timeout); @@ -367,15 +367,17 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, if (!Baritone.settings().cancelOnGoalInvalidation.get()) { return; } - if (current == null || goal == null) { - return; - } - Goal intended = current.getPath().getGoal(); - BlockPos end = current.getPath().getDest(); - if (intended.isInGoal(end) && !goal.isInGoal(end)) { - // this path used to end in the goal - // but the goal has changed, so there's no reason to continue... - cancel(); + synchronized (pathPlanLock) { + if (current == null || goal == null) { + return; + } + Goal intended = current.getPath().getGoal(); + BlockPos end = current.getPath().getDest(); + if (intended.isInGoal(end) && !goal.isInGoal(end)) { + // this path used to end in the goal + // but the goal has changed, so there's no reason to continue... + cancel(); + } } } diff --git a/src/main/java/baritone/utils/pathing/BetterBlockPos.java b/src/main/java/baritone/utils/pathing/BetterBlockPos.java index 7aed17c6..e81319db 100644 --- a/src/main/java/baritone/utils/pathing/BetterBlockPos.java +++ b/src/main/java/baritone/utils/pathing/BetterBlockPos.java @@ -36,14 +36,12 @@ public final class BetterBlockPos extends BlockPos { public final int x; public final int y; public final int z; - public final long hashCode; public BetterBlockPos(int x, int y, int z) { super(x, y, z); this.x = x; this.y = y; this.z = z; - this.hashCode = AbstractNodeCostSearch.posHash(x, y, z); } public BetterBlockPos(double x, double y, double z) { @@ -56,7 +54,11 @@ public final class BetterBlockPos extends BlockPos { @Override public int hashCode() { - return (int) hashCode; + return (int) AbstractNodeCostSearch.posHash(x, y, z); + } + + public static long longHash(BetterBlockPos pos) { + return AbstractNodeCostSearch.posHash(pos.x, pos.y, pos.z); } @Override @@ -66,9 +68,6 @@ public final class BetterBlockPos extends BlockPos { } 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)) {" From cd926283b3308bcb3926c29026ffabc252abc492 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Oct 2018 07:48:26 -0700 Subject: [PATCH 041/305] avoid synthetic lambda creation --- src/main/java/baritone/utils/ToolSet.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 62115f24..962ffb08 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -67,7 +67,14 @@ public class ToolSet implements Helper { * @return how long it would take in ticks */ public double getStrVsBlock(IBlockState state) { - return this.breakStrengthCache.computeIfAbsent(state.getBlock(), b -> calculateStrVsBlock(getBestSlot(state), state)); + Double strength = this.breakStrengthCache.get(state.getBlock()); + if (strength != null) { + // the function will take this path >99% of the time + return strength; + } + double str = calculateStrVsBlock(getBestSlot(state), state); + this.breakStrengthCache.put(state.getBlock(), str); + return str; } /** From 1ee44024b2e0a5d06c5ef93b401e7643cdc40029 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Oct 2018 07:52:17 -0700 Subject: [PATCH 042/305] don't construct favored positions hashset if the coefficient renders it useless --- src/main/java/baritone/behavior/PathingBehavior.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index f10a15cd..14b8db26 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -352,7 +352,12 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } else { timeout = Baritone.settings().planAheadTimeoutMS.get(); } - Optional> favoredPositions = previous.map(IPath::positions).map(Collection::stream).map(x -> x.map(BetterBlockPos::longHash)).map(x -> x.collect(Collectors.toList())).map(HashSet::new); // <-- okay this is EPIC + Optional> favoredPositions; + if (Baritone.settings().backtrackCostFavoringCoefficient.get() == 1D) { + favoredPositions = Optional.empty(); + } else { + favoredPositions = previous.map(IPath::positions).map(Collection::stream).map(x -> x.map(BetterBlockPos::longHash)).map(x -> x.collect(Collectors.toList())).map(HashSet::new); // <-- okay this is EPIC + } try { IPathFinder pf = new AStarPathFinder(start, goal, favoredPositions); return pf.calculate(timeout); From 36bdaa99ecf5be60bdd99898bf767443053142d3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Oct 2018 07:57:24 -0700 Subject: [PATCH 043/305] DAE BlockPos bad? --- .../baritone/behavior/PathingBehavior.java | 2 +- .../pathing/calc/AStarPathFinder.java | 7 +++-- .../pathing/calc/AbstractNodeCostSearch.java | 27 +++++++++---------- .../baritone/pathing/calc/IPathFinder.java | 3 --- 4 files changed, 16 insertions(+), 23 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 14b8db26..15748432 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -359,7 +359,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, favoredPositions = previous.map(IPath::positions).map(Collection::stream).map(x -> x.map(BetterBlockPos::longHash)).map(x -> x.collect(Collectors.toList())).map(HashSet::new); // <-- okay this is EPIC } try { - IPathFinder pf = new AStarPathFinder(start, goal, favoredPositions); + IPathFinder pf = new AStarPathFinder(start.getX(), start.getY(), start.getZ(), goal, favoredPositions); return pf.calculate(timeout); } catch (Exception e) { logDebug("Pathing exception: " + e); diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index c1d4cab8..aca23d0d 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -27,7 +27,6 @@ import baritone.pathing.path.IPath; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.pathing.MoveResult; -import net.minecraft.util.math.BlockPos; import java.util.HashSet; import java.util.Optional; @@ -41,14 +40,14 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel private final Optional> favoredPositions; - public AStarPathFinder(BlockPos start, Goal goal, Optional> favoredPositions) { - super(start, goal); + public AStarPathFinder(int startX, int startY, int startZ, Goal goal, Optional> favoredPositions) { + super(startX, startY, startZ, goal); this.favoredPositions = favoredPositions; } @Override protected Optional calculate0(long timeout) { - startNode = getNodeAtPosition(start.x, start.y, start.z, posHash(start.x, start.y, start.z)); + startNode = getNodeAtPosition(startX, startY, startZ, posHash(startX, startY, startZ)); startNode.cost = 0; startNode.combinedCost = startNode.estimatedCostToGoal; BinaryHeapOpenSet openSet = new BinaryHeapOpenSet(); diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 49e726b0..68a523fa 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -20,9 +20,7 @@ package baritone.pathing.calc; import baritone.Baritone; import baritone.api.pathing.goals.Goal; import baritone.pathing.path.IPath; -import baritone.utils.pathing.BetterBlockPos; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import net.minecraft.util.math.BlockPos; import java.util.Optional; @@ -38,7 +36,9 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { */ private static AbstractNodeCostSearch currentlyRunning = null; - protected final BetterBlockPos start; + protected final int startX; + protected final int startY; + protected final int startZ; protected final Goal goal; @@ -69,8 +69,10 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { */ protected final static double MIN_DIST_PATH = 5; - AbstractNodeCostSearch(BlockPos start, Goal goal) { - this.start = new BetterBlockPos(start.getX(), start.getY(), start.getZ()); + AbstractNodeCostSearch(int startX, int startY, int startZ, Goal goal) { + this.startX = startX; + this.startY = startY; + this.startZ = startZ; this.goal = goal; this.map = new Long2ObjectOpenHashMap<>(Baritone.settings().pathingMapDefaultSize.value, Baritone.settings().pathingMapLoadFactor.get()); } @@ -115,14 +117,14 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { * @return The distance, squared */ protected double getDistFromStartSq(PathNode n) { - int xDiff = n.x - start.x; - int yDiff = n.y - start.y; - int zDiff = n.z - start.z; + int xDiff = n.x - startX; + int yDiff = n.y - startY; + int zDiff = n.z - startZ; return xDiff * xDiff + yDiff * yDiff + zDiff * zDiff; } /** - * Attempts to search the {@link BlockPos} to {@link PathNode} map + * Attempts to search the block position hashCode long to {@link PathNode} map * for the node mapped to the specified pos. If no node is found, * a new node is created. * @@ -140,7 +142,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { public static long posHash(int x, int y, int z) { /* - * This is the hashcode implementation of Vec3i, the superclass of BlockPos + * This is the hashcode implementation of Vec3i (the superclass of the class which I shall not name) * * public int hashCode() { * return (this.getY() + this.getZ() * 31) * 31 + this.getX(); @@ -220,11 +222,6 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { return goal; } - @Override - public final BlockPos getStart() { - return start; - } - public static Optional getCurrentlyRunning() { return Optional.ofNullable(currentlyRunning); } diff --git a/src/main/java/baritone/pathing/calc/IPathFinder.java b/src/main/java/baritone/pathing/calc/IPathFinder.java index 6ed2b3a7..e6f3be06 100644 --- a/src/main/java/baritone/pathing/calc/IPathFinder.java +++ b/src/main/java/baritone/pathing/calc/IPathFinder.java @@ -19,7 +19,6 @@ package baritone.pathing.calc; import baritone.api.pathing.goals.Goal; import baritone.pathing.path.IPath; -import net.minecraft.util.math.BlockPos; import java.util.Optional; @@ -30,8 +29,6 @@ import java.util.Optional; */ public interface IPathFinder { - BlockPos getStart(); - Goal getGoal(); /** From 28af41b789a9551ec7d9ae21c129f3e14afdadca Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Oct 2018 08:04:30 -0700 Subject: [PATCH 044/305] defer movement propagation and assembly to postprocessing --- src/main/java/baritone/pathing/calc/Path.java | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 7f8cf085..72f1756c 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -86,11 +86,11 @@ class Path implements IPath { throw new IllegalStateException(); } PathNode current = end; - LinkedList tempPath = new LinkedList<>(); // Repeatedly inserting to the beginning of an arraylist is O(n^2) - LinkedList tempMovements = new LinkedList<>(); // Instead, do it into a linked list, then convert at the end + LinkedList tempPath = new LinkedList<>(); + // Repeatedly inserting to the beginning of an arraylist is O(n^2) + // Instead, do it into a linked list, then convert at the end while (!current.equals(start)) { tempPath.addFirst(new BetterBlockPos(current.x, current.y, current.z)); - tempMovements.addFirst(runBackwards(current.previous, current)); current = current.previous; } tempPath.addFirst(this.start); @@ -98,20 +98,6 @@ class Path implements IPath { // inserting into a LinkedList keeps track of length, then when we addall (which calls .toArray) it's able // to performantly do that conversion since it knows the length. path.addAll(tempPath); - movements.addAll(tempMovements); - } - - private static Movement runBackwards(PathNode src0, PathNode dest0) { // TODO this is horrifying - BetterBlockPos src = new BetterBlockPos(src0.x, src0.y, src0.z); - BetterBlockPos dest = new BetterBlockPos(dest0.x, dest0.y, dest0.z); - for (Moves moves : Moves.values()) { - Movement move = moves.apply0(src); - if (move.getDest().equals(dest)) { - return move; - } - } - // leave this as IllegalStateException; it's caught in AbstractNodeCostSearch - throw new IllegalStateException("Movement became impossible during calculation " + src + " " + dest + " " + dest.subtract(src)); } /** @@ -140,12 +126,33 @@ class Path implements IPath { } } + private void assembleMovements() { + if (path.isEmpty() || !movements.isEmpty()) { + throw new IllegalStateException(); + } + for (int i = 0; i < path.size() - 1; i++) { + movements.add(runBackwards(path.get(i), path.get(i + 1))); + } + } + + private static Movement runBackwards(BetterBlockPos src, BetterBlockPos dest) { // TODO this is horrifying + for (Moves moves : Moves.values()) { + Movement move = moves.apply0(src); + if (move.getDest().equals(dest)) { + return move; + } + } + // leave this as IllegalStateException; it's caught in AbstractNodeCostSearch + throw new IllegalStateException("Movement became impossible during calculation " + src + " " + dest + " " + dest.subtract(src)); + } + @Override public void postprocess() { if (verified) { throw new IllegalStateException(); } verified = true; + assembleMovements(); // more post processing here movements.forEach(Movement::checkLoadedChunk); sanityCheck(); From 6986f179cd8c050025dc1c7a43f5ef04ef64fd70 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Oct 2018 08:12:42 -0700 Subject: [PATCH 045/305] it's not much of an improvement, but it won't make it slower --- src/main/java/baritone/utils/PathRenderer.java | 14 ++++++++------ src/main/java/baritone/utils/Utils.java | 4 ---- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index a66bc0ae..bd49c5fe 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -22,8 +22,8 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.pathing.goals.GoalXZ; -import baritone.pathing.path.IPath; import baritone.api.utils.interfaces.IGoalRenderPos; +import baritone.pathing.path.IPath; import baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -49,7 +49,7 @@ import static org.lwjgl.opengl.GL11.*; * @since 8/9/2018 4:39 PM */ public final class PathRenderer implements Helper { - + private static final Tessellator TESSELLATOR = Tessellator.getInstance(); private static final BufferBuilder BUFFER = TESSELLATOR.getBuffer(); @@ -68,13 +68,15 @@ public final class PathRenderer implements Helper { int fadeStart = fadeStart0 + startIndex; int fadeEnd = fadeEnd0 + startIndex; for (int i = startIndex; i < positions.size() - 1; i = next) { - BlockPos start = positions.get(i); + BetterBlockPos start = positions.get(i); next = i + 1; - BlockPos end = positions.get(next); + BetterBlockPos end = positions.get(next); - BlockPos direction = Utils.diff(start, end); - while (next + 1 < positions.size() && (!fadeOut || next + 1 < fadeStart) && direction.equals(Utils.diff(end, positions.get(next + 1)))) { + int dirX = end.x - start.x; + int dirY = end.y - start.y; + int dirZ = end.z - start.z; + while (next + 1 < positions.size() && (!fadeOut || next + 1 < fadeStart) && (dirX == positions.get(next + 1).x - end.x && dirY == positions.get(next + 1).y - end.y && dirZ == positions.get(next + 1).z - end.z)) { next++; end = positions.get(next); } diff --git a/src/main/java/baritone/utils/Utils.java b/src/main/java/baritone/utils/Utils.java index 0de61461..a17aa577 100755 --- a/src/main/java/baritone/utils/Utils.java +++ b/src/main/java/baritone/utils/Utils.java @@ -130,8 +130,4 @@ public final class Utils { public static double radToDeg(double rad) { return rad * RAD_TO_DEG; } - - public static BlockPos diff(BlockPos a, BlockPos b) { - return new BlockPos(a.getX() - b.getX(), a.getY() - b.getY(), a.getZ() - b.getZ()); - } } From 1bd7c8455f13db67047efa0a861a744a86d9ce4f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Oct 2018 08:14:15 -0700 Subject: [PATCH 046/305] crucial performance optimization --- src/main/java/baritone/utils/PathRenderer.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index bd49c5fe..3f4dbe59 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -80,12 +80,12 @@ public final class PathRenderer implements Helper { next++; end = positions.get(next); } - double x1 = start.getX(); - double y1 = start.getY(); - double z1 = start.getZ(); - double x2 = end.getX(); - double y2 = end.getY(); - double z2 = end.getZ(); + double x1 = start.x; + double y1 = start.y; + double z1 = start.z; + double x2 = end.x; + double y2 = end.y; + double z2 = end.z; if (fadeOut) { float alpha; From 239bb14e3a9464cfef323bc3dfd88c9e37444b42 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Oct 2018 08:20:24 -0700 Subject: [PATCH 047/305] add blockBreakAdditionalPenalty --- src/api/java/baritone/api/Settings.java | 7 +++++++ .../java/baritone/pathing/movement/CalculationContext.java | 5 +++++ .../java/baritone/pathing/movement/MovementHelper.java | 1 + 3 files changed, 13 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index cbbe5839..00d4af85 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -56,6 +56,13 @@ public class Settings { */ public Setting blockPlacementPenalty = new Setting<>(20D); + /** + * This is just a tiebreaker to make it less likely to break blocks if it can avoid it. + * For example, fire has a break cost of 0, this makes it nonzero, so all else being equal + * it will take an otherwise equivalent route that doesn't require it to put out fire. + */ + public Setting blockBreakAdditionalPenalty = new Setting<>(2D); + /** * Allow Baritone to fall arbitrary distances and place a water bucket beneath it. * Reliability: questionable. diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index ee4cb188..0b40539e 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -43,6 +43,7 @@ public class CalculationContext implements Helper { private final int maxFallHeightNoWater; private final int maxFallHeightBucket; private final double waterWalkSpeed; + private final double breakBlockAdditionalCost; public CalculationContext() { this(new ToolSet()); @@ -63,6 +64,7 @@ public class CalculationContext implements Helper { } float mult = depth / 3.0F; this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - mult) + ActionCosts.WALK_ONE_BLOCK_COST * mult; + this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.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. @@ -104,4 +106,7 @@ public class CalculationContext implements Helper { return waterWalkSpeed; } + public double breakBlockAdditionalCost() { + return breakBlockAdditionalCost; + } } diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index d614e544..28b14e9e 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -374,6 +374,7 @@ public interface MovementHelper extends ActionCosts, Helper { } double result = m / strVsBlock; + result += context.breakBlockAdditionalCost(); if (includeFalling) { IBlockState above = BlockStateInterface.get(x, y + 1, z); if (above.getBlock() instanceof BlockFalling) { From 820c1085489fa16bd89882775739554753e0f290 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 3 Oct 2018 12:44:28 -0500 Subject: [PATCH 048/305] Add pause "command" in ExampleBaritoneControl --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 8ba5a8d2..f656e27f 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -480,5 +480,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper { event.cancel(); return; } + if (msg.equals("pause")) { + PathingBehavior.INSTANCE.toggle(); + return; + } } } From ee6e0b1784a1ca31e1b25ebe073e261e103a87ea Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 3 Oct 2018 12:45:57 -0500 Subject: [PATCH 049/305] Add message and actually cancel event --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index f656e27f..bbf024f9 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -481,7 +481,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return; } if (msg.equals("pause")) { - PathingBehavior.INSTANCE.toggle(); + boolean enabled = PathingBehavior.INSTANCE.toggle(); + logDirect("Pathing Behavior has " + (enabled ? "resumed" : "paused") + "."); + event.cancel(); return; } } From 4590b9f6dace6e3fb07acdd450b2b19fbd25e985 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Oct 2018 13:45:33 -0700 Subject: [PATCH 050/305] they say you are what you eat, but i don't remember eating a minecraft damn daniel mod --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index bbf024f9..cca6e3a2 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -486,5 +486,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper { event.cancel(); return; } + if (msg.equals("damn")) { + logDirect("daniel"); + return; + } } } From 39f415d4be151009029f440e99e4926630fe9e29 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Oct 2018 19:00:58 -0700 Subject: [PATCH 051/305] allowplace and allowparkourplace --- .../baritone/pathing/movement/movements/MovementParkour.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 9272b7fc..f88ad28f 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -24,6 +24,7 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; +import baritone.utils.Helper; import baritone.utils.InputOverrideHandler; import baritone.utils.Utils; import baritone.utils.pathing.BetterBlockPos; @@ -107,6 +108,10 @@ public class MovementParkour extends Movement { if (!Baritone.settings().allowParkourPlace.get()) { return IMPOSSIBLE; } + if (!Baritone.settings().allowPlace.get()) { + Helper.HELPER.logDirect("allowParkourPlace enabled but allowPlace disabled?"); + return IMPOSSIBLE; + } int destX = x + 4 * xDiff; int destZ = z + 4 * zDiff; IBlockState toPlace = BlockStateInterface.get(destX, y - 1, destZ); From c1af050fa64196293e1609f5b5b8f689fe4e7e67 Mon Sep 17 00:00:00 2001 From: leijurv Date: Thu, 4 Oct 2018 16:00:02 -0700 Subject: [PATCH 052/305] fix lilypad fall cost, fixes #207 --- .../baritone/pathing/movement/movements/MovementDescend.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 79d5a305..b4e41597 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -127,7 +127,9 @@ public class MovementDescend extends Movement { } IBlockState ontoBlock = BlockStateInterface.get(destX, newY, destZ); double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[fallHeight] + frontBreak; - if (ontoBlock.getBlock() == Blocks.WATER && !BlockStateInterface.isFlowing(ontoBlock)) { // TODO flowing check required here? + if (ontoBlock.getBlock() == Blocks.WATER && !BlockStateInterface.isFlowing(ontoBlock) && BlockStateInterface.getBlock(destX, newY + 1, destZ) != Blocks.WATERLILY) { // TODO flowing check required here? + // lilypads are canWalkThrough, but we can't end a fall that should be broken by water if it's covered by a lilypad + // however, don't return impossible in the lilypad scenario, because we could still jump right on it (water that's below a lilypad is canWalkOn so it works) if (Baritone.settings().assumeWalkOnWater.get()) { return IMPOSSIBLE; // TODO fix } From b720742f53e4539423ae4f2743e7a1fe9d1e16c1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 4 Oct 2018 21:28:34 -0700 Subject: [PATCH 053/305] render the goal block, fixes #166 --- .../baritone/pathing/movement/movements/MovementParkour.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index f88ad28f..178411fd 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -50,7 +50,7 @@ public class MovementParkour extends Movement { private final int dist; private MovementParkour(BetterBlockPos src, int dist, EnumFacing dir) { - super(src, src.offset(dir, dist), EMPTY); + super(src, src.offset(dir, dist), EMPTY, src.offset(dir, dist).down()); this.direction = dir; this.dist = dist; } From 4049c116d9bbbacb0337e298796f74327043d90c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Oct 2018 10:10:24 -0700 Subject: [PATCH 054/305] dynamicY and yOffset --- .../pathing/calc/AStarPathFinder.java | 3 ++ .../java/baritone/pathing/movement/Moves.java | 54 ++++++++++--------- 2 files changed, 32 insertions(+), 25 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index aca23d0d..64fd24b3 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -114,6 +114,9 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel if (!moves.dynamicXZ && (res.destX != newX || res.destZ != newZ)) { throw new IllegalStateException(moves + " " + res.destX + " " + newX + " " + res.destZ + " " + newZ); } + if (!moves.dynamicY && res.destY != currentNode.y + moves.yOffset) { + throw new IllegalStateException(moves + " " + res.destX + " " + newX + " " + res.destZ + " " + newZ); + } if (actionCost <= 0) { throw new IllegalStateException(moves + " calculated implausible cost " + actionCost); } diff --git a/src/main/java/baritone/pathing/movement/Moves.java b/src/main/java/baritone/pathing/movement/Moves.java index 6f49dfbd..80b27971 100644 --- a/src/main/java/baritone/pathing/movement/Moves.java +++ b/src/main/java/baritone/pathing/movement/Moves.java @@ -28,7 +28,7 @@ import net.minecraft.util.EnumFacing; * @author leijurv */ public enum Moves { - DOWNWARD(0, 0) { + DOWNWARD(0, -1, 0) { @Override public Movement apply0(BetterBlockPos src) { return new MovementDownward(src, src.down()); @@ -40,7 +40,7 @@ public enum Moves { } }, - PILLAR(0, 0) { + PILLAR(0, +1, 0) { @Override public Movement apply0(BetterBlockPos src) { return new MovementPillar(src, src.up()); @@ -52,7 +52,7 @@ public enum Moves { } }, - TRAVERSE_NORTH(0, -1) { + TRAVERSE_NORTH(0, 0, -1) { @Override public Movement apply0(BetterBlockPos src) { return new MovementTraverse(src, src.north()); @@ -64,7 +64,7 @@ public enum Moves { } }, - TRAVERSE_SOUTH(0, +1) { + TRAVERSE_SOUTH(0, 0, +1) { @Override public Movement apply0(BetterBlockPos src) { return new MovementTraverse(src, src.south()); @@ -76,7 +76,7 @@ public enum Moves { } }, - TRAVERSE_EAST(+1, 0) { + TRAVERSE_EAST(+1, 0, 0) { @Override public Movement apply0(BetterBlockPos src) { return new MovementTraverse(src, src.east()); @@ -88,7 +88,7 @@ public enum Moves { } }, - TRAVERSE_WEST(-1, 0) { + TRAVERSE_WEST(-1, 0, 0) { @Override public Movement apply0(BetterBlockPos src) { return new MovementTraverse(src, src.west()); @@ -100,7 +100,7 @@ public enum Moves { } }, - ASCEND_NORTH(0, -1) { + ASCEND_NORTH(0, +1, -1) { @Override public Movement apply0(BetterBlockPos src) { return new MovementAscend(src, new BetterBlockPos(src.x, src.y + 1, src.z - 1)); @@ -112,7 +112,7 @@ public enum Moves { } }, - ASCEND_SOUTH(0, +1) { + ASCEND_SOUTH(0, +1, +1) { @Override public Movement apply0(BetterBlockPos src) { return new MovementAscend(src, new BetterBlockPos(src.x, src.y + 1, src.z + 1)); @@ -124,7 +124,7 @@ public enum Moves { } }, - ASCEND_EAST(+1, 0) { + ASCEND_EAST(+1, +1, 0) { @Override public Movement apply0(BetterBlockPos src) { return new MovementAscend(src, new BetterBlockPos(src.x + 1, src.y + 1, src.z)); @@ -136,7 +136,7 @@ public enum Moves { } }, - ASCEND_WEST(-1, 0) { + ASCEND_WEST(-1, +1, 0) { @Override public Movement apply0(BetterBlockPos src) { return new MovementAscend(src, new BetterBlockPos(src.x - 1, src.y + 1, src.z)); @@ -148,7 +148,7 @@ public enum Moves { } }, - DESCEND_EAST(+1, 0) { + DESCEND_EAST(+1, 0, 0, false, true) { @Override public Movement apply0(BetterBlockPos src) { MoveResult res = apply(new CalculationContext(), src.x, src.y, src.z); @@ -165,7 +165,7 @@ public enum Moves { } }, - DESCEND_WEST(-1, 0) { + DESCEND_WEST(-1, 0, 0, false, true) { @Override public Movement apply0(BetterBlockPos src) { MoveResult res = apply(new CalculationContext(), src.x, src.y, src.z); @@ -182,7 +182,7 @@ public enum Moves { } }, - DESCEND_NORTH(0, -1) { + DESCEND_NORTH(0, 0, -1, false, true) { @Override public Movement apply0(BetterBlockPos src) { MoveResult res = apply(new CalculationContext(), src.x, src.y, src.z); @@ -199,7 +199,7 @@ public enum Moves { } }, - DESCEND_SOUTH(0, +1) { + DESCEND_SOUTH(0, 0, +1, false, true) { @Override public Movement apply0(BetterBlockPos src) { MoveResult res = apply(new CalculationContext(), src.x, src.y, src.z); @@ -216,7 +216,7 @@ public enum Moves { } }, - DIAGONAL_NORTHEAST(+1, -1) { + DIAGONAL_NORTHEAST(+1, 0, -1) { @Override public Movement apply0(BetterBlockPos src) { return new MovementDiagonal(src, EnumFacing.NORTH, EnumFacing.EAST); @@ -228,7 +228,7 @@ public enum Moves { } }, - DIAGONAL_NORTHWEST(-1, -1) { + DIAGONAL_NORTHWEST(-1, 0, -1) { @Override public Movement apply0(BetterBlockPos src) { return new MovementDiagonal(src, EnumFacing.NORTH, EnumFacing.WEST); @@ -240,7 +240,7 @@ public enum Moves { } }, - DIAGONAL_SOUTHEAST(+1, +1) { + DIAGONAL_SOUTHEAST(+1, 0, +1) { @Override public Movement apply0(BetterBlockPos src) { return new MovementDiagonal(src, EnumFacing.SOUTH, EnumFacing.EAST); @@ -252,7 +252,7 @@ public enum Moves { } }, - DIAGONAL_SOUTHWEST(-1, +1) { + DIAGONAL_SOUTHWEST(-1, 0, +1) { @Override public Movement apply0(BetterBlockPos src) { return new MovementDiagonal(src, EnumFacing.SOUTH, EnumFacing.WEST); @@ -264,7 +264,7 @@ public enum Moves { } }, - PARKOUR_NORTH(0, -4, true) { + PARKOUR_NORTH(0, 0, -4, true, false) { @Override public Movement apply0(BetterBlockPos src) { return MovementParkour.cost(new CalculationContext(), src, EnumFacing.NORTH); @@ -276,7 +276,7 @@ public enum Moves { } }, - PARKOUR_SOUTH(0, +4, true) { + PARKOUR_SOUTH(0, 0, +4, true, false) { @Override public Movement apply0(BetterBlockPos src) { return MovementParkour.cost(new CalculationContext(), src, EnumFacing.SOUTH); @@ -288,7 +288,7 @@ public enum Moves { } }, - PARKOUR_EAST(+4, 0, true) { + PARKOUR_EAST(+4, 0, 0, true, false) { @Override public Movement apply0(BetterBlockPos src) { return MovementParkour.cost(new CalculationContext(), src, EnumFacing.EAST); @@ -300,7 +300,7 @@ public enum Moves { } }, - PARKOUR_WEST(-4, 0, true) { + PARKOUR_WEST(-4, 0, 0, true, false) { @Override public Movement apply0(BetterBlockPos src) { return MovementParkour.cost(new CalculationContext(), src, EnumFacing.WEST); @@ -313,18 +313,22 @@ public enum Moves { }; public final boolean dynamicXZ; + public final boolean dynamicY; public final int xOffset; + public final int yOffset; public final int zOffset; - Moves(int x, int z, boolean dynamicXZ) { + Moves(int x, int y, int z, boolean dynamicXZ, boolean dynamicY) { this.xOffset = x; + this.yOffset = y; this.zOffset = z; this.dynamicXZ = dynamicXZ; + this.dynamicY = dynamicY; } - Moves(int x, int z) { - this(x, z, false); + Moves(int x, int y, int z) { + this(x, y, z, false, false); } public abstract Movement apply0(BetterBlockPos src); From 6fff4c52547d429d7ddfa3f22ccc34d5bcb1723b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Oct 2018 10:17:58 -0700 Subject: [PATCH 055/305] reduce repetition in Moves --- .../java/baritone/pathing/movement/Moves.java | 67 +++++++++++-------- 1 file changed, 38 insertions(+), 29 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/Moves.java b/src/main/java/baritone/pathing/movement/Moves.java index 80b27971..1a3f61ef 100644 --- a/src/main/java/baritone/pathing/movement/Moves.java +++ b/src/main/java/baritone/pathing/movement/Moves.java @@ -35,8 +35,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x, y - 1, z, MovementDownward.cost(context, x, y, z)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementDownward.cost(context, x, y, z); } }, @@ -47,8 +47,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x, y + 1, z, MovementPillar.cost(context, x, y, z)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementPillar.cost(context, x, y, z); } }, @@ -59,8 +59,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x, y, z - 1, MovementTraverse.cost(context, x, y, z, x, z - 1)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementTraverse.cost(context, x, y, z, x, z - 1); } }, @@ -71,8 +71,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x, y, z + 1, MovementTraverse.cost(context, x, y, z, x, z + 1)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementTraverse.cost(context, x, y, z, x, z + 1); } }, @@ -83,8 +83,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x + 1, y, z, MovementTraverse.cost(context, x, y, z, x + 1, z)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementTraverse.cost(context, x, y, z, x + 1, z); } }, @@ -95,8 +95,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x - 1, y, z, MovementTraverse.cost(context, x, y, z, x - 1, z)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementTraverse.cost(context, x, y, z, x - 1, z); } }, @@ -107,8 +107,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x, y + 1, z - 1, MovementAscend.cost(context, x, y, z, x, z - 1)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementAscend.cost(context, x, y, z, x, z - 1); } }, @@ -119,8 +119,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x, y + 1, z + 1, MovementAscend.cost(context, x, y, z, x, z + 1)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementAscend.cost(context, x, y, z, x, z + 1); } }, @@ -131,8 +131,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x + 1, y + 1, z, MovementAscend.cost(context, x, y, z, x + 1, z)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementAscend.cost(context, x, y, z, x + 1, z); } }, @@ -143,8 +143,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x - 1, y + 1, z, MovementAscend.cost(context, x, y, z, x - 1, z)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementAscend.cost(context, x, y, z, x - 1, z); } }, @@ -223,8 +223,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x + 1, y, z - 1, MovementDiagonal.cost(context, x, y, z, x + 1, z - 1)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementDiagonal.cost(context, x, y, z, x + 1, z - 1); } }, @@ -235,8 +235,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x - 1, y, z - 1, MovementDiagonal.cost(context, x, y, z, x - 1, z - 1)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementDiagonal.cost(context, x, y, z, x - 1, z - 1); } }, @@ -247,8 +247,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x + 1, y, z + 1, MovementDiagonal.cost(context, x, y, z, x + 1, z + 1)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementDiagonal.cost(context, x, y, z, x + 1, z + 1); } }, @@ -259,8 +259,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return new MoveResult(x - 1, y, z + 1, MovementDiagonal.cost(context, x, y, z, x - 1, z + 1)); + public double cost(CalculationContext context, int x, int y, int z) { + return MovementDiagonal.cost(context, x, y, z, x - 1, z + 1); } }, @@ -333,5 +333,14 @@ public enum Moves { public abstract Movement apply0(BetterBlockPos src); - public abstract MoveResult apply(CalculationContext context, int x, int y, int z); + public MoveResult apply(CalculationContext context, int x, int y, int z) { + if (dynamicXZ || dynamicY) { + throw new UnsupportedOperationException(); + } + return new MoveResult(x + xOffset, y + yOffset, z + zOffset, cost(context, x, y, z)); + } + + public double cost(CalculationContext context, int x, int y, int z) { + throw new UnsupportedOperationException(); + } } From cb589219d80143281044f4783638d07707675220 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Oct 2018 12:24:52 -0700 Subject: [PATCH 056/305] use mutable move result to avoid instantianing ten million move result objects --- .../pathing/calc/AStarPathFinder.java | 18 +++-- src/main/java/baritone/pathing/calc/Path.java | 1 + .../java/baritone/pathing/movement/Moves.java | 77 ++++++++++--------- .../movement/movements/MovementDescend.java | 65 ++++++++++------ .../movement/movements/MovementFall.java | 7 +- .../movement/movements/MovementParkour.java | 57 ++++++++------ ...MoveResult.java => MutableMoveResult.java} | 27 ++++--- 7 files changed, 144 insertions(+), 108 deletions(-) rename src/main/java/baritone/utils/pathing/{MoveResult.java => MutableMoveResult.java} (66%) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index 64fd24b3..583428e9 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -26,7 +26,7 @@ import baritone.pathing.movement.Moves; import baritone.pathing.path.IPath; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; -import baritone.utils.pathing.MoveResult; +import baritone.utils.pathing.MutableMoveResult; import java.util.HashSet; import java.util.Optional; @@ -60,6 +60,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel bestSoFar[i] = startNode; } CalculationContext calcContext = new CalculationContext(); + MutableMoveResult res = new MutableMoveResult(); HashSet favored = favoredPositions.orElse(null); BlockStateInterface.clearCachedChunk(); long startTime = System.nanoTime() / 1000000L; @@ -104,28 +105,29 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel continue; } } - MoveResult res = moves.apply(calcContext, currentNode.x, currentNode.y, currentNode.z); + res.reset(); + moves.apply(calcContext, currentNode.x, currentNode.y, currentNode.z, res); numMovementsConsidered++; double actionCost = res.cost; if (actionCost >= ActionCosts.COST_INF) { continue; } // check destination after verifying it's not COST_INF -- some movements return a static IMPOSSIBLE object with COST_INF and destination being 0,0,0 to avoid allocating a new result for every failed calculation - if (!moves.dynamicXZ && (res.destX != newX || res.destZ != newZ)) { - throw new IllegalStateException(moves + " " + res.destX + " " + newX + " " + res.destZ + " " + newZ); + if (!moves.dynamicXZ && (res.x != newX || res.z != newZ)) { + throw new IllegalStateException(moves + " " + res.x + " " + newX + " " + res.z + " " + newZ); } - if (!moves.dynamicY && res.destY != currentNode.y + moves.yOffset) { - throw new IllegalStateException(moves + " " + res.destX + " " + newX + " " + res.destZ + " " + newZ); + if (!moves.dynamicY && res.y != currentNode.y + moves.yOffset) { + throw new IllegalStateException(moves + " " + res.x + " " + newX + " " + res.z + " " + newZ); } if (actionCost <= 0) { throw new IllegalStateException(moves + " calculated implausible cost " + actionCost); } - long hashCode = posHash(res.destX, res.destY, res.destZ); + long hashCode = posHash(res.x, res.y, res.z); if (favoring && favored.contains(hashCode)) { // see issue #18 actionCost *= favorCoeff; } - PathNode neighbor = getNodeAtPosition(res.destX, res.destY, res.destZ, hashCode); + PathNode neighbor = getNodeAtPosition(res.x, res.y, res.z, hashCode); double tentativeCost = currentNode.cost + actionCost; if (tentativeCost < neighbor.cost) { if (tentativeCost < 0) { diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 72f1756c..911c0dc7 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -139,6 +139,7 @@ class Path implements IPath { for (Moves moves : Moves.values()) { Movement move = moves.apply0(src); if (move.getDest().equals(dest)) { + move.recalculateCost(); // have to calculate the cost at calculation time so we can accurately judge whether a cost increase happened between cached calculation and real execution return move; } } diff --git a/src/main/java/baritone/pathing/movement/Moves.java b/src/main/java/baritone/pathing/movement/Moves.java index 1a3f61ef..c5b1069d 100644 --- a/src/main/java/baritone/pathing/movement/Moves.java +++ b/src/main/java/baritone/pathing/movement/Moves.java @@ -19,7 +19,7 @@ package baritone.pathing.movement; import baritone.pathing.movement.movements.*; import baritone.utils.pathing.BetterBlockPos; -import baritone.utils.pathing.MoveResult; +import baritone.utils.pathing.MutableMoveResult; import net.minecraft.util.EnumFacing; /** @@ -151,68 +151,72 @@ public enum Moves { DESCEND_EAST(+1, 0, 0, false, true) { @Override public Movement apply0(BetterBlockPos src) { - MoveResult res = apply(new CalculationContext(), src.x, src.y, src.z); - if (res.destY == src.y - 1) { - return new MovementDescend(src, new BetterBlockPos(res.destX, res.destY, res.destZ)); + MutableMoveResult res = new MutableMoveResult(); + apply(new CalculationContext(), src.x, src.y, src.z, res); + if (res.y == src.y - 1) { + return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); } else { - return new MovementFall(src, new BetterBlockPos(res.destX, res.destY, res.destZ)); + return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z)); } } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return MovementDescend.cost(context, x, y, z, x + 1, z); + public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { + MovementDescend.cost(context, x, y, z, x + 1, z, result); } }, DESCEND_WEST(-1, 0, 0, false, true) { @Override public Movement apply0(BetterBlockPos src) { - MoveResult res = apply(new CalculationContext(), src.x, src.y, src.z); - if (res.destY == src.y - 1) { - return new MovementDescend(src, new BetterBlockPos(res.destX, res.destY, res.destZ)); + MutableMoveResult res = new MutableMoveResult(); + apply(new CalculationContext(), src.x, src.y, src.z, res); + if (res.y == src.y - 1) { + return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); } else { - return new MovementFall(src, new BetterBlockPos(res.destX, res.destY, res.destZ)); + return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z)); } } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return MovementDescend.cost(context, x, y, z, x - 1, z); + public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { + MovementDescend.cost(context, x, y, z, x - 1, z, result); } }, DESCEND_NORTH(0, 0, -1, false, true) { @Override public Movement apply0(BetterBlockPos src) { - MoveResult res = apply(new CalculationContext(), src.x, src.y, src.z); - if (res.destY == src.y - 1) { - return new MovementDescend(src, new BetterBlockPos(res.destX, res.destY, res.destZ)); + MutableMoveResult res = new MutableMoveResult(); + apply(new CalculationContext(), src.x, src.y, src.z, res); + if (res.y == src.y - 1) { + return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); } else { - return new MovementFall(src, new BetterBlockPos(res.destX, res.destY, res.destZ)); + return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z)); } } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return MovementDescend.cost(context, x, y, z, x, z - 1); + public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { + MovementDescend.cost(context, x, y, z, x, z - 1, result); } }, DESCEND_SOUTH(0, 0, +1, false, true) { @Override public Movement apply0(BetterBlockPos src) { - MoveResult res = apply(new CalculationContext(), src.x, src.y, src.z); - if (res.destY == src.y - 1) { - return new MovementDescend(src, new BetterBlockPos(res.destX, res.destY, res.destZ)); + MutableMoveResult res = new MutableMoveResult(); + apply(new CalculationContext(), src.x, src.y, src.z, res); + if (res.y == src.y - 1) { + return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); } else { - return new MovementFall(src, new BetterBlockPos(res.destX, res.destY, res.destZ)); + return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z)); } } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return MovementDescend.cost(context, x, y, z, x, z + 1); + public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { + MovementDescend.cost(context, x, y, z, x, z + 1, result); } }, @@ -271,8 +275,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return MovementParkour.cost(context, x, y, z, EnumFacing.NORTH); + public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { + MovementParkour.cost(context, x, y, z, EnumFacing.NORTH, result); } }, @@ -283,8 +287,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return MovementParkour.cost(context, x, y, z, EnumFacing.SOUTH); + public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { + MovementParkour.cost(context, x, y, z, EnumFacing.SOUTH, result); } }, @@ -295,8 +299,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return MovementParkour.cost(context, x, y, z, EnumFacing.EAST); + public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { + MovementParkour.cost(context, x, y, z, EnumFacing.EAST, result); } }, @@ -307,8 +311,8 @@ public enum Moves { } @Override - public MoveResult apply(CalculationContext context, int x, int y, int z) { - return MovementParkour.cost(context, x, y, z, EnumFacing.WEST); + public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { + MovementParkour.cost(context, x, y, z, EnumFacing.WEST, result); } }; @@ -333,11 +337,14 @@ public enum Moves { public abstract Movement apply0(BetterBlockPos src); - public MoveResult apply(CalculationContext context, int x, int y, int z) { + public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { if (dynamicXZ || dynamicY) { throw new UnsupportedOperationException(); } - return new MoveResult(x + xOffset, y + yOffset, z + zOffset, cost(context, x, y, z)); + result.x = x + xOffset; + result.y = y + yOffset; + result.z = z + zOffset; + result.cost = cost(context, x, y, z); } public double cost(CalculationContext context, int x, int y, int z) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index b4e41597..3bba5f1d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -26,15 +26,13 @@ import baritone.pathing.movement.MovementState.MovementStatus; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; import baritone.utils.pathing.BetterBlockPos; -import baritone.utils.pathing.MoveResult; +import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; -import static baritone.utils.pathing.MoveResult.IMPOSSIBLE; - public class MovementDescend extends Movement { private int numTicks = 0; @@ -51,32 +49,33 @@ public class MovementDescend extends Movement { @Override protected double calculateCost(CalculationContext context) { - MoveResult result = cost(context, src.x, src.y, src.z, dest.x, dest.z); - if (result.destY != dest.y) { + MutableMoveResult result = new MutableMoveResult(); + cost(context, src.x, src.y, src.z, dest.x, dest.z, result); + if (result.y != dest.y) { return COST_INF; // doesn't apply to us, this position is a fall not a descend } return result.cost; } - public static MoveResult cost(CalculationContext context, int x, int y, int z, int destX, int destZ) { + public static void cost(CalculationContext context, int x, int y, int z, int destX, int destZ, MutableMoveResult res) { Block fromDown = BlockStateInterface.get(x, y - 1, z).getBlock(); if (fromDown == Blocks.LADDER || fromDown == Blocks.VINE) { - return IMPOSSIBLE; + return; } double totalCost = 0; IBlockState destDown = BlockStateInterface.get(destX, y - 1, destZ); totalCost += MovementHelper.getMiningDurationTicks(context, destX, y - 1, destZ, destDown, false); if (totalCost >= COST_INF) { - return IMPOSSIBLE; + return; } totalCost += MovementHelper.getMiningDurationTicks(context, destX, y, destZ, false); if (totalCost >= COST_INF) { - return IMPOSSIBLE; + return; } totalCost += MovementHelper.getMiningDurationTicks(context, destX, y + 1, destZ, true); // only the top block in the 3 we need to mine needs to consider the falling blocks above if (totalCost >= COST_INF) { - return IMPOSSIBLE; + return; } // A @@ -91,11 +90,12 @@ public class MovementDescend extends Movement { IBlockState below = BlockStateInterface.get(destX, y - 2, destZ); if (!MovementHelper.canWalkOn(destX, y - 2, destZ, below)) { - return dynamicFallCost(context, x, y, z, destX, destZ, totalCost, below); + dynamicFallCost(context, x, y, z, destX, destZ, totalCost, below, res); + return; } if (destDown.getBlock() == Blocks.LADDER || destDown.getBlock() == Blocks.VINE) { - return IMPOSSIBLE; + return; } // 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) @@ -105,25 +105,28 @@ public class MovementDescend extends Movement { walk = WALK_ONE_OVER_SOUL_SAND_COST; } totalCost += walk + Math.max(FALL_N_BLOCKS_COST[1], CENTER_AFTER_FALL_COST); - return new MoveResult(destX, y - 1, destZ, totalCost); + res.x = destX; + res.y = y - 1; + res.z = destZ; + res.cost = totalCost; } - public static MoveResult dynamicFallCost(CalculationContext context, int x, int y, int z, int destX, int destZ, double frontBreak, IBlockState below) { + public static void dynamicFallCost(CalculationContext context, int x, int y, int z, int destX, int destZ, double frontBreak, IBlockState below, MutableMoveResult res) { if (frontBreak != 0 && BlockStateInterface.get(destX, y + 2, destZ).getBlock() instanceof BlockFalling) { // if frontBreak is 0 we can actually get through this without updating the falling block and making it actually fall // but if frontBreak is nonzero, we're breaking blocks in front, so don't let anything fall through this column, // and potentially replace the water we're going to fall into - return IMPOSSIBLE; + return; } if (!MovementHelper.canWalkThrough(destX, y - 2, destZ, below) && below.getBlock() != Blocks.WATER) { - return IMPOSSIBLE; + return; } for (int fallHeight = 3; true; fallHeight++) { int newY = y - fallHeight; if (newY < 0) { // when pathing in the end, where you could plausibly fall into the void // this check prevents it from getting the block at y=-1 and crashing - return IMPOSSIBLE; + return; } IBlockState ontoBlock = BlockStateInterface.get(destX, newY, destZ); double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[fallHeight] + frontBreak; @@ -131,31 +134,43 @@ public class MovementDescend extends Movement { // lilypads are canWalkThrough, but we can't end a fall that should be broken by water if it's covered by a lilypad // however, don't return impossible in the lilypad scenario, because we could still jump right on it (water that's below a lilypad is canWalkOn so it works) if (Baritone.settings().assumeWalkOnWater.get()) { - return IMPOSSIBLE; // TODO fix + return; // TODO fix } // found a fall into water - return new MoveResult(destX, newY, destZ, tentativeCost); // TODO incorporate water swim up cost? + res.x = destX; + res.y = newY; + res.z = destZ; + res.cost = tentativeCost;// TODO incorporate water swim up cost? + return; } if (ontoBlock.getBlock() == Blocks.FLOWING_WATER) { - return IMPOSSIBLE; + return; } if (MovementHelper.canWalkThrough(destX, newY, destZ, ontoBlock)) { continue; } if (!MovementHelper.canWalkOn(destX, newY, destZ, ontoBlock)) { - return IMPOSSIBLE; + return; } if (MovementHelper.isBottomSlab(ontoBlock)) { - return IMPOSSIBLE; // falling onto a half slab is really glitchy, and can cause more fall damage than we'd expect + return; // falling onto a half slab is really glitchy, and can cause more fall damage than we'd expect } if (context.hasWaterBucket() && fallHeight <= context.maxFallHeightBucket() + 1) { - return new MoveResult(destX, newY + 1, destZ, tentativeCost + context.placeBlockCost()); // this is the block we're falling onto, so dest is +1 + res.x = destX; + res.y = newY + 1;// this is the block we're falling onto, so dest is +1 + res.z = destZ; + res.cost = tentativeCost + context.placeBlockCost(); + return; } if (fallHeight <= context.maxFallHeightNoWater() + 1) { // fallHeight = 4 means onto.up() is 3 blocks down, which is the max - return new MoveResult(destX, newY + 1, destZ, tentativeCost); + res.x = destX; + res.y = newY + 1; + res.z = destZ; + res.cost = tentativeCost; + return; } else { - return IMPOSSIBLE; + return; } } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 1cfd451f..818ae124 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -30,7 +30,7 @@ import baritone.utils.InputOverrideHandler; import baritone.utils.RayTraceUtils; import baritone.utils.Utils; import baritone.utils.pathing.BetterBlockPos; -import baritone.utils.pathing.MoveResult; +import baritone.utils.pathing.MutableMoveResult; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; @@ -49,8 +49,9 @@ public class MovementFall extends Movement { @Override protected double calculateCost(CalculationContext context) { - MoveResult result = MovementDescend.cost(context, src.x, src.y, src.z, dest.x, dest.z); - if (result.destY != dest.y) { + MutableMoveResult result = new MutableMoveResult(); + MovementDescend.cost(context, src.x, src.y, src.z, dest.x, dest.z, result); + if (result.y != dest.y) { return COST_INF; // doesn't apply to us, this position is a descend not a fall } return result.cost; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 178411fd..a4576ec7 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -28,7 +28,7 @@ import baritone.utils.Helper; import baritone.utils.InputOverrideHandler; import baritone.utils.Utils; import baritone.utils.pathing.BetterBlockPos; -import baritone.utils.pathing.MoveResult; +import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -39,8 +39,6 @@ import net.minecraft.util.math.Vec3d; import java.util.Objects; -import static baritone.utils.pathing.MoveResult.IMPOSSIBLE; - public class MovementParkour extends Movement { private static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN}; @@ -56,70 +54,75 @@ public class MovementParkour extends Movement { } public static MovementParkour cost(CalculationContext context, BetterBlockPos src, EnumFacing direction) { - MoveResult res = cost(context, src.x, src.y, src.z, direction); - int dist = Math.abs(res.destX - src.x) + Math.abs(res.destZ - src.z); + MutableMoveResult res = new MutableMoveResult(); + cost(context, src.x, src.y, src.z, direction, res); + int dist = Math.abs(res.x - src.x) + Math.abs(res.z - src.z); return new MovementParkour(src, dist, direction); } - public static MoveResult cost(CalculationContext context, int x, int y, int z, EnumFacing dir) { + public static void cost(CalculationContext context, int x, int y, int z, EnumFacing dir, MutableMoveResult res) { if (!Baritone.settings().allowParkour.get()) { - return IMPOSSIBLE; + return; } IBlockState standingOn = BlockStateInterface.get(x, y - 1, z); if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || MovementHelper.isBottomSlab(standingOn)) { - return IMPOSSIBLE; + return; } int xDiff = dir.getXOffset(); int zDiff = dir.getZOffset(); IBlockState adj = BlockStateInterface.get(x + xDiff, y - 1, z + zDiff); if (MovementHelper.avoidWalkingInto(adj.getBlock()) && adj.getBlock() != Blocks.WATER && adj.getBlock() != Blocks.FLOWING_WATER) { // magma sucks - return IMPOSSIBLE; + return; } if (MovementHelper.canWalkOn(x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now) - return IMPOSSIBLE; + return; } if (!MovementHelper.fullyPassable(x + xDiff, y, z + zDiff)) { - return IMPOSSIBLE; + return; } if (!MovementHelper.fullyPassable(x + xDiff, y + 1, z + zDiff)) { - return IMPOSSIBLE; + return; } if (!MovementHelper.fullyPassable(x + xDiff, y + 2, z + zDiff)) { - return IMPOSSIBLE; + return; } if (!MovementHelper.fullyPassable(x, y + 2, z)) { - return IMPOSSIBLE; + return; } for (int i = 2; i <= (context.canSprint() ? 4 : 3); i++) { // TODO perhaps dest.up(3) doesn't need to be fullyPassable, just canWalkThrough, possibly? for (int y2 = 0; y2 < 4; y2++) { if (!MovementHelper.fullyPassable(x + xDiff * i, y + y2, z + zDiff * i)) { - return IMPOSSIBLE; + return; } } if (MovementHelper.canWalkOn(x + xDiff * i, y - 1, z + zDiff * i)) { - return new MoveResult(x + xDiff * i, y, z + zDiff * i, costFromJumpDistance(i)); + res.x = x + xDiff * i; + res.y = y; + res.z = z + zDiff * i; + res.cost = costFromJumpDistance(i); + return; } } if (!context.canSprint()) { - return IMPOSSIBLE; + return; } if (!Baritone.settings().allowParkourPlace.get()) { - return IMPOSSIBLE; + return; } if (!Baritone.settings().allowPlace.get()) { Helper.HELPER.logDirect("allowParkourPlace enabled but allowPlace disabled?"); - return IMPOSSIBLE; + return; } int destX = x + 4 * xDiff; int destZ = z + 4 * zDiff; IBlockState toPlace = BlockStateInterface.get(destX, y - 1, destZ); if (!context.hasThrowaway()) { - return IMPOSSIBLE; + return; } if (toPlace.getBlock() != Blocks.AIR && !BlockStateInterface.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y - 1, destZ, toPlace)) { - return IMPOSSIBLE; + return; } for (int i = 0; i < 5; i++) { int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); @@ -128,10 +131,13 @@ public class MovementParkour extends Movement { continue; } if (MovementHelper.canPlaceAgainst(againstX, y - 1, againstZ)) { - return new MoveResult(destX, y, destZ, costFromJumpDistance(4) + context.placeBlockCost()); + res.x = destX; + res.y = y; + res.z = destZ; + res.cost = costFromJumpDistance(4) + context.placeBlockCost(); + return; } } - return IMPOSSIBLE; } private static double costFromJumpDistance(int dist) { @@ -150,8 +156,9 @@ public class MovementParkour extends Movement { @Override protected double calculateCost(CalculationContext context) { - MoveResult res = cost(context, src.x, src.y, src.z, direction); - if (res.destX != dest.x || res.destZ != dest.z) { + MutableMoveResult res = new MutableMoveResult(); + cost(context, src.x, src.y, src.z, direction, res); + if (res.x != dest.x || res.z != dest.z) { return COST_INF; } return res.cost; diff --git a/src/main/java/baritone/utils/pathing/MoveResult.java b/src/main/java/baritone/utils/pathing/MutableMoveResult.java similarity index 66% rename from src/main/java/baritone/utils/pathing/MoveResult.java rename to src/main/java/baritone/utils/pathing/MutableMoveResult.java index 8478a617..b6e1ba8a 100644 --- a/src/main/java/baritone/utils/pathing/MoveResult.java +++ b/src/main/java/baritone/utils/pathing/MutableMoveResult.java @@ -17,24 +17,27 @@ package baritone.utils.pathing; -import static baritone.api.pathing.movement.ActionCosts.COST_INF; +import baritone.api.pathing.movement.ActionCosts; /** * The result of a calculated movement, with destination x, y, z, and the cost of performing the movement * * @author leijurv */ -public final class MoveResult { - public static final MoveResult IMPOSSIBLE = new MoveResult(0, 0, 0, COST_INF); - public final int destX; - public final int destY; - public final int destZ; - public final double cost; +public final class MutableMoveResult { + public int x; + public int y; + public int z; + public double cost; - public MoveResult(int x, int y, int z, double cost) { - this.destX = x; - this.destY = y; - this.destZ = z; - this.cost = cost; + public MutableMoveResult() { + reset(); + } + + public final void reset() { + x = 0; + y = 0; + z = 0; + cost = ActionCosts.COST_INF; } } From 9880a4e94889da5113d6882feec573d9725e08ce Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Oct 2018 13:11:09 -0700 Subject: [PATCH 057/305] when asusmeSafeWalk is on, we don't sneak in the first place --- .../baritone/pathing/movement/movements/MovementTraverse.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 26952b02..6b31b8f0 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -269,7 +269,7 @@ public class MovementTraverse extends Movement { state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true)); EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; - if (Objects.equals(LookBehaviorUtils.getSelectedBlock().orElse(null), against1) && Minecraft.getMinecraft().player.isSneaking()) { + if (Objects.equals(LookBehaviorUtils.getSelectedBlock().orElse(null), against1) && (Minecraft.getMinecraft().player.isSneaking() || Baritone.settings().assumeSafeWalk.get())) { if (LookBehaviorUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } From ca48dabcc7edcd1f0cbaccbe91fbe543cf7c9fdb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Oct 2018 13:49:47 -0700 Subject: [PATCH 058/305] change sneak-backplace behavior, fixes #208 --- .../pathing/movement/movements/MovementTraverse.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 6b31b8f0..abd870e7 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -294,9 +294,17 @@ 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.setInput(InputOverrideHandler.Input.MOVE_BACK, true); + Rotation backToFace = Utils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()); + float pitch = backToFace.getPitch(); + double dist = Math.max(Math.abs(player().posX - faceX), Math.abs(player().posZ - faceZ)); + if (dist < 0.29) { + float yaw = Utils.calcRotationFromVec3d(Utils.getBlockPosCenter(dest), playerHead(), playerRotations()).getYaw(); + state.setTarget(new MovementState.MovementTarget(new Rotation(yaw, pitch), true)); + state.setInput(InputOverrideHandler.Input.MOVE_BACK, true); + } else { + state.setTarget(new MovementState.MovementTarget(backToFace, true)); + } state.setInput(InputOverrideHandler.Input.SNEAK, true); if (Objects.equals(LookBehaviorUtils.getSelectedBlock().orElse(null), goalLook)) { return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); // wait to right click until we are able to place From 046de8436020844f75abc3c80ac91ffa9d0d469e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Oct 2018 14:39:17 -0700 Subject: [PATCH 059/305] that should really default to true --- src/main/java/baritone/pathing/movement/Movement.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index b952e547..2b87c1e0 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -192,7 +192,7 @@ public abstract class Movement implements Helper, MovementHelper { } protected boolean safeToCancel(MovementState currentState) { - return false; + return true; } public boolean isFinished() { From 78b626af23bddb572f975b72c22bef8df379ad3b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Oct 2018 15:42:02 -0700 Subject: [PATCH 060/305] v0.0.6 --- build.gradle | 2 +- scripts/proguard.pro | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 0a1bb804..52f3e97c 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '0.0.3' +version '0.0.6' buildscript { repositories { diff --git a/scripts/proguard.pro b/scripts/proguard.pro index b0f4a5f9..6efbe0fa 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -1,4 +1,4 @@ --injars baritone-0.0.3.jar +-injars baritone-0.0.6.jar -outjars Obfuscated From 1ab5609d4ec7e89f7c3c08e0043f9f48a4a559de Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Oct 2018 15:51:23 -0700 Subject: [PATCH 061/305] spam travis less --- src/main/java/baritone/pathing/path/PathExecutor.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 523b98b0..117e8008 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -177,7 +177,7 @@ public class PathExecutor implements Helper { } } }*/ - long start = System.nanoTime() / 1000000L; + //long start = System.nanoTime() / 1000000L; for (int i = pathPosition - 10; i < pathPosition + 10; i++) { if (i < 0 || i >= path.movements().size()) { continue; @@ -213,10 +213,10 @@ public class PathExecutor implements Helper { toWalkInto = newWalkInto; recalcBP = false; } - long end = System.nanoTime() / 1000000L; + /*long end = System.nanoTime() / 1000000L; if (end - start > 0) { System.out.println("Recalculating break and place took " + (end - start) + "ms"); - } + }*/ Movement movement = path.movements().get(pathPosition); boolean canCancel = movement.safeToCancel(); if (costEstimateIndex == null || costEstimateIndex != pathPosition) { From 6c9f317f3193f942b2821101697032aa4285ebef Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Oct 2018 18:27:02 -0700 Subject: [PATCH 062/305] don't look to the side on a parkour place until the place is in range --- .../movement/movements/MovementParkour.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index a4576ec7..22fc5909 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -18,15 +18,13 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.utils.Rotation; import baritone.behavior.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.Helper; -import baritone.utils.InputOverrideHandler; -import baritone.utils.Utils; +import baritone.utils.*; import baritone.utils.pathing.BetterBlockPos; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; @@ -35,6 +33,7 @@ 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.RayTraceResult; import net.minecraft.util.math.Vec3d; import java.util.Objects; @@ -201,10 +200,13 @@ public class MovementParkour extends Movement { 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)); - EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; - + Rotation place = Utils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()); + RayTraceResult res = RayTraceUtils.rayTraceTowards(place); + if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(dest.down())) { + state.setTarget(new MovementState.MovementTarget(place, true)); + } LookBehaviorUtils.getSelectedBlock().ifPresent(selectedBlock -> { + EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; if (Objects.equals(selectedBlock, against1) && selectedBlock.offset(side).equals(dest.down())) { state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } From d5130aa6ba57e14b35fc5770ee6e57b0950702d0 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 6 Oct 2018 20:16:38 -0500 Subject: [PATCH 063/305] Expose event listener registry in API --- src/api/java/baritone/api/BaritoneAPI.java | 5 +++++ .../java/baritone/api/IBaritoneProvider.java | 8 ++++++++ src/main/java/baritone/Baritone.java | 17 +---------------- src/main/java/baritone/BaritoneProvider.java | 6 ++++++ 4 files changed, 20 insertions(+), 16 deletions(-) diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index dec7ec13..cba66ddc 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -19,6 +19,7 @@ package baritone.api; import baritone.api.behavior.*; import baritone.api.cache.IWorldProvider; +import baritone.api.event.listener.IGameEventListener; import java.util.Iterator; import java.util.ServiceLoader; @@ -71,4 +72,8 @@ public final class BaritoneAPI { public static IWorldProvider getWorldProvider() { return baritone.getWorldProvider(); } + + public static void registerEventListener(IGameEventListener listener) { + baritone.registerEventListener(listener); + } } diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index 52dae153..aa20979b 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -19,6 +19,7 @@ package baritone.api; import baritone.api.behavior.*; import baritone.api.cache.IWorldProvider; +import baritone.api.event.listener.IGameEventListener; /** * @author Brady @@ -67,4 +68,11 @@ public interface IBaritoneProvider { * @return The {@link IWorldProvider} instance */ IWorldProvider getWorldProvider(); + + /** + * Registers a {@link IGameEventListener} with Baritone's "event bus". + * + * @param listener The listener + */ + void registerEventListener(IGameEventListener listener); } diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index b7904d00..9b887032 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -21,7 +21,6 @@ import baritone.api.BaritoneAPI; import baritone.api.Settings; import baritone.api.event.listener.IGameEventListener; import baritone.behavior.*; -import baritone.cache.WorldProvider; import baritone.event.GameEventHandler; import baritone.utils.BaritoneAutoTest; import baritone.utils.InputOverrideHandler; @@ -36,7 +35,6 @@ import java.util.concurrent.Executor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; /** * @author Brady @@ -61,19 +59,13 @@ public enum Baritone { private File dir; private ThreadPoolExecutor threadPool; - - /** - * List of consumers to be called after Baritone has initialized - */ - private List> onInitConsumers; - /** * Whether or not Baritone is active */ private boolean active; Baritone() { - this.onInitConsumers = new ArrayList<>(); + this.gameEventHandler = new GameEventHandler(); } public synchronized void init() { @@ -81,7 +73,6 @@ public enum Baritone { return; } this.threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); - this.gameEventHandler = new GameEventHandler(); this.inputOverrideHandler = new InputOverrideHandler(); // Acquire the "singleton" instance of the settings directly from the API @@ -109,8 +100,6 @@ public enum Baritone { this.active = true; this.initialized = true; - - this.onInitConsumers.forEach(consumer -> consumer.accept(this)); } public boolean isInitialized() { @@ -157,8 +146,4 @@ public enum Baritone { public File getDir() { return this.dir; } - - public void registerInitListener(Consumer runnable) { - this.onInitConsumers.add(runnable); - } } diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index 370a398e..eb6bf27a 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -20,6 +20,7 @@ package baritone; import baritone.api.IBaritoneProvider; import baritone.api.behavior.*; import baritone.api.cache.IWorldProvider; +import baritone.api.event.listener.IGameEventListener; import baritone.behavior.*; import baritone.cache.WorldProvider; @@ -58,4 +59,9 @@ public final class BaritoneProvider implements IBaritoneProvider { public IWorldProvider getWorldProvider() { return WorldProvider.INSTANCE; } + + @Override + public void registerEventListener(IGameEventListener listener) { + Baritone.INSTANCE.registerEventListener(listener); + } } From 4b61452c628cae8734752a1a28e7cb122da24594 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 6 Oct 2018 20:30:09 -0500 Subject: [PATCH 064/305] Expose WorldScanner in API --- .../java/baritone/api/IBaritoneProvider.java | 8 ++++ .../baritone/api/cache/IWorldScanner.java | 42 +++++++++++++++++++ src/main/java/baritone/BaritoneProvider.java | 7 ++++ .../java/baritone/cache/WorldScanner.java | 15 ++----- 4 files changed, 61 insertions(+), 11 deletions(-) create mode 100644 src/api/java/baritone/api/cache/IWorldScanner.java diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index aa20979b..88c4adff 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -19,6 +19,7 @@ package baritone.api; import baritone.api.behavior.*; import baritone.api.cache.IWorldProvider; +import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IGameEventListener; /** @@ -69,6 +70,13 @@ public interface IBaritoneProvider { */ IWorldProvider getWorldProvider(); + /** + * @see IWorldScanner + * + * @return The {@link IWorldScanner} instance + */ + IWorldScanner getWorldScanner(); + /** * Registers a {@link IGameEventListener} with Baritone's "event bus". * diff --git a/src/api/java/baritone/api/cache/IWorldScanner.java b/src/api/java/baritone/api/cache/IWorldScanner.java new file mode 100644 index 00000000..c35757ef --- /dev/null +++ b/src/api/java/baritone/api/cache/IWorldScanner.java @@ -0,0 +1,42 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.cache; + +import net.minecraft.block.Block; +import net.minecraft.util.math.BlockPos; + +import java.util.List; + +/** + * @author Brady + * @since 10/6/2018 + */ +public interface IWorldScanner { + + /** + * Scans the world, up to the specified max chunk radius, for the specified blocks. + * + * @param blocks The blocks to scan for + * @param max The maximum number of blocks to scan before cutoff + * @param yLevelThreshold If a block is found within this Y level, the current result will be + * returned, if the value is negative, then this condition doesn't apply. + * @param maxSearchRadius The maximum chunk search radius + * @return The matching block positions + */ + List scanLoadedChunks(List blocks, int max, int yLevelThreshold, int maxSearchRadius); +} diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index eb6bf27a..d9dfe624 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -20,9 +20,11 @@ package baritone; import baritone.api.IBaritoneProvider; import baritone.api.behavior.*; import baritone.api.cache.IWorldProvider; +import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IGameEventListener; import baritone.behavior.*; import baritone.cache.WorldProvider; +import baritone.cache.WorldScanner; /** * @author Brady @@ -60,6 +62,11 @@ public final class BaritoneProvider implements IBaritoneProvider { return WorldProvider.INSTANCE; } + @Override + public IWorldScanner getWorldScanner() { + return WorldScanner.INSTANCE; + } + @Override public void registerEventListener(IGameEventListener listener) { Baritone.INSTANCE.registerEventListener(listener); diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index d6b466ef..a0d905c6 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -17,6 +17,7 @@ package baritone.cache; +import baritone.api.cache.IWorldScanner; import baritone.utils.Helper; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -29,19 +30,11 @@ import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import java.util.LinkedList; import java.util.List; -public enum WorldScanner implements Helper { +public enum WorldScanner implements IWorldScanner, Helper { + INSTANCE; - /** - * Scans the world, up to your render distance, for the specified blocks. - * - * @param blocks The blocks to scan for - * @param max The maximum number of blocks to scan before cutoff - * @param yLevelThreshold If a block is found within this Y level, the current result will be - * returned, if the value is negative, then this condition doesn't apply. - * @param maxSearchRadius The maximum chunk search radius - * @return The matching block positions - */ + @Override public List scanLoadedChunks(List blocks, int max, int yLevelThreshold, int maxSearchRadius) { if (blocks.contains(null)) { throw new IllegalStateException("Invalid block name should have been caught earlier: " + blocks.toString()); From e4ef659756b6a7c0d322b4bff522a8c0426b2df5 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 6 Oct 2018 20:35:32 -0500 Subject: [PATCH 065/305] Fix WorldScanner exposure --- src/api/java/baritone/api/BaritoneAPI.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index cba66ddc..7497454e 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -19,6 +19,7 @@ package baritone.api; import baritone.api.behavior.*; import baritone.api.cache.IWorldProvider; +import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IGameEventListener; import java.util.Iterator; @@ -73,6 +74,10 @@ public final class BaritoneAPI { return baritone.getWorldProvider(); } + public static IWorldScanner getWorldScanner() { + return baritone.getWorldScanner(); + } + public static void registerEventListener(IGameEventListener listener) { baritone.registerEventListener(listener); } From 939e9c32d55abfd57328e49ccf380dc68d183451 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 6 Oct 2018 18:39:30 -0700 Subject: [PATCH 066/305] pause when current best is a backtrack, fixes #201 --- src/main/java/baritone/pathing/calc/Path.java | 3 +- .../movement/movements/MovementFall.java | 4 ++- .../movement/movements/MovementParkour.java | 8 +++++ .../movement/movements/MovementTraverse.java | 8 +++++ .../baritone/pathing/path/PathExecutor.java | 32 +++++++++++++++++++ 5 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 911c0dc7..f1a31553 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -139,11 +139,12 @@ class Path implements IPath { for (Moves moves : Moves.values()) { Movement move = moves.apply0(src); if (move.getDest().equals(dest)) { + // TODO instead of recalculating here, could we take pathNode.cost - pathNode.prevNode.cost to get the cost as-calculated? move.recalculateCost(); // have to calculate the cost at calculation time so we can accurately judge whether a cost increase happened between cached calculation and real execution return move; } } - // leave this as IllegalStateException; it's caught in AbstractNodeCostSearch + // this is no longer called from bestPathSoFar, now it's in postprocessing throw new IllegalStateException("Movement became impossible during calculation " + src + " " + dest + " " + dest.subtract(src)); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 818ae124..f901c61f 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -114,7 +114,9 @@ public class MovementFall extends Movement { @Override public boolean safeToCancel(MovementState state) { - return state.getStatus() != MovementStatus.RUNNING; + // if we haven't started walking off the edge yet, or if we're in the process of breaking blocks before doing the fall + // then it's safe to cancel this + return playerFeet().equals(src) || state.getStatus() != MovementStatus.RUNNING; } private static BetterBlockPos[] buildPositionsToBreak(BetterBlockPos src, BetterBlockPos dest) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 22fc5909..2310f773 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -163,6 +163,14 @@ public class MovementParkour extends Movement { return res.cost; } + @Override + public boolean safeToCancel(MovementState state) { + // once this movement is instantiated, the state is default to PREPPING + // but once it's ticked for the first time it changes to RUNNING + // since we don't really know anything about momentum, it suffices to say Parkour can only be canceled on the 0th tick + return state.getStatus() != MovementState.MovementStatus.RUNNING; + } + @Override public MovementState updateState(MovementState state) { super.updateState(state); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index abd870e7..7c4ba237 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -319,6 +319,14 @@ public class MovementTraverse extends Movement { } } + @Override + public boolean safeToCancel(MovementState state) { + // if we're in the process of breaking blocks before walking forwards + // or if this isn't a sneak place (the block is already there) + // then it's safe to cancel this + return state.getStatus() != MovementState.MovementStatus.RUNNING || MovementHelper.canWalkOn(dest.down()); + } + @Override protected boolean prepared(MovementState state) { if (playerFeet().equals(src) || playerFeet().equals(src.down())) { diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 117e8008..9aeeac69 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -20,6 +20,7 @@ package baritone.pathing.path; import baritone.Baritone; import baritone.api.event.events.TickEvent; import baritone.api.pathing.movement.ActionCosts; +import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; @@ -33,6 +34,7 @@ import net.minecraft.util.math.BlockPos; import java.util.Collections; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import static baritone.pathing.movement.MovementState.MovementStatus.*; @@ -242,6 +244,10 @@ public class PathExecutor implements Helper { cancel(); return true; } + if (shouldPause()) { + logDebug("Pausing since current best path is a backtrack"); + return true; + } MovementState.MovementStatus movementStatus = movement.update(); if (movementStatus == UNREACHABLE || movementStatus == FAILED) { logDebug("Movement returns status " + movementStatus); @@ -270,6 +276,32 @@ public class PathExecutor implements Helper { return false; // movement is in progress } + private boolean shouldPause() { + Optional current = AbstractNodeCostSearch.getCurrentlyRunning(); + if (!current.isPresent()) { + return false; + } + if (!player().onGround) { + return false; + } + if (!MovementHelper.canWalkOn(playerFeet().down())) { + // we're in some kind of sketchy situation, maybe parkouring + return false; + } + if (!MovementHelper.canWalkThrough(playerFeet()) || !MovementHelper.canWalkThrough(playerFeet().up())) { + // suffocating? + return false; + } + if (!path.movements().get(pathPosition).safeToCancel()) { + return false; + } + Optional currentBest = current.get().bestPathSoFar(); + if (!currentBest.isPresent()) { + return false; + } + return currentBest.get().positions().contains(playerFeet()); + } + private boolean possiblyOffPath(Tuple status, double leniency) { double distanceFromPath = status.getFirst(); if (distanceFromPath > leniency) { From 8c7657339506c0562e93545244cf696fa6825eac Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 6 Oct 2018 18:43:20 -0700 Subject: [PATCH 067/305] don't pause on one block overlap --- .../java/baritone/pathing/path/PathExecutor.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 9aeeac69..15cb44d2 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -32,10 +32,7 @@ import net.minecraft.init.Blocks; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; -import java.util.Collections; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; +import java.util.*; import static baritone.pathing.movement.MovementState.MovementStatus.*; @@ -299,7 +296,14 @@ public class PathExecutor implements Helper { if (!currentBest.isPresent()) { return false; } - return currentBest.get().positions().contains(playerFeet()); + List positions = currentBest.get().positions(); + if (positions.size() < 3) { + return false; // not long enough yet to justify pausing, its far from certain we'll actually take this route + } + // the first block of the next path will always overlap + // no need to pause our very last movement when it would have otherwise cleanly exited with MovementStatus SUCCESS + positions = positions.subList(1, positions.size()); + return positions.contains(playerFeet()); } private boolean possiblyOffPath(Tuple status, double leniency) { From af357d4d8e280878db0337191531aec10478cb9f Mon Sep 17 00:00:00 2001 From: leijurv Date: Sat, 6 Oct 2018 20:28:17 -0700 Subject: [PATCH 068/305] fix a weird bug --- src/main/java/baritone/pathing/path/PathExecutor.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 15cb44d2..cc140941 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -114,7 +114,8 @@ public class PathExecutor implements Helper { return false; } } - for (int i = pathPosition + 2; i < path.length(); i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing) + for (int i = pathPosition + 3; i < path.length(); i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing) + // also don't check pathPosition+2 because reasons if (whereAmI.equals(path.positions().get(i))) { if (i - pathPosition > 2) { logDebug("Skipping forward " + (i - pathPosition) + " steps, to " + i); From 4da0731664781630b8cabb842662ed362120d270 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Oct 2018 11:55:15 -0700 Subject: [PATCH 069/305] deterministic --- build.gradle | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/build.gradle b/build.gradle index 52f3e97c..0cca9190 100755 --- a/build.gradle +++ b/build.gradle @@ -89,3 +89,8 @@ mixin { jar { from sourceSets.launch.output, sourceSets.api.output } + +tasks.withType(AbstractArchiveTask) { + preserveFileTimestamps = false + reproducibleFileOrder = true +} From 80240cb9f214a182ec024b34df4db89d6bee39e4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Oct 2018 14:23:29 -0700 Subject: [PATCH 070/305] maybe needs to be higher --- build.gradle | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index 0cca9190..d55084e6 100755 --- a/build.gradle +++ b/build.gradle @@ -46,6 +46,11 @@ compileJava { sourceCompatibility = targetCompatibility = '1.8' } +tasks.withType(AbstractArchiveTask) { + preserveFileTimestamps = false + reproducibleFileOrder = true +} + sourceSets { launch { compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output @@ -89,8 +94,3 @@ mixin { jar { from sourceSets.launch.output, sourceSets.api.output } - -tasks.withType(AbstractArchiveTask) { - preserveFileTimestamps = false - reproducibleFileOrder = true -} From db8daf4c596ac91d0bed2ed1594a38027de19797 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Oct 2018 16:07:35 -0700 Subject: [PATCH 071/305] maybe in jar --- build.gradle | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index d55084e6..a678849a 100755 --- a/build.gradle +++ b/build.gradle @@ -46,7 +46,7 @@ compileJava { sourceCompatibility = targetCompatibility = '1.8' } -tasks.withType(AbstractArchiveTask) { +tasks.withType(RepackageTask) { preserveFileTimestamps = false reproducibleFileOrder = true } @@ -93,4 +93,6 @@ mixin { jar { from sourceSets.launch.output, sourceSets.api.output + preserveFileTimestamps = false + reproducibleFileOrder = true } From d1e62ef8f2e68de7bfb2a78eb3945aa10510a038 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Oct 2018 16:56:46 -0700 Subject: [PATCH 072/305] ok but really this time they're deterministic --- build.gradle | 53 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index a678849a..8a205281 100755 --- a/build.gradle +++ b/build.gradle @@ -1,3 +1,7 @@ +import java.util.jar.JarEntry +import java.util.jar.JarFile +import java.util.jar.JarOutputStream + /* * This file is part of Baritone. * @@ -46,11 +50,6 @@ compileJava { sourceCompatibility = targetCompatibility = '1.8' } -tasks.withType(RepackageTask) { - preserveFileTimestamps = false - reproducibleFileOrder = true -} - sourceSets { launch { compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output @@ -96,3 +95,47 @@ jar { preserveFileTimestamps = false reproducibleFileOrder = true } + +build { + // while "jar" supports preserveFileTimestamps false + // reobfJar doesn't, it just sets all the last modified times to that instant where it runs the reobfuscator + // so we have to set all those last modified times back to zero + doLast { + JarFile jf = new JarFile("build/libs/baritone-" + version + ".jar") + JarOutputStream jos = new JarOutputStream(new FileOutputStream(new File("build/libs/baritone-unoptimized-" + version + ".jar"))) + + + jf.entries().unique { it.name }.sort { it.name }.each { + cloneAndCopyEntry(jf, it, jos, 0) + } + jos.finish() + jf.close() + } +} + +void cloneAndCopyEntry(JarFile originalFile, JarEntry original, JarOutputStream jos, long newTimestamp) { + JarEntry clone = new JarEntry(original) + clone.time = newTimestamp + def entryIs = originalFile.getInputStream(original) + jos.putNextEntry(clone) + copyBinaryData(entryIs, jos) +} + +void copyBinaryData(InputStream is, JarOutputStream jos) { + byte[] buffer = new byte[1024] + int len = 0 + while ((len = is.read(buffer)) != -1) { + jos.write(buffer, 0, len) + } +} + +gradle.taskGraph.whenReady { taskGraph -> + println "Found task graph: " + taskGraph + println "Found " + taskGraph.allTasks.size() + " tasks." + taskGraph.allTasks.forEach { task -> + println task + task.dependsOn.forEach { dep -> + println " - " + dep + } + } +} \ No newline at end of file From 65ce5ca75212db77271d7c0ca854e7a9a32deee7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Oct 2018 16:57:04 -0700 Subject: [PATCH 073/305] fix nullpointerexception in cachedworld --- src/main/java/baritone/cache/CachedWorld.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index db626aca..cb05360b 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -142,7 +142,11 @@ public final class CachedWorld implements ICachedWorld, Helper { public final void save() { if (!Baritone.settings().chunkCaching.get()) { System.out.println("Not saving to disk; chunk caching is disabled."); - allRegions().forEach(CachedRegion::removeExpired); // even if we aren't saving to disk, still delete expired old chunks from RAM + allRegions().forEach(region -> { + if (region != null) { + region.removeExpired(); + } + }); // even if we aren't saving to disk, still delete expired old chunks from RAM return; } long start = System.nanoTime() / 1000000L; From b5347cebc30ec0b447aa44810a99744ed47ab665 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Oct 2018 17:02:21 -0700 Subject: [PATCH 074/305] cleanup build gradle --- build.gradle | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/build.gradle b/build.gradle index 8a205281..5707b408 100755 --- a/build.gradle +++ b/build.gradle @@ -101,15 +101,15 @@ build { // reobfJar doesn't, it just sets all the last modified times to that instant where it runs the reobfuscator // so we have to set all those last modified times back to zero doLast { - JarFile jf = new JarFile("build/libs/baritone-" + version + ".jar") - JarOutputStream jos = new JarOutputStream(new FileOutputStream(new File("build/libs/baritone-unoptimized-" + version + ".jar"))) - - + File jarFile = new File("build/libs/baritone-" + version + ".jar") + JarFile jf = new JarFile(jarFile) + JarOutputStream jos = new JarOutputStream(new FileOutputStream(new File("temp.jar"))) jf.entries().unique { it.name }.sort { it.name }.each { cloneAndCopyEntry(jf, it, jos, 0) } jos.finish() jf.close() + file("temp.jar").renameTo(jarFile) } } @@ -128,14 +128,3 @@ void copyBinaryData(InputStream is, JarOutputStream jos) { jos.write(buffer, 0, len) } } - -gradle.taskGraph.whenReady { taskGraph -> - println "Found task graph: " + taskGraph - println "Found " + taskGraph.allTasks.size() + " tasks." - taskGraph.allTasks.forEach { task -> - println task - task.dependsOn.forEach { dep -> - println " - " + dep - } - } -} \ No newline at end of file From 796b45601e20eb769bf1428e1c4d926c9325cccd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Oct 2018 17:39:13 -0700 Subject: [PATCH 075/305] add info about reproducibility --- IMPACT.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/IMPACT.md b/IMPACT.md index e8430ab5..6d963a34 100644 --- a/IMPACT.md +++ b/IMPACT.md @@ -18,6 +18,8 @@ For Impact 4.3, there is no Baritone integration yet, so you will want `baritone Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. +The build for `baritone-unoptimized-X.Y.Z.jar` is deterministic, and you can verify Travis did it properly by running `scripts/build.sh` yourself and comparing the shasum. The proguarded files (api and standalone) aren't yet reproducible, because proguard annoyingly includes the current timestamp into the final jar. + ### Building Baritone yourself There are a few steps to this - Clone this repository From 7481c98dbc057a3ab925d63027ad1ed371429e2c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Oct 2018 17:57:07 -0700 Subject: [PATCH 076/305] more documentation --- FEATURES.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 71cb7f6c..cd2a90fe 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -10,13 +10,16 @@ - **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 +- **Parkour place** Sprint jumping over a 3 block gap and placing the block to land on while executing the jump. It's really cool. # Pathing method -Baritone uses a modified version of A*. +Baritone uses A*, with some modifications: -- **Incremental cost backoff** Since most of the time Baritone only knows the terrain up to the render distance, it can't calculate a full path to the goal. Therefore it needs to select a segment to execute first (assuming it will calculate the next segment at the end of this one). It uses incremental cost backoff to select the best node by varying metrics, then paths to that node. This is unchanged from MineBot and I made a write-up that still applies. In essence, it keeps track of the best node by various increasing coefficients, then picks the node with the least coefficient that goes at least 5 blocks from the starting position. +- **Segmented calculation** Traditional A* calculates until the most promising node is in the goal, however in the environment of Minecraft with a limited render distance, we don't know the environment all the way to our goal. Baritone has three possible ways for path calculation to end: finding a path all the way to the goal, running out of time, or getting to the render distance. In the latter two scenarios, the selection of which segment to actually execute falls to the next item (incremental cost backoff). Whenever the path calculation thread finds that the best / most promising node is at the edge of loaded chunks, it increments a counter. If this happens more than 50 times (configurable), path calculation exits early. This happens with very low render distances. Otherwise, calculation continues until the timeout is hit (also configurable) or we find a path all the way to the goal. +- **Incremental cost backoff** When path calculation exits early without getting all the way to the goal, Baritone it needs to select a segment to execute first (assuming it will calculate the next segment at the end of this one). It uses incremental cost backoff to select the best node by varying metrics, then paths to that node. This is unchanged from MineBot and I made a write-up that still applies. In essence, it keeps track of the best node by various increasing coefficients, then picks the node with the least coefficient that goes at least 5 blocks from the starting position. - **Minimum improvement repropagation** The pathfinder ignores alternate routes that provide minimal improvements (less than 0.01 ticks of improvement), because the calculation cost of repropagating this to all connected nodes is much higher than the half-millisecond path time improvement it would get. -- **Backtrack cost favoring** While calculating the next segment, Baritone favors backtracking its current segment slightly, as a tiebreaker. This allows it to splice and jump onto the next segment as early as possible, if the next segment begins with a backtrack of the current one. Example +- **Backtrack cost favoring** While calculating the next segment, Baritone favors backtracking its current segment. The cost is decreased heavily, but is still positive (this won't cause it to backtrack if it doesn't need to). This allows it to splice and jump onto the next segment as early as possible, if the next segment begins with a backtrack of the current one. Example +- **Backtrack detection and pausing** While path calculation happens on a separate thread, the main game thread has access to the latest node considered, and the best path so far (those are rendered light blue and dark blue respectively). When the current best path (rendered dark blue) passes through the player's current position on the current path segment, path execution is paused (if it's safe to do so), because there's no point continuing forward if we're about to turn around and go back that same way. Note that the current best path as reported by the path calculation thread takes into account the incremental cost backoff system, so it's accurate to what the path calculation thread will actually pick once it finishes. # Configuring Baritone All the settings and documentation are here. @@ -30,6 +33,7 @@ The pathing goal can be set to any of these options: - **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 +- **GoalAxis** a block position on an axis or diagonal axis (so x=0, z=0, or x=z), and y=120 (configurable) 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. @@ -38,7 +42,6 @@ And finally `GoalComposite`. `GoalComposite` is a list of other goals, any one o Things it doesn't have yet - Trapdoors - Sprint jumping in a 1x2 corridor -- Parkour (jumping over gaps of any length) [IN PROGRESS] See issues for more. From 60c29fd1594cf42eb2675d59c1b867d96d1446cd Mon Sep 17 00:00:00 2001 From: leijurv Date: Sun, 7 Oct 2018 21:39:43 -0700 Subject: [PATCH 077/305] actually stop sprinting, fixes #199 --- src/main/java/baritone/pathing/path/PathExecutor.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index cc140941..4afd8b76 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -329,6 +329,7 @@ public class PathExecutor implements Helper { // first and foremost, if allowSprint is off, or if we don't have enough hunger, don't try and sprint if (!new CalculationContext().canSprint()) { + Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT,false); player().setSprinting(false); return; } @@ -341,6 +342,9 @@ public class PathExecutor implements Helper { return; } + // we'll take it from here, no need for minecraft to see we're holding down control and sprint for us + Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT,false); + // however, descend doesn't request sprinting, beceause it doesn't know the context of what movement comes after it Movement current = path.movements().get(pathPosition); if (current instanceof MovementDescend && pathPosition < path.length() - 2) { From e17cc79cb3951649fd6fe3356a840b83c016b2c4 Mon Sep 17 00:00:00 2001 From: leijurv Date: Sun, 7 Oct 2018 21:55:03 -0700 Subject: [PATCH 078/305] synchronize MemoryBehavior, fixes #198 --- .../java/baritone/behavior/MemoryBehavior.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 6570cbc2..a684556e 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -50,14 +50,14 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H private MemoryBehavior() {} @Override - public void onPlayerUpdate(PlayerUpdateEvent event) { + public synchronized void onPlayerUpdate(PlayerUpdateEvent event) { if (event.getState() == EventState.PRE) { updateInventory(); } } @Override - public void onSendPacket(PacketEvent event) { + public synchronized void onSendPacket(PacketEvent event) { Packet p = event.getPacket(); if (event.getState() == EventState.PRE) { @@ -83,7 +83,7 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H } @Override - public void onReceivePacket(PacketEvent event) { + public synchronized void onReceivePacket(PacketEvent event) { Packet p = event.getPacket(); if (event.getState() == EventState.PRE) { @@ -130,13 +130,14 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H } @Override - public final RememberedInventory getInventoryByPos(BlockPos pos) { + public final synchronized RememberedInventory getInventoryByPos(BlockPos pos) { return this.getCurrentContainer().rememberedInventories.get(pos); } @Override - public final Map getRememberedInventories() { - return Collections.unmodifiableMap(this.getCurrentContainer().rememberedInventories); + public final synchronized Map getRememberedInventories() { + // make a copy since this map is modified from the packet thread + return new HashMap<>(this.getCurrentContainer().rememberedInventories); } private static final class WorldDataContainer { @@ -213,7 +214,7 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H @Override public final List getContents() { - return this.items; + return Collections.unmodifiableList(this.items); } @Override From 69762bf4b49809adcec5c925909c19f6561300f3 Mon Sep 17 00:00:00 2001 From: leijurv Date: Sun, 7 Oct 2018 22:07:49 -0700 Subject: [PATCH 079/305] fix parkour maybe? fixes #211 --- .../baritone/pathing/movement/movements/MovementParkour.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 2310f773..e128bb3c 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -224,7 +224,7 @@ public class MovementParkour extends Movement { } state.setInput(InputOverrideHandler.Input.JUMP, true); - } else { + } else if(!playerFeet().equals(dest.offset(direction, -1))) { state.setInput(InputOverrideHandler.Input.SPRINT, false); if (playerFeet().equals(src.offset(direction, -1))) { MovementHelper.moveTowards(state, src); From 10bb177664902eb267081d3a03176d119e3508e1 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 17:06:41 -0500 Subject: [PATCH 080/305] Add renderGoalIgnoreDepth setting --- src/api/java/baritone/api/Settings.java | 5 +++ .../java/baritone/utils/PathRenderer.java | 37 +++++++++---------- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 00d4af85..81069e1f 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -302,6 +302,11 @@ public class Settings { */ public Setting renderGoal = new Setting<>(true); + /** + * Ignore depth when rendering the goal + */ + public Setting renderGoalIgnoreDepth = new Setting<>(false); + /** * Line width of the path when rendered, in pixels */ diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 3f4dbe59..ba39a06a 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -232,26 +232,12 @@ public final class PathRenderer implements Helper { 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(); - BUFFER.pos(maxX, y1, minZ).endVertex(); - BUFFER.pos(maxX, y1, maxZ).endVertex(); - BUFFER.pos(minX, y1, maxZ).endVertex(); - BUFFER.pos(minX, y1, minZ).endVertex(); - TESSELLATOR.draw(); + if (Baritone.settings().renderGoalIgnoreDepth.get()) { + GlStateManager.disableDepth(); } - if (y2 != 0) { - BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); - BUFFER.pos(minX, y2, minZ).endVertex(); - BUFFER.pos(maxX, y2, minZ).endVertex(); - BUFFER.pos(maxX, y2, maxZ).endVertex(); - BUFFER.pos(minX, y2, maxZ).endVertex(); - BUFFER.pos(minX, y2, minZ).endVertex(); - TESSELLATOR.draw(); - } + renderHorizontalQuad(minX, maxX, minZ, maxZ, y1); + renderHorizontalQuad(minX, maxX, minZ, maxZ, y2); BUFFER.begin(GL_LINES, DefaultVertexFormats.POSITION); BUFFER.pos(minX, minY, minZ).endVertex(); @@ -264,9 +250,22 @@ public final class PathRenderer implements Helper { BUFFER.pos(minX, maxY, maxZ).endVertex(); TESSELLATOR.draw(); - + if (Baritone.settings().renderGoalIgnoreDepth.get()) { + GlStateManager.enableDepth(); + } GlStateManager.depthMask(true); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); } + + private static void renderHorizontalQuad(double minX, double maxX, double minZ, double maxZ, double y) { + if (y != 0) { + BUFFER.begin(GL_LINE_LOOP, DefaultVertexFormats.POSITION); + BUFFER.pos(minX, y, minZ).endVertex(); + BUFFER.pos(maxX, y, minZ).endVertex(); + BUFFER.pos(maxX, y, maxZ).endVertex(); + BUFFER.pos(minX, y, maxZ).endVertex(); + TESSELLATOR.draw(); + } + } } From 5a9e5cdac416c0810c376f63549ebe6408656381 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 8 Oct 2018 15:11:07 -0700 Subject: [PATCH 081/305] move rendering, fixes #212 --- .../baritone/behavior/PathingBehavior.java | 52 +--------------- .../java/baritone/utils/PathRenderer.java | 60 +++++++++++++++++++ 2 files changed, 61 insertions(+), 51 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 15748432..2092c656 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -42,7 +42,6 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; import java.util.Collection; -import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.stream.Collectors; @@ -388,56 +387,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, @Override public void onRenderPass(RenderEvent event) { - // System.out.println("Render passing"); - // System.out.println(event.getPartialTicks()); - float partialTicks = event.getPartialTicks(); - if (goal != null && Baritone.settings().renderGoal.value) { - PathRenderer.drawLitDankGoalBox(player(), goal, partialTicks, Baritone.settings().colorGoalBox.get()); - } - if (!Baritone.settings().renderPath.get()) { - return; - } - - //long start = System.nanoTime(); - - - PathExecutor current = this.current; // this should prevent most race conditions? - PathExecutor next = this.next; // like, now it's not possible for current!=null to be true, then suddenly false because of another thread - // TODO is this enough, or do we need to acquire a lock here? - // TODO benchmark synchronized in render loop - - // Render the current path, if there is one - if (current != null && current.getPath() != null) { - int renderBegin = Math.max(current.getPosition() - 3, 0); - PathRenderer.drawPath(current.getPath(), renderBegin, player(), partialTicks, Baritone.settings().colorCurrentPath.get(), Baritone.settings().fadePath.get(), 10, 20); - } - if (next != null && next.getPath() != null) { - PathRenderer.drawPath(next.getPath(), 0, player(), partialTicks, Baritone.settings().colorNextPath.get(), Baritone.settings().fadePath.get(), 10, 20); - } - - //long split = System.nanoTime(); - if (current != null) { - PathRenderer.drawManySelectionBoxes(player(), current.toBreak(), partialTicks, Baritone.settings().colorBlocksToBreak.get()); - PathRenderer.drawManySelectionBoxes(player(), current.toPlace(), partialTicks, Baritone.settings().colorBlocksToPlace.get()); - PathRenderer.drawManySelectionBoxes(player(), current.toWalkInto(), partialTicks, Baritone.settings().colorBlocksToWalkInto.get()); - } - - // If there is a path calculation currently running, render the path calculation process - AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(currentlyRunning -> { - currentlyRunning.bestPathSoFar().ifPresent(p -> { - PathRenderer.drawPath(p, 0, player(), partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20); - }); - currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { - - PathRenderer.drawPath(mr, 0, player(), partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); - PathRenderer.drawManySelectionBoxes(player(), Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); - }); - }); - //long end = System.nanoTime(); - //System.out.println((end - split) + " " + (split - start)); - // if (end - start > 0) { - // System.out.println("Frame took " + (split - start) + " " + (end - split)); - //} + PathRenderer.render(event, this); } @Override diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index ba39a06a..6891a299 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -18,12 +18,16 @@ package baritone.utils; import baritone.Baritone; +import baritone.api.event.events.RenderEvent; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.interfaces.IGoalRenderPos; +import baritone.behavior.PathingBehavior; +import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.path.IPath; +import baritone.pathing.path.PathExecutor; import baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -40,6 +44,7 @@ import net.minecraft.util.math.MathHelper; import java.awt.*; import java.util.Collection; +import java.util.Collections; import java.util.List; import static org.lwjgl.opengl.GL11.*; @@ -55,6 +60,61 @@ public final class PathRenderer implements Helper { private PathRenderer() {} + public static void render(RenderEvent event, PathingBehavior behavior) { + // System.out.println("Render passing"); + // System.out.println(event.getPartialTicks()); + float partialTicks = event.getPartialTicks(); + Goal goal = behavior.getGoal(); + EntityPlayerSP player = mc.player; + if (goal != null && Baritone.settings().renderGoal.value) { + PathRenderer.drawLitDankGoalBox(player, goal, partialTicks, Baritone.settings().colorGoalBox.get()); + } + if (!Baritone.settings().renderPath.get()) { + return; + } + + //long start = System.nanoTime(); + + + PathExecutor current = behavior.getCurrent(); // this should prevent most race conditions? + PathExecutor next = behavior.getNext(); // like, now it's not possible for current!=null to be true, then suddenly false because of another thread + // TODO is this enough, or do we need to acquire a lock here? + // TODO benchmark synchronized in render loop + + // Render the current path, if there is one + if (current != null && current.getPath() != null) { + int renderBegin = Math.max(current.getPosition() - 3, 0); + PathRenderer.drawPath(current.getPath(), renderBegin, player, partialTicks, Baritone.settings().colorCurrentPath.get(), Baritone.settings().fadePath.get(), 10, 20); + } + if (next != null && next.getPath() != null) { + PathRenderer.drawPath(next.getPath(), 0, player, partialTicks, Baritone.settings().colorNextPath.get(), Baritone.settings().fadePath.get(), 10, 20); + } + + //long split = System.nanoTime(); + if (current != null) { + PathRenderer.drawManySelectionBoxes(player, current.toBreak(), partialTicks, Baritone.settings().colorBlocksToBreak.get()); + PathRenderer.drawManySelectionBoxes(player, current.toPlace(), partialTicks, Baritone.settings().colorBlocksToPlace.get()); + PathRenderer.drawManySelectionBoxes(player, current.toWalkInto(), partialTicks, Baritone.settings().colorBlocksToWalkInto.get()); + } + + // If there is a path calculation currently running, render the path calculation process + AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(currentlyRunning -> { + currentlyRunning.bestPathSoFar().ifPresent(p -> { + PathRenderer.drawPath(p, 0, player, partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20); + }); + currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { + + PathRenderer.drawPath(mr, 0, player, partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); + PathRenderer.drawManySelectionBoxes(player, Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); + }); + }); + //long end = System.nanoTime(); + //System.out.println((end - split) + " " + (split - start)); + // if (end - start > 0) { + // System.out.println("Frame took " + (split - start) + " " + (end - split)); + //} + } + public static void drawPath(IPath path, int startIndex, EntityPlayerSP player, float partialTicks, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); From 0ee14b4b905c179f440005efc5e69e0a34b460b2 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 17:12:51 -0500 Subject: [PATCH 082/305] Good javadocs They're not good they're shit I lied to you --- src/api/java/baritone/api/Settings.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 81069e1f..f69ee6dc 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -485,7 +485,14 @@ public class Settings { */ public Setting colorGoalBox = new Setting<>(Color.GREEN); + /** + * A map of lowercase setting field names to their respective setting + */ public final Map> byLowerName; + + /** + * A list of all settings + */ public final List> allSettings; public class Setting { From 336154fd9b47dcc2cbea19b51c2cd9b6c8a4ad3b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 8 Oct 2018 15:25:03 -0700 Subject: [PATCH 083/305] clean up build and remove unnecessary files --- build.gradle | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/build.gradle b/build.gradle index 5707b408..d3f69d43 100755 --- a/build.gradle +++ b/build.gradle @@ -105,7 +105,12 @@ build { JarFile jf = new JarFile(jarFile) JarOutputStream jos = new JarOutputStream(new FileOutputStream(new File("temp.jar"))) jf.entries().unique { it.name }.sort { it.name }.each { - cloneAndCopyEntry(jf, it, jos, 0) + if (it.name != "META-INF/fml_cache_annotation.json" && it.name != "META-INF/fml_cache_class_versions.json") { + JarEntry clone = new JarEntry(it) + clone.time = 0 + jos.putNextEntry(clone) + copy(jf.getInputStream(it), jos) + } } jos.finish() jf.close() @@ -113,18 +118,10 @@ build { } } -void cloneAndCopyEntry(JarFile originalFile, JarEntry original, JarOutputStream jos, long newTimestamp) { - JarEntry clone = new JarEntry(original) - clone.time = newTimestamp - def entryIs = originalFile.getInputStream(original) - jos.putNextEntry(clone) - copyBinaryData(entryIs, jos) -} - -void copyBinaryData(InputStream is, JarOutputStream jos) { +void copy(InputStream is, OutputStream os) { byte[] buffer = new byte[1024] int len = 0 while ((len = is.read(buffer)) != -1) { - jos.write(buffer, 0, len) + os.write(buffer, 0, len) } } From 1245e222a761ffc3ac4e8be831b01140e5b057df Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 19:23:43 -0500 Subject: [PATCH 084/305] Begin path api prep --- .../baritone/behavior/PathingBehavior.java | 26 ++++++++- .../baritone/pathing/path/CutoffResult.java | 54 +++++++++++++++++++ .../java/baritone/pathing/path/IPath.java | 29 +++++----- 3 files changed, 90 insertions(+), 19 deletions(-) create mode 100644 src/main/java/baritone/pathing/path/CutoffResult.java diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 2092c656..16c88b92 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -30,6 +30,7 @@ import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.calc.IPathFinder; import baritone.pathing.movement.MovementHelper; +import baritone.pathing.path.CutoffResult; import baritone.pathing.path.IPath; import baritone.pathing.path.PathExecutor; import baritone.utils.BlockBreakHelper; @@ -283,9 +284,30 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, Optional path = findPath(start, previous); if (Baritone.settings().cutoffAtLoadBoundary.get()) { - path = path.map(IPath::cutoffAtLoadedChunks); + path = path.map(p -> { + CutoffResult result = p.cutoffAtLoadedChunks(); + + if (result.wasCut()) { + logDebug("Cutting off path at edge of loaded chunks"); + logDebug("Length decreased by " + result.getRemoved()); + } else { + logDebug("Path ends within loaded chunks"); + } + + return result.getPath(); + }); } - Optional executor = path.map(p -> p.staticCutoff(goal)).map(PathExecutor::new); + + Optional executor = path.map(p -> { + CutoffResult result = p.staticCutoff(goal); + + if (result.wasCut()) { + logDebug("Static cutoff " + p.length() + " to " + result.getPath().length()); + } + + return result.getPath(); + }).map(PathExecutor::new); + synchronized (pathPlanLock) { if (current == null) { if (executor.isPresent()) { diff --git a/src/main/java/baritone/pathing/path/CutoffResult.java b/src/main/java/baritone/pathing/path/CutoffResult.java new file mode 100644 index 00000000..d1c03c1e --- /dev/null +++ b/src/main/java/baritone/pathing/path/CutoffResult.java @@ -0,0 +1,54 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.pathing.path; + +/** + * @author Brady + * @since 10/8/2018 + */ +public final class CutoffResult { + + private final IPath path; + + private final int removed; + + private CutoffResult(IPath path, int removed) { + this.path = path; + this.removed = removed; + } + + public final boolean wasCut() { + return this.removed > 0; + } + + public final int getRemoved() { + return this.removed; + } + + public final IPath getPath() { + return this.path; + } + + public static CutoffResult cutoffPath(IPath path, int index) { + return new CutoffResult(new CutoffPath(path, index), path.positions().size() - index - 1); + } + + public static CutoffResult preservePath(IPath path) { + return new CutoffResult(path, 0); + } +} diff --git a/src/main/java/baritone/pathing/path/IPath.java b/src/main/java/baritone/pathing/path/IPath.java index 0701abf6..5741c440 100644 --- a/src/main/java/baritone/pathing/path/IPath.java +++ b/src/main/java/baritone/pathing/path/IPath.java @@ -17,10 +17,9 @@ package baritone.pathing.path; -import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.Goal; import baritone.pathing.movement.Movement; -import baritone.utils.Helper; import baritone.utils.Utils; import baritone.utils.pathing.BetterBlockPos; import net.minecraft.client.Minecraft; @@ -33,7 +32,7 @@ import java.util.List; /** * @author leijurv */ -public interface IPath extends Helper { +public interface IPath { /** * Ordered list of movements to carry out. @@ -87,7 +86,7 @@ public interface IPath extends Helper { /** * Where does this path start */ - default BetterBlockPos getSrc() { + default BlockPos getSrc() { return positions().get(0); } @@ -110,29 +109,25 @@ public interface IPath extends Helper { int getNumNodesConsidered(); - default IPath cutoffAtLoadedChunks() { + default CutoffResult cutoffAtLoadedChunks() { for (int i = 0; i < positions().size(); i++) { BlockPos pos = positions().get(i); if (Minecraft.getMinecraft().world.getChunk(pos) instanceof EmptyChunk) { - logDebug("Cutting off path at edge of loaded chunks"); - logDebug("Length decreased by " + (positions().size() - i - 1)); - return new CutoffPath(this, i); + return CutoffResult.cutoffPath(this, i); } } - logDebug("Path ends within loaded chunks"); - return this; + return CutoffResult.preservePath(this); } - default IPath staticCutoff(Goal destination) { - if (length() < Baritone.settings().pathCutoffMinimumLength.get()) { - return this; + default CutoffResult staticCutoff(Goal destination) { + if (length() < BaritoneAPI.getSettings().pathCutoffMinimumLength.get()) { + return CutoffResult.preservePath(this); } if (destination == null || destination.isInGoal(getDest())) { - return this; + return CutoffResult.preservePath(this); } - double factor = Baritone.settings().pathCutoffFactor.get(); + double factor = BaritoneAPI.getSettings().pathCutoffFactor.get(); int newLength = (int) (length() * factor); - logDebug("Static cutoff " + length() + " to " + newLength); - return new CutoffPath(this, newLength); + return CutoffResult.cutoffPath(this, newLength); } } From d177db5a35ba146876b8540bdb116e36dee06713 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 19:57:22 -0500 Subject: [PATCH 085/305] IMovement Hey would you look at that --- src/main/java/baritone/pathing/calc/Path.java | 3 +- .../pathing/movement/CalculationContext.java | 18 ++--- .../baritone/pathing/movement/IMovement.java | 67 +++++++++++++++++++ .../baritone/pathing/movement/Movement.java | 31 +++++++-- .../pathing/movement/MovementState.java | 4 -- .../pathing/movement/MovementStatus.java | 27 ++++++++ .../movement/movements/MovementAscend.java | 6 +- .../movement/movements/MovementDescend.java | 2 +- .../movement/movements/MovementDiagonal.java | 9 +-- .../movement/movements/MovementDownward.java | 9 +-- .../movement/movements/MovementFall.java | 2 +- .../movement/movements/MovementParkour.java | 15 ++--- .../movement/movements/MovementPillar.java | 17 ++--- .../movement/movements/MovementTraverse.java | 17 ++--- .../baritone/pathing/path/CutoffPath.java | 6 +- .../java/baritone/pathing/path/IPath.java | 8 +-- .../baritone/pathing/path/PathExecutor.java | 27 +++----- .../utils/ExampleBaritoneControl.java | 4 +- 18 files changed, 179 insertions(+), 93 deletions(-) create mode 100644 src/main/java/baritone/pathing/movement/IMovement.java create mode 100644 src/main/java/baritone/pathing/movement/MovementStatus.java diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index f1a31553..6606cfba 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -18,6 +18,7 @@ package baritone.pathing.calc; import baritone.api.pathing.goals.Goal; +import baritone.pathing.movement.IMovement; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.pathing.path.IPath; @@ -161,7 +162,7 @@ class Path implements IPath { } @Override - public List movements() { + public List movements() { if (!verified) { throw new IllegalStateException(); } diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 0b40539e..464703ff 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -17,7 +17,7 @@ package baritone.pathing.movement; -import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.pathing.movement.ActionCosts; import baritone.utils.Helper; import baritone.utils.ToolSet; @@ -51,20 +51,20 @@ public class CalculationContext implements Helper { public CalculationContext(ToolSet toolSet) { this.toolSet = toolSet; - this.hasThrowaway = Baritone.settings().allowPlace.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(); + this.hasThrowaway = BaritoneAPI.getSettings().allowPlace.get() && MovementHelper.throwaway(false); + this.hasWaterBucket = BaritoneAPI.getSettings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_WATER)) && !world().provider.isNether(); + this.canSprint = BaritoneAPI.getSettings().allowSprint.get() && player().getFoodStats().getFoodLevel() > 6; + this.placeBlockCost = BaritoneAPI.getSettings().blockPlacementPenalty.get(); + this.allowBreak = BaritoneAPI.getSettings().allowBreak.get(); + this.maxFallHeightNoWater = BaritoneAPI.getSettings().maxFallHeightNoWater.get(); + this.maxFallHeightBucket = BaritoneAPI.getSettings().maxFallHeightBucket.get(); int depth = EnchantmentHelper.getDepthStriderModifier(player()); if (depth > 3) { depth = 3; } float mult = depth / 3.0F; this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - mult) + ActionCosts.WALK_ONE_BLOCK_COST * mult; - this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.get(); + this.breakBlockAdditionalCost = BaritoneAPI.getSettings().blockBreakAdditionalPenalty.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. diff --git a/src/main/java/baritone/pathing/movement/IMovement.java b/src/main/java/baritone/pathing/movement/IMovement.java new file mode 100644 index 00000000..83b65019 --- /dev/null +++ b/src/main/java/baritone/pathing/movement/IMovement.java @@ -0,0 +1,67 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.pathing.movement; + +import baritone.utils.pathing.BetterBlockPos; +import net.minecraft.util.math.BlockPos; + +import java.util.List; + +/** + * @author Brady + * @since 10/8/2018 + */ +public interface IMovement { + + double getCost(); + + MovementStatus update(); + + /** + * Resets the current state status to {@link MovementStatus#PREPPING} + */ + void reset(); + + /** + * Resets the cache for special break, place, and walk into blocks + */ + void resetBlockCache(); + + /** + * @return Whether or not it is safe to cancel the current movement state + */ + boolean safeToCancel(); + + double recalculateCost(); + + double calculateCostWithoutCaching(); + + boolean calculatedWhileLoaded(); + + BetterBlockPos getSrc(); + + BetterBlockPos getDest(); + + BlockPos getDirection(); + + List toBreak(); + + List toPlace(); + + List toWalkInto(); +} diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 2b87c1e0..b529873a 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -21,7 +21,6 @@ import baritone.Baritone; import baritone.api.utils.Rotation; import baritone.behavior.LookBehavior; import baritone.behavior.LookBehaviorUtils; -import baritone.pathing.movement.MovementState.MovementStatus; import baritone.utils.*; import baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.BlockLiquid; @@ -36,7 +35,7 @@ import java.util.Optional; import static baritone.utils.InputOverrideHandler.Input; -public abstract class Movement implements Helper, MovementHelper { +public abstract class Movement implements IMovement, Helper, MovementHelper { protected static final EnumFacing[] HORIZONTALS = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST}; @@ -64,7 +63,7 @@ public abstract class Movement implements Helper, MovementHelper { public List toPlaceCached = null; public List toWalkIntoCached = null; - private Boolean calculatedWhileLoaded; + private boolean calculatedWhileLoaded; protected Movement(BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak, BetterBlockPos toPlace) { this.src = src; @@ -77,24 +76,27 @@ public abstract class Movement implements Helper, MovementHelper { this(src, dest, toBreak, null); } - public double getCost(CalculationContext context) { + @Override + public double getCost() { if (cost == null) { - cost = calculateCost(context != null ? context : new CalculationContext()); + cost = calculateCost(new CalculationContext()); } return cost; } protected abstract double calculateCost(CalculationContext context); + @Override public double recalculateCost() { cost = null; - return getCost(null); + return getCost(); } protected void override(double cost) { this.cost = cost; } + @Override public double calculateCostWithoutCaching() { return calculateCost(new CalculationContext()); } @@ -105,6 +107,7 @@ public abstract class Movement implements Helper, MovementHelper { * * @return Status */ + @Override public MovementStatus update() { player().capabilities.allowFlying = false; MovementState latestState = updateState(currentState); @@ -187,6 +190,7 @@ public abstract class Movement implements Helper, MovementHelper { return true; } + @Override public boolean safeToCancel() { return safeToCancel(currentState); } @@ -201,10 +205,12 @@ public abstract class Movement implements Helper, MovementHelper { && currentState.getStatus() != MovementStatus.WAITING); } + @Override public BetterBlockPos getSrc() { return src; } + @Override public BetterBlockPos getDest() { return dest; } @@ -223,6 +229,7 @@ public abstract class Movement implements Helper, MovementHelper { currentState.setStatus(MovementStatus.CANCELED); } + @Override public void reset() { currentState = new MovementState().setStatus(MovementStatus.PREPPING); } @@ -247,6 +254,7 @@ public abstract class Movement implements Helper, MovementHelper { return state; } + @Override public BlockPos getDirection() { return getDest().subtract(getSrc()); } @@ -255,10 +263,19 @@ public abstract class Movement implements Helper, MovementHelper { calculatedWhileLoaded = !(world().getChunk(getDest()) instanceof EmptyChunk); } + @Override public boolean calculatedWhileLoaded() { return calculatedWhileLoaded; } + @Override + public void resetBlockCache() { + toBreakCached = null; + toPlaceCached = null; + toWalkIntoCached = null; + } + + @Override public List toBreak() { if (toBreakCached != null) { return toBreakCached; @@ -273,6 +290,7 @@ public abstract class Movement implements Helper, MovementHelper { return result; } + @Override public List toPlace() { if (toPlaceCached != null) { return toPlaceCached; @@ -285,6 +303,7 @@ public abstract class Movement implements Helper, MovementHelper { return result; } + @Override public List toWalkInto() { // overridden by movementdiagonal if (toWalkIntoCached == null) { toWalkIntoCached = new ArrayList<>(); diff --git a/src/main/java/baritone/pathing/movement/MovementState.java b/src/main/java/baritone/pathing/movement/MovementState.java index 6d0262e6..acf223d4 100644 --- a/src/main/java/baritone/pathing/movement/MovementState.java +++ b/src/main/java/baritone/pathing/movement/MovementState.java @@ -72,10 +72,6 @@ public class MovementState { return this.inputState; } - public enum MovementStatus { - PREPPING, WAITING, RUNNING, SUCCESS, UNREACHABLE, FAILED, CANCELED - } - public static class MovementTarget { /** diff --git a/src/main/java/baritone/pathing/movement/MovementStatus.java b/src/main/java/baritone/pathing/movement/MovementStatus.java new file mode 100644 index 00000000..4b4b92c3 --- /dev/null +++ b/src/main/java/baritone/pathing/movement/MovementStatus.java @@ -0,0 +1,27 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.pathing.movement; + +/** + * @author Brady + * @since 10/8/2018 + */ +public enum MovementStatus { + + PREPPING, WAITING, RUNNING, SUCCESS, UNREACHABLE, FAILED, CANCELED +} diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index b5e21eea..9ad42d99 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -19,11 +19,7 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.behavior.LookBehaviorUtils; -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.*; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; import baritone.utils.Utils; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 3bba5f1d..227a6b89 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -22,7 +22,7 @@ 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.MovementStatus; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; import baritone.utils.pathing.BetterBlockPos; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 58027a8d..b8ef01c3 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -17,10 +17,7 @@ package baritone.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.*; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; import baritone.utils.pathing.BetterBlockPos; @@ -140,12 +137,12 @@ public class MovementDiagonal extends Movement { @Override public MovementState updateState(MovementState state) { super.updateState(state); - if (state.getStatus() != MovementState.MovementStatus.RUNNING) { + if (state.getStatus() != MovementStatus.RUNNING) { return state; } if (playerFeet().equals(dest)) { - state.setStatus(MovementState.MovementStatus.SUCCESS); + state.setStatus(MovementStatus.SUCCESS); return state; } if (!BlockStateInterface.isLiquid(playerFeet())) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java index 148dc3b3..d808d993 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java @@ -17,10 +17,7 @@ package baritone.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.*; import baritone.utils.BlockStateInterface; import baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.Block; @@ -64,12 +61,12 @@ public class MovementDownward extends Movement { @Override public MovementState updateState(MovementState state) { super.updateState(state); - if (state.getStatus() != MovementState.MovementStatus.RUNNING) { + if (state.getStatus() != MovementStatus.RUNNING) { return state; } if (playerFeet().equals(dest)) { - return state.setStatus(MovementState.MovementStatus.SUCCESS); + return state.setStatus(MovementStatus.SUCCESS); } double diffX = player().posX - (dest.getX() + 0.5); double diffZ = player().posZ - (dest.getZ() + 0.5); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index f901c61f..3ce2848f 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -23,7 +23,7 @@ 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.MovementStatus; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index e128bb3c..7ecb4c04 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -20,10 +20,7 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.utils.Rotation; import baritone.behavior.LookBehaviorUtils; -import baritone.pathing.movement.CalculationContext; -import baritone.pathing.movement.Movement; -import baritone.pathing.movement.MovementHelper; -import baritone.pathing.movement.MovementState; +import baritone.pathing.movement.*; import baritone.utils.*; import baritone.utils.pathing.BetterBlockPos; import baritone.utils.pathing.MutableMoveResult; @@ -168,13 +165,13 @@ public class MovementParkour extends Movement { // once this movement is instantiated, the state is default to PREPPING // but once it's ticked for the first time it changes to RUNNING // since we don't really know anything about momentum, it suffices to say Parkour can only be canceled on the 0th tick - return state.getStatus() != MovementState.MovementStatus.RUNNING; + return state.getStatus() != MovementStatus.RUNNING; } @Override public MovementState updateState(MovementState state) { super.updateState(state); - if (state.getStatus() != MovementState.MovementStatus.RUNNING) { + if (state.getStatus() != MovementStatus.RUNNING) { return state; } if (dist >= 4) { @@ -186,10 +183,10 @@ public class MovementParkour extends Movement { if (d == Blocks.VINE || d == Blocks.LADDER) { // it physically hurt me to add support for parkour jumping onto a vine // but i did it anyway - return state.setStatus(MovementState.MovementStatus.SUCCESS); + return state.setStatus(MovementStatus.SUCCESS); } if (player().posY - playerFeet().getY() < 0.094) { // lilypads - state.setStatus(MovementState.MovementStatus.SUCCESS); + state.setStatus(MovementStatus.SUCCESS); } } else if (!playerFeet().equals(src)) { if (playerFeet().equals(src.offset(direction)) || player().posY - playerFeet().getY() > 0.0001) { @@ -203,7 +200,7 @@ public class MovementParkour extends Movement { } if (MovementHelper.canPlaceAgainst(against1)) { if (!MovementHelper.throwaway(true)) {//get ready to place a throwaway block - return state.setStatus(MovementState.MovementStatus.UNREACHABLE); + return state.setStatus(MovementStatus.UNREACHABLE); } double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + against1.getY()) * 0.5D; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index be524185..7680fb43 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -18,10 +18,7 @@ package baritone.pathing.movement.movements; import baritone.api.utils.Rotation; -import baritone.pathing.movement.CalculationContext; -import baritone.pathing.movement.Movement; -import baritone.pathing.movement.MovementHelper; -import baritone.pathing.movement.MovementState; +import baritone.pathing.movement.*; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; import baritone.utils.Utils; @@ -148,7 +145,7 @@ public class MovementPillar extends Movement { @Override public MovementState updateState(MovementState state) { super.updateState(state); - if (state.getStatus() != MovementState.MovementStatus.RUNNING) { + if (state.getStatus() != MovementStatus.RUNNING) { return state; } @@ -161,7 +158,7 @@ public class MovementPillar extends Movement { state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); } if (playerFeet().equals(dest)) { - return state.setStatus(MovementState.MovementStatus.SUCCESS); + return state.setStatus(MovementStatus.SUCCESS); } return state; } @@ -178,11 +175,11 @@ public class MovementPillar extends Movement { BlockPos against = vine ? getAgainst(src) : src.offset(fromDown.getValue(BlockLadder.FACING).getOpposite()); if (against == null) { logDebug("Unable to climb vines"); - return state.setStatus(MovementState.MovementStatus.UNREACHABLE); + return state.setStatus(MovementStatus.UNREACHABLE); } if (playerFeet().equals(against.up()) || playerFeet().equals(dest)) { - return state.setStatus(MovementState.MovementStatus.SUCCESS); + return state.setStatus(MovementStatus.SUCCESS); } if (MovementHelper.isBottomSlab(src.down())) { state.setInput(InputOverrideHandler.Input.JUMP, true); @@ -198,7 +195,7 @@ public class MovementPillar extends Movement { } else { // Get ready to place a throwaway block if (!MovementHelper.throwaway(true)) { - return state.setStatus(MovementState.MovementStatus.UNREACHABLE); + return state.setStatus(MovementStatus.UNREACHABLE); } numTicks++; @@ -233,7 +230,7 @@ public class MovementPillar extends Movement { // If we are at our goal and the block below us is placed if (playerFeet().equals(dest) && blockIsThere) { - return state.setStatus(MovementState.MovementStatus.SUCCESS); + return state.setStatus(MovementStatus.SUCCESS); } return state; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 7c4ba237..00000ac4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -20,10 +20,7 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.utils.Rotation; import baritone.behavior.LookBehaviorUtils; -import baritone.pathing.movement.CalculationContext; -import baritone.pathing.movement.Movement; -import baritone.pathing.movement.MovementHelper; -import baritone.pathing.movement.MovementState; +import baritone.pathing.movement.*; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; import baritone.utils.Utils; @@ -144,13 +141,13 @@ public class MovementTraverse extends Movement { @Override public MovementState updateState(MovementState state) { super.updateState(state); - if (state.getStatus() != MovementState.MovementStatus.RUNNING) { + if (state.getStatus() != MovementStatus.RUNNING) { // if the setting is enabled if (!Baritone.settings().walkWhileBreaking.get()) { return state; } // and if we're prepping (aka mining the block in front) - if (state.getStatus() != MovementState.MovementStatus.PREPPING) { + if (state.getStatus() != MovementStatus.PREPPING) { return state; } // and if it's fine to walk into the blocks in front @@ -225,7 +222,7 @@ public class MovementTraverse extends Movement { if (isTheBridgeBlockThere) { if (playerFeet().equals(dest)) { - return state.setStatus(MovementState.MovementStatus.SUCCESS); + return state.setStatus(MovementStatus.SUCCESS); } if (wasTheBridgeBlockAlwaysThere && !BlockStateInterface.isLiquid(playerFeet())) { state.setInput(InputOverrideHandler.Input.SPRINT, true); @@ -248,7 +245,7 @@ public class MovementTraverse extends Movement { if (MovementHelper.canPlaceAgainst(against1)) { if (!MovementHelper.throwaway(true)) { // get ready to place a throwaway block logDebug("bb pls get me some blocks. dirt or cobble"); - return state.setStatus(MovementState.MovementStatus.UNREACHABLE); + return state.setStatus(MovementStatus.UNREACHABLE); } if (!Baritone.settings().assumeSafeWalk.get()) { state.setInput(InputOverrideHandler.Input.SNEAK, true); @@ -287,7 +284,7 @@ public class MovementTraverse extends Movement { // Out.log(from + " " + to + " " + faceX + "," + faceY + "," + faceZ + " " + whereAmI); if (!MovementHelper.throwaway(true)) {// get ready to place a throwaway block logDebug("bb pls get me some blocks. dirt or cobble"); - return state.setStatus(MovementState.MovementStatus.UNREACHABLE); + return state.setStatus(MovementStatus.UNREACHABLE); } double faceX = (dest.getX() + src.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + src.getY() - 1.0D) * 0.5D; @@ -324,7 +321,7 @@ public class MovementTraverse extends Movement { // if we're in the process of breaking blocks before walking forwards // or if this isn't a sneak place (the block is already there) // then it's safe to cancel this - return state.getStatus() != MovementState.MovementStatus.RUNNING || MovementHelper.canWalkOn(dest.down()); + return state.getStatus() != MovementStatus.RUNNING || MovementHelper.canWalkOn(dest.down()); } @Override diff --git a/src/main/java/baritone/pathing/path/CutoffPath.java b/src/main/java/baritone/pathing/path/CutoffPath.java index e517452e..916b6c52 100644 --- a/src/main/java/baritone/pathing/path/CutoffPath.java +++ b/src/main/java/baritone/pathing/path/CutoffPath.java @@ -18,7 +18,7 @@ package baritone.pathing.path; import baritone.api.pathing.goals.Goal; -import baritone.pathing.movement.Movement; +import baritone.pathing.movement.IMovement; import baritone.utils.pathing.BetterBlockPos; import java.util.Collections; @@ -28,7 +28,7 @@ public class CutoffPath implements IPath { private final List path; - private final List movements; + private final List movements; private final int numNodes; @@ -47,7 +47,7 @@ public class CutoffPath implements IPath { } @Override - public List movements() { + public List movements() { return Collections.unmodifiableList(movements); } diff --git a/src/main/java/baritone/pathing/path/IPath.java b/src/main/java/baritone/pathing/path/IPath.java index 5741c440..afc1bce3 100644 --- a/src/main/java/baritone/pathing/path/IPath.java +++ b/src/main/java/baritone/pathing/path/IPath.java @@ -19,7 +19,7 @@ package baritone.pathing.path; import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.Goal; -import baritone.pathing.movement.Movement; +import baritone.pathing.movement.IMovement; import baritone.utils.Utils; import baritone.utils.pathing.BetterBlockPos; import net.minecraft.client.Minecraft; @@ -40,7 +40,7 @@ public interface IPath { * movements.get(i).getDest() should equal positions.get(i+1) * movements.size() should equal positions.size()-1 */ - List movements(); + List movements(); /** * All positions along the way. @@ -86,7 +86,7 @@ public interface IPath { /** * Where does this path start */ - default BlockPos getSrc() { + default BetterBlockPos getSrc() { return positions().get(0); } @@ -102,7 +102,7 @@ public interface IPath { double sum = 0; //this is fast because we aren't requesting recalculation, it's just cached for (int i = pathPosition; i < movements().size(); i++) { - sum += movements().get(i).getCost(null); + sum += movements().get(i).getCost(); } return sum; } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 4afd8b76..a60b4a29 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -21,10 +21,7 @@ import baritone.Baritone; import baritone.api.event.events.TickEvent; import baritone.api.pathing.movement.ActionCosts; import baritone.pathing.calc.AbstractNodeCostSearch; -import baritone.pathing.movement.CalculationContext; -import baritone.pathing.movement.Movement; -import baritone.pathing.movement.MovementHelper; -import baritone.pathing.movement.MovementState; +import baritone.pathing.movement.*; import baritone.pathing.movement.movements.*; import baritone.utils.*; import baritone.utils.pathing.BetterBlockPos; @@ -34,7 +31,7 @@ import net.minecraft.util.math.BlockPos; import java.util.*; -import static baritone.pathing.movement.MovementState.MovementStatus.*; +import static baritone.pathing.movement.MovementStatus.*; /** * Behavior to execute a precomputed path. Does not (yet) deal with path segmentation or stitching @@ -182,13 +179,11 @@ public class PathExecutor implements Helper { if (i < 0 || i >= path.movements().size()) { continue; } - Movement m = path.movements().get(i); + IMovement m = path.movements().get(i); HashSet prevBreak = new HashSet<>(m.toBreak()); HashSet prevPlace = new HashSet<>(m.toPlace()); HashSet prevWalkInto = new HashSet<>(m.toWalkInto()); - m.toBreakCached = null; - m.toPlaceCached = null; - m.toWalkIntoCached = null; + m.resetBlockCache(); if (!prevBreak.equals(new HashSet<>(m.toBreak()))) { recalcBP = true; } @@ -217,12 +212,12 @@ public class PathExecutor implements Helper { if (end - start > 0) { System.out.println("Recalculating break and place took " + (end - start) + "ms"); }*/ - Movement movement = path.movements().get(pathPosition); + IMovement movement = path.movements().get(pathPosition); boolean canCancel = movement.safeToCancel(); 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 - currentMovementOriginalCostEstimate = movement.getCost(null); + currentMovementOriginalCostEstimate = movement.getCost(); 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 && canCancel) { logDebug("Something has changed in the world and a future movement has become impossible. Cancelling."); @@ -246,7 +241,7 @@ public class PathExecutor implements Helper { logDebug("Pausing since current best path is a backtrack"); return true; } - MovementState.MovementStatus movementStatus = movement.update(); + MovementStatus movementStatus = movement.update(); if (movementStatus == UNREACHABLE || movementStatus == FAILED) { logDebug("Movement returns status " + movementStatus); cancel(); @@ -346,7 +341,7 @@ public class PathExecutor implements Helper { Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT,false); // however, descend doesn't request sprinting, beceause it doesn't know the context of what movement comes after it - Movement current = path.movements().get(pathPosition); + IMovement current = path.movements().get(pathPosition); if (current instanceof MovementDescend && pathPosition < path.length() - 2) { // (dest - src) + dest is offset 1 more in the same direction @@ -361,7 +356,7 @@ public class PathExecutor implements Helper { } } - Movement next = path.movements().get(pathPosition + 1); + IMovement next = path.movements().get(pathPosition + 1); if (next instanceof MovementAscend && current.getDirection().up().equals(next.getDirection().down())) { // a descend then an ascend in the same direction if (!player().isSprinting()) { @@ -385,7 +380,7 @@ public class PathExecutor implements Helper { //logDebug("Turning off sprinting " + movement + " " + next + " " + movement.getDirection() + " " + next.getDirection().down() + " " + next.getDirection().down().equals(movement.getDirection())); } if (current instanceof MovementAscend && pathPosition != 0) { - Movement prev = path.movements().get(pathPosition - 1); + IMovement prev = path.movements().get(pathPosition - 1); if (prev instanceof MovementDescend && prev.getDirection().up().equals(current.getDirection().down())) { BlockPos center = current.getSrc().up(); if (player().posY >= center.getY()) { // playerFeet adds 0.1251 to account for soul sand @@ -400,7 +395,7 @@ public class PathExecutor implements Helper { player().setSprinting(false); } - private static boolean canSprintInto(Movement current, Movement next) { + private static boolean canSprintInto(IMovement current, IMovement next) { if (next instanceof MovementDescend) { if (next.getDirection().equals(current.getDirection())) { return true; diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index cca6e3a2..fd733d7f 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -467,10 +467,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper { while (moves.contains(null)) { moves.remove(null); } - moves.sort(Comparator.comparingDouble(movement -> movement.getCost(new CalculationContext()))); + moves.sort(Comparator.comparingDouble(Movement::getCost)); for (Movement move : moves) { String[] parts = move.getClass().toString().split("\\."); - double cost = move.getCost(new CalculationContext()); + double cost = move.getCost(); String strCost = cost + ""; if (cost >= ActionCosts.COST_INF) { strCost = "IMPOSSIBLE"; From 1449edb8af81c9fbed3cbf5503480d41f14f738f Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 19:59:25 -0500 Subject: [PATCH 086/305] Didn't need to do that --- .../pathing/movement/CalculationContext.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 464703ff..0b40539e 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -17,7 +17,7 @@ package baritone.pathing.movement; -import baritone.api.BaritoneAPI; +import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; import baritone.utils.Helper; import baritone.utils.ToolSet; @@ -51,20 +51,20 @@ public class CalculationContext implements Helper { public CalculationContext(ToolSet toolSet) { this.toolSet = toolSet; - this.hasThrowaway = BaritoneAPI.getSettings().allowPlace.get() && MovementHelper.throwaway(false); - this.hasWaterBucket = BaritoneAPI.getSettings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_WATER)) && !world().provider.isNether(); - this.canSprint = BaritoneAPI.getSettings().allowSprint.get() && player().getFoodStats().getFoodLevel() > 6; - this.placeBlockCost = BaritoneAPI.getSettings().blockPlacementPenalty.get(); - this.allowBreak = BaritoneAPI.getSettings().allowBreak.get(); - this.maxFallHeightNoWater = BaritoneAPI.getSettings().maxFallHeightNoWater.get(); - this.maxFallHeightBucket = BaritoneAPI.getSettings().maxFallHeightBucket.get(); + this.hasThrowaway = Baritone.settings().allowPlace.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(); int depth = EnchantmentHelper.getDepthStriderModifier(player()); if (depth > 3) { depth = 3; } float mult = depth / 3.0F; this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - mult) + ActionCosts.WALK_ONE_BLOCK_COST * mult; - this.breakBlockAdditionalCost = BaritoneAPI.getSettings().blockBreakAdditionalPenalty.get(); + this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.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. From e23a9c976a6b1f4a618a4eac6da8442ef66739a8 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 20:01:44 -0500 Subject: [PATCH 087/305] Bad code --- src/main/java/baritone/pathing/movement/Movement.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index b529873a..bb699d0e 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -63,7 +63,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { public List toPlaceCached = null; public List toWalkIntoCached = null; - private boolean calculatedWhileLoaded; + private Boolean calculatedWhileLoaded; protected Movement(BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak, BetterBlockPos toPlace) { this.src = src; From 0f1edba5f1b2c74078a9bb6acce54815ac4503fa Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 8 Oct 2018 18:05:08 -0700 Subject: [PATCH 088/305] save settings --- src/api/java/baritone/api/BaritoneAPI.java | 2 + src/api/java/baritone/api/Settings.java | 2 + .../java/baritone/api/utils/SettingsUtil.java | 137 ++++++++++++++++++ .../utils/ExampleBaritoneControl.java | 3 + 4 files changed, 144 insertions(+) create mode 100644 src/api/java/baritone/api/utils/SettingsUtil.java diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index 7497454e..29238ea7 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -21,6 +21,7 @@ import baritone.api.behavior.*; import baritone.api.cache.IWorldProvider; import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IGameEventListener; +import baritone.api.utils.SettingsUtil; import java.util.Iterator; import java.util.ServiceLoader; @@ -44,6 +45,7 @@ public final class BaritoneAPI { baritone = instances.next(); settings = new Settings(); + SettingsUtil.readAndApply(settings); } public static IFollowBehavior getFollowBehavior() { diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index f69ee6dc..fcf84b3a 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -497,6 +497,7 @@ public class Settings { public class Setting { public T value; + public final T defaultValue; private String name; private final Class klass; @@ -506,6 +507,7 @@ public class Settings { throw new IllegalArgumentException("Cannot determine value type class from null"); } this.value = value; + this.defaultValue = value; this.klass = (Class) value.getClass(); } diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java new file mode 100644 index 00000000..219c17f7 --- /dev/null +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -0,0 +1,137 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils; + +import baritone.api.Settings; +import net.minecraft.client.Minecraft; +import net.minecraft.item.Item; +import net.minecraft.util.ResourceLocation; + +import java.awt.*; +import java.io.File; +import java.io.FileOutputStream; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class SettingsUtil { + private static final File settingsFile = new File(new File(Minecraft.getMinecraft().gameDir, "baritone"), "settings.txt"); + + private static final Map, SettingsIO> map; + + public static void readAndApply(Settings settings) { + try (Scanner scan = new Scanner(settingsFile)) { + while (scan.hasNextLine()) { + String line = scan.nextLine(); + if (line.isEmpty()) { + continue; + } + if (line.startsWith("#") || line.startsWith("//")) { + continue; + } + int space = line.indexOf(" "); + if (space == -1) { + System.out.println("Skipping invalid line with no space: " + line); + continue; + } + String settingName = line.substring(0, space).trim().toLowerCase(); + String settingValue = line.substring(space).trim(); + try { + parseAndApply(settings, settingName, settingValue); + } catch (Exception ex) { + ex.printStackTrace(); + System.out.println("Unable to parse line " + line); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + System.out.println("Exception while reading Baritone settings, some settings may be reset to default values!"); + } + } + + public static synchronized void save(Settings settings) { + try (FileOutputStream out = new FileOutputStream(settingsFile)) { + for (Settings.Setting setting : settings.allSettings) { + if (setting.get() == null) { + System.out.println("NULL SETTING?" + setting.getName()); + continue; + } + if (setting.getName().equals("logger")) { + continue; // NO + } + SettingsIO io = map.get(setting.getValueClass()); + if (io == null) { + throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting + " " + setting.getName()); + } + out.write((setting.getName() + " " + io.toString.apply(setting.get()) + "\n").getBytes()); + } + } catch (Exception ex) { + ex.printStackTrace(); + System.out.println("Exception while saving Baritone settings!"); + } + } + + private static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException { + Settings.Setting setting = settings.byLowerName.get(settingName); + if (setting == null) { + throw new IllegalStateException("No setting by that name"); + } + Class intendedType = setting.getValueClass(); + SettingsIO ioMethod = map.get(intendedType); + Object parsed = ioMethod.parser.apply(settingValue); + if (!intendedType.isInstance(parsed)) { + throw new IllegalStateException(ioMethod + " parser returned incorrect type, expected " + intendedType + " got " + parsed + " which is " + parsed.getClass()); + } + setting.value = parsed; + } + + private enum SettingsIO { + DOUBLE(Double.class, Double::parseDouble), + BOOLEAN(Boolean.class, Boolean::parseBoolean), + INTEGER(Integer.class, Integer::parseInt), + FLOAT(Float.class, Float::parseFloat), + LONG(Long.class, Long::parseLong), + + ITEM_LIST(ArrayList.class, str -> Stream.of(str.split(",")).map(Item::getByNameOrId).collect(Collectors.toCollection(ArrayList::new)), list -> ((ArrayList) list).stream().map(Item.REGISTRY::getNameForObject).map(ResourceLocation::toString).collect(Collectors.joining(","))), + COLOR(Color.class, str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])), color -> color.getRed() + "," + color.getGreen() + "," + color.getBlue()); + + + Class klass; + Function parser; + Function toString; + + SettingsIO(Class klass, Function parser) { + this(klass, parser, Object::toString); + } + + SettingsIO(Class klass, Function parser, Function toString) { + this.klass = klass; + this.parser = parser::apply; + this.toString = x -> toString.apply((T) x); + } + } + + static { + HashMap, SettingsIO> tempMap = new HashMap<>(); + for (SettingsIO type : SettingsIO.values()) { + tempMap.put(type.klass, type); + } + map = Collections.unmodifiableMap(tempMap); + } +} diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index cca6e3a2..683ec62b 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -23,6 +23,7 @@ import baritone.api.cache.IWaypoint; import baritone.api.event.events.ChatEvent; import baritone.api.pathing.goals.*; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.utils.SettingsUtil; import baritone.behavior.Behavior; import baritone.behavior.FollowBehavior; import baritone.behavior.MineBehavior; @@ -79,6 +80,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { setting.value ^= true; event.cancel(); logDirect("Toggled " + setting.getName() + " to " + setting.value); + SettingsUtil.save(Baritone.settings()); return; } } @@ -112,6 +114,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { event.cancel(); return; } + SettingsUtil.save(Baritone.settings()); logDirect(setting.toString()); event.cancel(); return; From 413e5056836013903eebb3068af5408550ac94ca Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 8 Oct 2018 18:08:01 -0700 Subject: [PATCH 089/305] epic --- src/api/java/baritone/api/utils/SettingsUtil.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 219c17f7..3e11d8e5 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -75,6 +75,9 @@ public class SettingsUtil { if (setting.getName().equals("logger")) { continue; // NO } + if (setting.value == setting.defaultValue) { + continue; + } SettingsIO io = map.get(setting.getValueClass()); if (io == null) { throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting + " " + setting.getName()); From 2b4512ee3f8ab8217c7ba81083d899ca92104b18 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 20:37:52 -0500 Subject: [PATCH 090/305] Move to API --- .../api/behavior/IPathingBehavior.java | 29 +++++++++++++++++++ .../api}/pathing/calc/IPathFinder.java | 4 +-- .../api}/pathing/movement/IMovement.java | 4 +-- .../api}/pathing/movement/MovementStatus.java | 2 +- .../api}/pathing/path/CutoffPath.java | 6 ++-- .../api}/pathing/path/CutoffResult.java | 2 +- .../baritone/api}/pathing/path/IPath.java | 21 ++------------ .../api/pathing/path/IPathExecutor.java | 27 +++++++++++++++++ .../baritone/api/utils}/BetterBlockPos.java | 26 ++++++++++++++--- .../launch/mixins/MixinMinecraft.java | 1 - .../java/baritone/behavior/MineBehavior.java | 6 ++-- .../baritone/behavior/PathingBehavior.java | 18 ++++++------ .../pathing/calc/AStarPathFinder.java | 7 +++-- .../pathing/calc/AbstractNodeCostSearch.java | 26 ++++------------- src/main/java/baritone/pathing/calc/Path.java | 6 ++-- .../java/baritone/pathing/calc/PathNode.java | 3 +- .../baritone/pathing/movement/Movement.java | 4 ++- .../pathing/movement/MovementHelper.java | 2 +- .../pathing/movement/MovementState.java | 1 + .../java/baritone/pathing/movement/Moves.java | 2 +- .../movement/movements/MovementAscend.java | 8 +++-- .../movement/movements/MovementDescend.java | 4 +-- .../movement/movements/MovementDiagonal.java | 8 +++-- .../movement/movements/MovementDownward.java | 8 +++-- .../movement/movements/MovementFall.java | 4 +-- .../movement/movements/MovementParkour.java | 8 +++-- .../movement/movements/MovementPillar.java | 8 +++-- .../movement/movements/MovementTraverse.java | 8 +++-- .../baritone/pathing/path/PathExecutor.java | 28 ++++++++++++++---- .../utils/ExampleBaritoneControl.java | 1 - src/main/java/baritone/utils/Helper.java | 2 +- .../java/baritone/utils/PathRenderer.java | 4 +-- .../utils/pathing/BetterBlockPosTest.java | 1 + 33 files changed, 190 insertions(+), 99 deletions(-) rename src/{main/java/baritone => api/java/baritone/api}/pathing/calc/IPathFinder.java (96%) rename src/{main/java/baritone => api/java/baritone/api}/pathing/movement/IMovement.java (95%) rename src/{main/java/baritone => api/java/baritone/api}/pathing/movement/MovementStatus.java (95%) rename src/{main/java/baritone => api/java/baritone/api}/pathing/path/CutoffPath.java (93%) rename src/{main/java/baritone => api/java/baritone/api}/pathing/path/CutoffResult.java (97%) rename src/{main/java/baritone => api/java/baritone/api}/pathing/path/IPath.java (85%) create mode 100644 src/api/java/baritone/api/pathing/path/IPathExecutor.java rename src/{main/java/baritone/utils/pathing => api/java/baritone/api/utils}/BetterBlockPos.java (86%) diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index e21d999d..5960688a 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -17,7 +17,10 @@ package baritone.api.behavior; +import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.path.IPath; +import baritone.api.pathing.path.IPathExecutor; import java.util.Optional; @@ -65,4 +68,30 @@ public interface IPathingBehavior extends IBehavior { * Cancels the pathing behavior or the current path calculation. */ void cancel(); + + /** + * Returns the current path, from the current path executor, if there is one. + * + * @return The current path + */ + default Optional getPath() { + return Optional.ofNullable(getCurrent()).map(IPathExecutor::getPath); + } + + /** + * @return The current path finder being executed + */ + Optional getCurrentPathSearch(); + + /** + * @return The current path executor + */ + IPathExecutor getCurrent(); + + /** + * Returns the next path executor, created when planning ahead. + * + * @return The next path executor + */ + IPathExecutor getNext(); } diff --git a/src/main/java/baritone/pathing/calc/IPathFinder.java b/src/api/java/baritone/api/pathing/calc/IPathFinder.java similarity index 96% rename from src/main/java/baritone/pathing/calc/IPathFinder.java rename to src/api/java/baritone/api/pathing/calc/IPathFinder.java index e6f3be06..31fed89d 100644 --- a/src/main/java/baritone/pathing/calc/IPathFinder.java +++ b/src/api/java/baritone/api/pathing/calc/IPathFinder.java @@ -15,10 +15,10 @@ * along with Baritone. If not, see . */ -package baritone.pathing.calc; +package baritone.api.pathing.calc; import baritone.api.pathing.goals.Goal; -import baritone.pathing.path.IPath; +import baritone.api.pathing.path.IPath; import java.util.Optional; diff --git a/src/main/java/baritone/pathing/movement/IMovement.java b/src/api/java/baritone/api/pathing/movement/IMovement.java similarity index 95% rename from src/main/java/baritone/pathing/movement/IMovement.java rename to src/api/java/baritone/api/pathing/movement/IMovement.java index 83b65019..7b3eca5f 100644 --- a/src/main/java/baritone/pathing/movement/IMovement.java +++ b/src/api/java/baritone/api/pathing/movement/IMovement.java @@ -15,9 +15,9 @@ * along with Baritone. If not, see . */ -package baritone.pathing.movement; +package baritone.api.pathing.movement; -import baritone.utils.pathing.BetterBlockPos; +import baritone.api.utils.BetterBlockPos; import net.minecraft.util.math.BlockPos; import java.util.List; diff --git a/src/main/java/baritone/pathing/movement/MovementStatus.java b/src/api/java/baritone/api/pathing/movement/MovementStatus.java similarity index 95% rename from src/main/java/baritone/pathing/movement/MovementStatus.java rename to src/api/java/baritone/api/pathing/movement/MovementStatus.java index 4b4b92c3..6b5215ad 100644 --- a/src/main/java/baritone/pathing/movement/MovementStatus.java +++ b/src/api/java/baritone/api/pathing/movement/MovementStatus.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.pathing.movement; +package baritone.api.pathing.movement; /** * @author Brady diff --git a/src/main/java/baritone/pathing/path/CutoffPath.java b/src/api/java/baritone/api/pathing/path/CutoffPath.java similarity index 93% rename from src/main/java/baritone/pathing/path/CutoffPath.java rename to src/api/java/baritone/api/pathing/path/CutoffPath.java index 916b6c52..a702b7fd 100644 --- a/src/main/java/baritone/pathing/path/CutoffPath.java +++ b/src/api/java/baritone/api/pathing/path/CutoffPath.java @@ -15,11 +15,11 @@ * along with Baritone. If not, see . */ -package baritone.pathing.path; +package baritone.api.pathing.path; import baritone.api.pathing.goals.Goal; -import baritone.pathing.movement.IMovement; -import baritone.utils.pathing.BetterBlockPos; +import baritone.api.pathing.movement.IMovement; +import baritone.api.utils.BetterBlockPos; import java.util.Collections; import java.util.List; diff --git a/src/main/java/baritone/pathing/path/CutoffResult.java b/src/api/java/baritone/api/pathing/path/CutoffResult.java similarity index 97% rename from src/main/java/baritone/pathing/path/CutoffResult.java rename to src/api/java/baritone/api/pathing/path/CutoffResult.java index d1c03c1e..eeaa4ad1 100644 --- a/src/main/java/baritone/pathing/path/CutoffResult.java +++ b/src/api/java/baritone/api/pathing/path/CutoffResult.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.pathing.path; +package baritone.api.pathing.path; /** * @author Brady diff --git a/src/main/java/baritone/pathing/path/IPath.java b/src/api/java/baritone/api/pathing/path/IPath.java similarity index 85% rename from src/main/java/baritone/pathing/path/IPath.java rename to src/api/java/baritone/api/pathing/path/IPath.java index afc1bce3..2d4b08e3 100644 --- a/src/main/java/baritone/pathing/path/IPath.java +++ b/src/api/java/baritone/api/pathing/path/IPath.java @@ -15,15 +15,13 @@ * along with Baritone. If not, see . */ -package baritone.pathing.path; +package baritone.api.pathing.path; import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.Goal; -import baritone.pathing.movement.IMovement; -import baritone.utils.Utils; -import baritone.utils.pathing.BetterBlockPos; +import baritone.api.pathing.movement.IMovement; +import baritone.api.utils.BetterBlockPos; import net.minecraft.client.Minecraft; -import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; @@ -70,19 +68,6 @@ public interface IPath { */ Goal getGoal(); - default Tuple closestPathPos() { - double best = -1; - BlockPos bestPos = null; - for (BlockPos pos : positions()) { - double dist = Utils.playerDistanceToCenter(pos); - if (dist < best || best == -1) { - best = dist; - bestPos = pos; - } - } - return new Tuple<>(best, bestPos); - } - /** * Where does this path start */ diff --git a/src/api/java/baritone/api/pathing/path/IPathExecutor.java b/src/api/java/baritone/api/pathing/path/IPathExecutor.java new file mode 100644 index 00000000..bf701224 --- /dev/null +++ b/src/api/java/baritone/api/pathing/path/IPathExecutor.java @@ -0,0 +1,27 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.pathing.path; + +/** + * @author Brady + * @since 10/8/2018 + */ +public interface IPathExecutor { + + IPath getPath(); +} diff --git a/src/main/java/baritone/utils/pathing/BetterBlockPos.java b/src/api/java/baritone/api/utils/BetterBlockPos.java similarity index 86% rename from src/main/java/baritone/utils/pathing/BetterBlockPos.java rename to src/api/java/baritone/api/utils/BetterBlockPos.java index e81319db..a1a3cb32 100644 --- a/src/main/java/baritone/utils/pathing/BetterBlockPos.java +++ b/src/api/java/baritone/api/utils/BetterBlockPos.java @@ -15,9 +15,8 @@ * along with Baritone. If not, see . */ -package baritone.utils.pathing; +package baritone.api.utils; -import baritone.pathing.calc.AbstractNodeCostSearch; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; @@ -54,11 +53,30 @@ public final class BetterBlockPos extends BlockPos { @Override public int hashCode() { - return (int) AbstractNodeCostSearch.posHash(x, y, z); + return (int) longHash(x, y, z); } public static long longHash(BetterBlockPos pos) { - return AbstractNodeCostSearch.posHash(pos.x, pos.y, pos.z); + return longHash(pos.x, pos.y, pos.z); + } + + public static long longHash(int x, int y, int z) { + /* + * This is the hashcode implementation of Vec3i (the superclass of the class which I shall not name) + * + * 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 + */ + long hash = 3241; + hash = 3457689L * hash + x; + hash = 8734625L * hash + y; + hash = 2873465L * hash + z; + return hash; } @Override diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 2f0d1ab4..5d2ed420 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -40,7 +40,6 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; /** diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index 0f1a6b34..205c677d 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -22,13 +22,13 @@ import baritone.api.behavior.IMineBehavior; import baritone.api.event.events.PathEvent; import baritone.api.event.events.TickEvent; import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalBlock; +import baritone.api.pathing.goals.GoalComposite; +import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.cache.CachedChunk; import baritone.cache.ChunkPacker; import baritone.cache.WorldProvider; import baritone.cache.WorldScanner; -import baritone.api.pathing.goals.GoalBlock; -import baritone.api.pathing.goals.GoalComposite; -import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import net.minecraft.block.Block; diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 16c88b92..45163852 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -25,19 +25,19 @@ import baritone.api.event.events.RenderEvent; import baritone.api.event.events.TickEvent; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; +import baritone.api.pathing.path.CutoffResult; +import baritone.api.pathing.path.IPath; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AbstractNodeCostSearch; -import baritone.pathing.calc.IPathFinder; +import baritone.api.pathing.calc.IPathFinder; import baritone.pathing.movement.MovementHelper; -import baritone.pathing.path.CutoffResult; -import baritone.pathing.path.IPath; import baritone.pathing.path.PathExecutor; import baritone.utils.BlockBreakHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.PathRenderer; -import baritone.utils.pathing.BetterBlockPos; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; @@ -191,19 +191,19 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return goal; } + @Override public PathExecutor getCurrent() { return current; } + @Override public PathExecutor getNext() { return next; } - // TODO: Expose this method in the API? - // In order to do so, we'd need to move over IPath which has a whole lot of references to other - // things that may not need to be exposed necessarily, so we'll need to figure that out. - public Optional getPath() { - return Optional.ofNullable(current).map(PathExecutor::getPath); + @Override + public Optional getCurrentPathSearch() { + return Optional.ofNullable(AbstractNodeCostSearch.currentlyRunning()); } @Override diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index 583428e9..3afafda9 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -20,10 +20,11 @@ package baritone.pathing.calc; import baritone.Baritone; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.pathing.path.IPath; +import baritone.api.utils.BetterBlockPos; import baritone.pathing.calc.openset.BinaryHeapOpenSet; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Moves; -import baritone.pathing.path.IPath; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.pathing.MutableMoveResult; @@ -47,7 +48,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel @Override protected Optional calculate0(long timeout) { - startNode = getNodeAtPosition(startX, startY, startZ, posHash(startX, startY, startZ)); + startNode = getNodeAtPosition(startX, startY, startZ, BetterBlockPos.longHash(startX, startY, startZ)); startNode.cost = 0; startNode.combinedCost = startNode.estimatedCostToGoal; BinaryHeapOpenSet openSet = new BinaryHeapOpenSet(); @@ -122,7 +123,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel if (actionCost <= 0) { throw new IllegalStateException(moves + " calculated implausible cost " + actionCost); } - long hashCode = posHash(res.x, res.y, res.z); + long hashCode = BetterBlockPos.longHash(res.x, res.y, res.z); if (favoring && favored.contains(hashCode)) { // see issue #18 actionCost *= favorCoeff; diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 68a523fa..adac5e28 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -18,8 +18,9 @@ package baritone.pathing.calc; import baritone.Baritone; +import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; -import baritone.pathing.path.IPath; +import baritone.api.pathing.path.IPath; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import java.util.Optional; @@ -140,25 +141,6 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { return node; } - public static long posHash(int x, int y, int z) { - /* - * This is the hashcode implementation of Vec3i (the superclass of the class which I shall not name) - * - * 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 - */ - long hash = 3241; - hash = 3457689L * hash + x; - hash = 8734625L * hash + y; - hash = 2873465L * hash + z; - return hash; - } - public static void forceCancel() { currentlyRunning = null; } @@ -225,4 +207,8 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { public static Optional getCurrentlyRunning() { return Optional.ofNullable(currentlyRunning); } + + public static AbstractNodeCostSearch currentlyRunning() { + return currentlyRunning; + } } diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 6606cfba..ddd51dc2 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -18,11 +18,11 @@ package baritone.pathing.calc; import baritone.api.pathing.goals.Goal; -import baritone.pathing.movement.IMovement; +import baritone.api.pathing.movement.IMovement; +import baritone.api.pathing.path.IPath; +import baritone.api.utils.BetterBlockPos; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; -import baritone.pathing.path.IPath; -import baritone.utils.pathing.BetterBlockPos; import net.minecraft.util.math.BlockPos; import java.util.ArrayList; diff --git a/src/main/java/baritone/pathing/calc/PathNode.java b/src/main/java/baritone/pathing/calc/PathNode.java index 8e42d564..8f316132 100644 --- a/src/main/java/baritone/pathing/calc/PathNode.java +++ b/src/main/java/baritone/pathing/calc/PathNode.java @@ -19,6 +19,7 @@ package baritone.pathing.calc; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.utils.BetterBlockPos; /** * A node in the path, containing the cost and steps to get to it. @@ -85,7 +86,7 @@ public final class PathNode { */ @Override public int hashCode() { - return (int) AbstractNodeCostSearch.posHash(x, y, z); + return (int) BetterBlockPos.longHash(x, y, z); } @Override diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index bb699d0e..cffa28ee 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -18,11 +18,13 @@ package baritone.pathing.movement; import baritone.Baritone; +import baritone.api.pathing.movement.IMovement; +import baritone.api.pathing.movement.MovementStatus; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; import baritone.behavior.LookBehavior; import baritone.behavior.LookBehaviorUtils; import baritone.utils.*; -import baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.BlockLiquid; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 28b14e9e..5b5be77e 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -19,11 +19,11 @@ package baritone.pathing.movement; import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; import baritone.behavior.LookBehaviorUtils; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.*; -import baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.*; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.IBlockState; diff --git a/src/main/java/baritone/pathing/movement/MovementState.java b/src/main/java/baritone/pathing/movement/MovementState.java index acf223d4..db99ce5d 100644 --- a/src/main/java/baritone/pathing/movement/MovementState.java +++ b/src/main/java/baritone/pathing/movement/MovementState.java @@ -17,6 +17,7 @@ package baritone.pathing.movement; +import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.Rotation; import baritone.utils.InputOverrideHandler.Input; import net.minecraft.util.math.Vec3d; diff --git a/src/main/java/baritone/pathing/movement/Moves.java b/src/main/java/baritone/pathing/movement/Moves.java index c5b1069d..3d53ff5b 100644 --- a/src/main/java/baritone/pathing/movement/Moves.java +++ b/src/main/java/baritone/pathing/movement/Moves.java @@ -17,8 +17,8 @@ package baritone.pathing.movement; +import baritone.api.utils.BetterBlockPos; import baritone.pathing.movement.movements.*; -import baritone.utils.pathing.BetterBlockPos; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.util.EnumFacing; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 9ad42d99..6989179b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -18,12 +18,16 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.pathing.movement.MovementStatus; +import baritone.api.utils.BetterBlockPos; import baritone.behavior.LookBehaviorUtils; -import baritone.pathing.movement.*; +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 baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 227a6b89..ba3deb7d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -18,14 +18,14 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.pathing.movement.MovementStatus; +import baritone.api.utils.BetterBlockPos; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; -import baritone.pathing.movement.MovementStatus; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; -import baritone.utils.pathing.BetterBlockPos; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; import net.minecraft.block.BlockFalling; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index b8ef01c3..8ff681c6 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -17,10 +17,14 @@ package baritone.pathing.movement.movements; -import baritone.pathing.movement.*; +import baritone.api.pathing.movement.MovementStatus; +import baritone.api.utils.BetterBlockPos; +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.pathing.BetterBlockPos; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java index d808d993..0ac4f2b0 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java @@ -17,9 +17,13 @@ package baritone.pathing.movement.movements; -import baritone.pathing.movement.*; +import baritone.api.pathing.movement.MovementStatus; +import baritone.api.utils.BetterBlockPos; +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.pathing.BetterBlockPos; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 3ce2848f..e09eb579 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -18,18 +18,18 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.pathing.movement.MovementStatus; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; -import baritone.pathing.movement.MovementStatus; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; import baritone.utils.RayTraceUtils; import baritone.utils.Utils; -import baritone.utils.pathing.BetterBlockPos; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 7ecb4c04..94b7dfea 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -18,11 +18,15 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.pathing.movement.MovementStatus; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; import baritone.behavior.LookBehaviorUtils; -import baritone.pathing.movement.*; +import baritone.pathing.movement.CalculationContext; +import baritone.pathing.movement.Movement; +import baritone.pathing.movement.MovementHelper; +import baritone.pathing.movement.MovementState; import baritone.utils.*; -import baritone.utils.pathing.BetterBlockPos; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 7680fb43..60803a3c 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -17,12 +17,16 @@ package baritone.pathing.movement.movements; +import baritone.api.pathing.movement.MovementStatus; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; -import baritone.pathing.movement.*; +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 baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 00000ac4..f029619a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -18,13 +18,17 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.pathing.movement.MovementStatus; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; import baritone.behavior.LookBehaviorUtils; -import baritone.pathing.movement.*; +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 baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index a60b4a29..5f8c3f89 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -20,18 +20,23 @@ package baritone.pathing.path; import baritone.Baritone; import baritone.api.event.events.TickEvent; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.pathing.movement.IMovement; +import baritone.api.pathing.movement.MovementStatus; +import baritone.api.pathing.path.IPath; +import baritone.api.pathing.path.IPathExecutor; +import baritone.api.utils.BetterBlockPos; import baritone.pathing.calc.AbstractNodeCostSearch; -import baritone.pathing.movement.*; +import baritone.pathing.movement.CalculationContext; +import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.movements.*; import baritone.utils.*; -import baritone.utils.pathing.BetterBlockPos; import net.minecraft.init.Blocks; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; import java.util.*; -import static baritone.pathing.movement.MovementStatus.*; +import static baritone.api.pathing.movement.MovementStatus.*; /** * Behavior to execute a precomputed path. Does not (yet) deal with path segmentation or stitching @@ -39,7 +44,7 @@ import static baritone.pathing.movement.MovementStatus.*; * * @author leijurv */ -public class PathExecutor implements Helper { +public class PathExecutor implements IPathExecutor, Helper { private static final double MAX_MAX_DIST_FROM_PATH = 3; private static final double MAX_DIST_FROM_PATH = 2; @@ -125,7 +130,7 @@ public class PathExecutor implements Helper { } } } - Tuple status = path.closestPathPos(); + Tuple status = closestPathPos(path); if (possiblyOffPath(status, MAX_DIST_FROM_PATH)) { ticksAway++; System.out.println("FAR AWAY FROM PATH FOR " + ticksAway + " TICKS. Current distance: " + status.getFirst() + ". Threshold: " + MAX_DIST_FROM_PATH); @@ -269,6 +274,19 @@ public class PathExecutor implements Helper { return false; // movement is in progress } + private Tuple closestPathPos(IPath path) { + double best = -1; + BlockPos bestPos = null; + for (BlockPos pos : path.positions()) { + double dist = Utils.playerDistanceToCenter(pos); + if (dist < best || best == -1) { + best = dist; + bestPos = pos; + } + } + return new Tuple<>(best, bestPos); + } + private boolean shouldPause() { Optional current = AbstractNodeCostSearch.getCurrentlyRunning(); if (!current.isPresent()) { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index fd733d7f..c851a087 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -31,7 +31,6 @@ import baritone.cache.ChunkPacker; import baritone.cache.Waypoint; import baritone.cache.WorldProvider; import baritone.pathing.calc.AbstractNodeCostSearch; -import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.Moves; diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index a0ffdb96..f026ec38 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -18,8 +18,8 @@ package baritone.utils; import baritone.Baritone; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; -import baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.BlockSlab; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 6891a299..de2630c9 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -23,12 +23,12 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.pathing.goals.GoalXZ; +import baritone.api.pathing.path.IPath; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.behavior.PathingBehavior; import baritone.pathing.calc.AbstractNodeCostSearch; -import baritone.pathing.path.IPath; import baritone.pathing.path.PathExecutor; -import baritone.utils.pathing.BetterBlockPos; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; diff --git a/src/test/java/baritone/utils/pathing/BetterBlockPosTest.java b/src/test/java/baritone/utils/pathing/BetterBlockPosTest.java index 13b76c73..a21f0cd4 100644 --- a/src/test/java/baritone/utils/pathing/BetterBlockPosTest.java +++ b/src/test/java/baritone/utils/pathing/BetterBlockPosTest.java @@ -17,6 +17,7 @@ package baritone.utils.pathing; +import baritone.api.utils.BetterBlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import org.junit.Test; From 7d0aa4d7a5cb57fa2bb3c431f47cb7e9122c2681 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 20:39:33 -0500 Subject: [PATCH 091/305] Add override annotation to getPath in PathExecutor --- src/main/java/baritone/pathing/path/PathExecutor.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 5f8c3f89..cbf078fd 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -451,6 +451,7 @@ public class PathExecutor implements IPathExecutor, Helper { return pathPosition; } + @Override public IPath getPath() { return path; } From 8278576227f2c3b8043e358c4f926791aea68fa3 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 21:02:55 -0500 Subject: [PATCH 092/305] Rename getCurrentPathSearch to getPathFinder --- src/api/java/baritone/api/behavior/IPathingBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index 5960688a..f92a00ca 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -81,7 +81,7 @@ public interface IPathingBehavior extends IBehavior { /** * @return The current path finder being executed */ - Optional getCurrentPathSearch(); + Optional getPathFinder(); /** * @return The current path executor From 6a4a8ab2d9184ba04fef38d85043e7aa4f88b677 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 21:09:54 -0500 Subject: [PATCH 093/305] I'm an IDIOT --- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 45163852..c701e7a5 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -202,7 +202,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } @Override - public Optional getCurrentPathSearch() { + public Optional getPathFinder() { return Optional.ofNullable(AbstractNodeCostSearch.currentlyRunning()); } From 8e1d827819ed531f00b1f8d82ac5f28abc7ac499 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 8 Oct 2018 20:57:06 -0700 Subject: [PATCH 094/305] v0.0.7 --- build.gradle | 2 +- scripts/proguard.pro | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index d3f69d43..d9b78641 100755 --- a/build.gradle +++ b/build.gradle @@ -20,7 +20,7 @@ import java.util.jar.JarOutputStream */ group 'baritone' -version '0.0.6' +version '0.0.7' buildscript { repositories { diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 6efbe0fa..410fcc33 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -1,4 +1,4 @@ --injars baritone-0.0.6.jar +-injars baritone-0.0.7.jar -outjars Obfuscated From 875f01c358279e334d38c2e304f31a7c4b6aee44 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 23:29:16 -0500 Subject: [PATCH 095/305] More comprehensive IPath javadocs --- .../baritone/api/pathing/path/CutoffPath.java | 2 +- .../java/baritone/api/pathing/path/IPath.java | 54 +++++++++++++++---- .../pathing/calc/AbstractNodeCostSearch.java | 2 +- src/main/java/baritone/pathing/calc/Path.java | 2 +- 4 files changed, 47 insertions(+), 13 deletions(-) diff --git a/src/api/java/baritone/api/pathing/path/CutoffPath.java b/src/api/java/baritone/api/pathing/path/CutoffPath.java index a702b7fd..1fcbdadc 100644 --- a/src/api/java/baritone/api/pathing/path/CutoffPath.java +++ b/src/api/java/baritone/api/pathing/path/CutoffPath.java @@ -34,7 +34,7 @@ public class CutoffPath implements IPath { private final Goal goal; - public CutoffPath(IPath prev, int lastPositionToInclude) { + CutoffPath(IPath prev, int lastPositionToInclude) { path = prev.positions().subList(0, lastPositionToInclude + 1); movements = prev.movements().subList(0, lastPositionToInclude + 1); numNodes = prev.getNumNodesConsidered(); diff --git a/src/api/java/baritone/api/pathing/path/IPath.java b/src/api/java/baritone/api/pathing/path/IPath.java index 2d4b08e3..275f0f97 100644 --- a/src/api/java/baritone/api/pathing/path/IPath.java +++ b/src/api/java/baritone/api/pathing/path/IPath.java @@ -18,6 +18,7 @@ package baritone.api.pathing.path; import baritone.api.BaritoneAPI; +import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; import baritone.api.utils.BetterBlockPos; @@ -28,7 +29,7 @@ import net.minecraft.world.chunk.EmptyChunk; import java.util.List; /** - * @author leijurv + * @author leijurv, Brady */ public interface IPath { @@ -37,12 +38,16 @@ public interface IPath { * movements.get(i).getSrc() should equal positions.get(i) * movements.get(i).getDest() should equal positions.get(i+1) * movements.size() should equal positions.size()-1 + * + * @return All of the movements to carry out */ List movements(); /** * All positions along the way. * Should begin with the same as getSrc and end with the same as getDest + * + * @return All of the positions along this path */ List positions(); @@ -50,10 +55,10 @@ public interface IPath { * This path is actually going to be executed in the world. Do whatever additional processing is required. * (as opposed to Path objects that are just constructed every frame for rendering) */ - default void postprocess() {} + default void postProcess() {} /** - * Number of positions in this path + * Returns the number of positions in this path. Equivalent to {@code positions().size()}. * * @return Number of positions in this path */ @@ -62,27 +67,45 @@ public interface IPath { } /** - * What goal was this path calculated towards? - * - * @return + * @return The goal that this path was calculated towards */ Goal getGoal(); /** - * Where does this path start + * Returns the number of nodes that were considered during calculation before + * this path was found. + * + * @return The number of nodes that were considered before finding this path + */ + int getNumNodesConsidered(); + + /** + * Returns the start position of this path. This is the first element in the + * {@link List} that is returned by {@link IPath#positions()}. + * + * @return The start position of this path */ default BetterBlockPos getSrc() { return positions().get(0); } /** - * Where does this path end + * Returns the end position of this path. This is the last element in the + * {@link List} that is returned by {@link IPath#positions()}. + * + * @return The end position of this path. */ default BetterBlockPos getDest() { List pos = positions(); return pos.get(pos.size() - 1); } + /** + * Returns the estimated number of ticks to complete the path from the given node index. + * + * @param pathPosition The index of the node we're calculating from + * @return The estimated number of ticks remaining frm the given position + */ default double ticksRemainingFrom(int pathPosition) { double sum = 0; //this is fast because we aren't requesting recalculation, it's just cached @@ -92,8 +115,11 @@ public interface IPath { return sum; } - int getNumNodesConsidered(); - + /** + * Cuts off this path at the loaded chunk border, and returns the {@link CutoffResult}. + * + * @return The result of this cut-off operation + */ default CutoffResult cutoffAtLoadedChunks() { for (int i = 0; i < positions().size(); i++) { BlockPos pos = positions().get(i); @@ -104,6 +130,14 @@ public interface IPath { return CutoffResult.preservePath(this); } + /** + * Cuts off this path using the min length and cutoff factor settings, and returns the {@link CutoffResult}. + * + * @see Settings#pathCutoffMinimumLength + * @see Settings#pathCutoffFactor + * + * @return The result of this cut-off operation + */ default CutoffResult staticCutoff(Goal destination) { if (length() < BaritoneAPI.getSettings().pathCutoffMinimumLength.get()) { return CutoffResult.preservePath(this); diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index adac5e28..3c033a93 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -89,7 +89,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { this.cancelRequested = false; try { Optional path = calculate0(timeout); - path.ifPresent(IPath::postprocess); + path.ifPresent(IPath::postProcess); isFinished = true; return path; } finally { diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index ddd51dc2..4983de54 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -150,7 +150,7 @@ class Path implements IPath { } @Override - public void postprocess() { + public void postProcess() { if (verified) { throw new IllegalStateException(); } From 2e69bbe371a03cfbcf3c7c41b63d60743280bc64 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 23:34:12 -0500 Subject: [PATCH 096/305] Minimal CutoffResult Javadocs --- .../api/pathing/path/CutoffResult.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/api/java/baritone/api/pathing/path/CutoffResult.java b/src/api/java/baritone/api/pathing/path/CutoffResult.java index eeaa4ad1..d4175e85 100644 --- a/src/api/java/baritone/api/pathing/path/CutoffResult.java +++ b/src/api/java/baritone/api/pathing/path/CutoffResult.java @@ -18,13 +18,21 @@ package baritone.api.pathing.path; /** + * The result of a path cut-off operation. + * * @author Brady * @since 10/8/2018 */ public final class CutoffResult { + /** + * The resulting path + */ private final IPath path; + /** + * The amount of movements that were removed + */ private final int removed; private CutoffResult(IPath path, int removed) { @@ -32,22 +40,44 @@ public final class CutoffResult { this.removed = removed; } + /** + * @return Whether or not the path was cut + */ public final boolean wasCut() { return this.removed > 0; } + /** + * @return The amount of movements that were removed + */ public final int getRemoved() { return this.removed; } + /** + * @return The resulting path + */ public final IPath getPath() { return this.path; } + /** + * Creates a new result from a successful cut-off operation. + * + * @param path The input path + * @param index The index to cut the path at + * @return The result of the operation + */ public static CutoffResult cutoffPath(IPath path, int index) { return new CutoffResult(new CutoffPath(path, index), path.positions().size() - index - 1); } + /** + * Creates a new result in which no cut-off occurred. + * + * @param path The input path + * @return The result of the operation + */ public static CutoffResult preservePath(IPath path) { return new CutoffResult(path, 0); } From a497a944a64eed5306c080da78ce8885ef02a291 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 8 Oct 2018 21:49:36 -0700 Subject: [PATCH 097/305] bottom of the class --- src/main/java/baritone/utils/BaritoneAutoTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index faad6153..1c11c937 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -35,8 +35,6 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { public static final BaritoneAutoTest INSTANCE = new BaritoneAutoTest(); - private BaritoneAutoTest() {} - public static final boolean ENABLE_AUTO_TEST = "true".equals(System.getenv("BARITONE_AUTO_TEST")); private static final long TEST_SEED = -928872506371745L; private static final BlockPos STARTING_POSITION = new BlockPos(0, 65, 0); @@ -123,4 +121,6 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { } } } + + private BaritoneAutoTest() {} } From f17ce87e4596f8882282528ea48790b3b9eab177 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 8 Oct 2018 21:51:19 -0700 Subject: [PATCH 098/305] publicize --- src/main/java/baritone/cache/WorldData.java | 2 +- src/main/java/baritone/pathing/calc/PathNode.java | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/cache/WorldData.java b/src/main/java/baritone/cache/WorldData.java index 19461d22..b489d933 100644 --- a/src/main/java/baritone/cache/WorldData.java +++ b/src/main/java/baritone/cache/WorldData.java @@ -42,7 +42,7 @@ public class WorldData implements IWorldData { this.waypoints = new Waypoints(directory.resolve("waypoints")); } - void onClose() { + public void onClose() { Baritone.INSTANCE.getExecutor().execute(() -> { System.out.println("Started saving the world in a new thread"); cache.save(); diff --git a/src/main/java/baritone/pathing/calc/PathNode.java b/src/main/java/baritone/pathing/calc/PathNode.java index 8e42d564..207b3d65 100644 --- a/src/main/java/baritone/pathing/calc/PathNode.java +++ b/src/main/java/baritone/pathing/calc/PathNode.java @@ -30,20 +30,20 @@ public final class PathNode { /** * The position of this node */ - final int x; - final int y; - final int z; + public final int x; + public final int y; + public final int z; /** * Cached, should always be equal to goal.heuristic(pos) */ - final double estimatedCostToGoal; + public final double estimatedCostToGoal; /** * Total cost of getting from start to here * Mutable and changed by PathFinder */ - double cost; + public double cost; /** * Should always be equal to estimatedCosttoGoal + cost @@ -55,13 +55,13 @@ public final class PathNode { * In the graph search, what previous node contributed to the cost * Mutable and changed by PathFinder */ - PathNode previous; + public PathNode previous; /** * Is this a member of the open set in A*? (only used during pathfinding) * Instead of doing a costly member check in the open set, cache membership in each node individually too. */ - boolean isOpen; + public boolean isOpen; /** * Where is this node in the array flattenization of the binary heap? Needed for decrease-key operations. From 0fb5f3233f4f1c2996550d40a0aa326294a0dbde Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 8 Oct 2018 23:52:36 -0500 Subject: [PATCH 099/305] MovementStatus javadocs --- .../api/pathing/movement/MovementStatus.java | 49 ++++++++++++++++++- .../baritone/pathing/movement/Movement.java | 9 +--- 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/pathing/movement/MovementStatus.java b/src/api/java/baritone/api/pathing/movement/MovementStatus.java index 6b5215ad..0190f8e1 100644 --- a/src/api/java/baritone/api/pathing/movement/MovementStatus.java +++ b/src/api/java/baritone/api/pathing/movement/MovementStatus.java @@ -23,5 +23,52 @@ package baritone.api.pathing.movement; */ public enum MovementStatus { - PREPPING, WAITING, RUNNING, SUCCESS, UNREACHABLE, FAILED, CANCELED + /** + * We are preparing the movement to be executed. This is when any blocks obstructing the destination are broken. + */ + PREPPING(false), + + /** + * We are waiting for the movement to begin, after {@link MovementStatus#PREPPING}. + */ + WAITING(false), + + /** + * The movement is currently in progress, after {@link MovementStatus#WAITING} + */ + RUNNING(false), + + /** + * The movement has been completed and we are at our destination + */ + SUCCESS(true), + + /** + * There was a change in state between calculation and actual + * movement execution, and the movement has now become impossible. + */ + UNREACHABLE(true), + + /** + * Unused + */ + FAILED(true), + + /** + * "Unused" + */ + CANCELED(true); + + /** + * Whether or not this status indicates a complete movement. + */ + private final boolean complete; + + MovementStatus(boolean complete) { + this.complete = complete; + } + + public final boolean isComplete() { + return this.complete; + } } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index cffa28ee..92a1f4db 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -152,7 +152,8 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { currentState = latestState; - if (isFinished()) { + // If the current status indicates a completed movement + if (currentState.getStatus().isComplete()) { onFinish(latestState); } @@ -201,12 +202,6 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { return true; } - public boolean isFinished() { - return (currentState.getStatus() != MovementStatus.RUNNING - && currentState.getStatus() != MovementStatus.PREPPING - && currentState.getStatus() != MovementStatus.WAITING); - } - @Override public BetterBlockPos getSrc() { return src; From 9df5f942ded79dbf74e5034d33c329e6e21d8d0a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 8 Oct 2018 22:01:57 -0700 Subject: [PATCH 100/305] add shebang --- scripts/build.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/build.sh b/scripts/build.sh index e2f9b01f..7c0f83cb 100644 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -1,3 +1,4 @@ +#!/bin/sh set -e # this makes the whole script fail immediately if any one of these commands fails ./gradlew build export VERSION=$(cat build.gradle | grep "version '" | cut -d "'" -f 2-2) From 771e892b31f3f3463a976b0e7e19d9ba0e9821fa Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 9 Oct 2018 00:10:50 -0500 Subject: [PATCH 101/305] Get Cutoff implementation out of API we DON'T need you --- .../api/behavior/IPathingBehavior.java | 2 +- .../api/pathing/{path => calc}/IPath.java | 34 ++------ .../api/pathing/calc/IPathFinder.java | 1 - .../api/pathing/path/CutoffResult.java | 84 ------------------- .../api/pathing/path/IPathExecutor.java | 2 + .../baritone/behavior/PathingBehavior.java | 20 ++--- .../pathing/calc/AStarPathFinder.java | 2 +- .../pathing/calc/AbstractNodeCostSearch.java | 2 +- .../baritone/pathing/calc}/CutoffPath.java | 3 +- src/main/java/baritone/pathing/calc/Path.java | 29 ++++++- .../baritone/pathing/path/PathExecutor.java | 2 +- .../java/baritone/utils/PathRenderer.java | 2 +- 12 files changed, 56 insertions(+), 127 deletions(-) rename src/api/java/baritone/api/pathing/{path => calc}/IPath.java (77%) delete mode 100644 src/api/java/baritone/api/pathing/path/CutoffResult.java rename src/{api/java/baritone/api/pathing/path => main/java/baritone/pathing/calc}/CutoffPath.java (96%) diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index f92a00ca..cfc93d2d 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -19,7 +19,7 @@ package baritone.api.behavior; import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.path.IPath; +import baritone.api.pathing.calc.IPath; import baritone.api.pathing.path.IPathExecutor; import java.util.Optional; diff --git a/src/api/java/baritone/api/pathing/path/IPath.java b/src/api/java/baritone/api/pathing/calc/IPath.java similarity index 77% rename from src/api/java/baritone/api/pathing/path/IPath.java rename to src/api/java/baritone/api/pathing/calc/IPath.java index 275f0f97..c9d58818 100644 --- a/src/api/java/baritone/api/pathing/path/IPath.java +++ b/src/api/java/baritone/api/pathing/calc/IPath.java @@ -15,16 +15,12 @@ * along with Baritone. If not, see . */ -package baritone.api.pathing.path; +package baritone.api.pathing.calc; -import baritone.api.BaritoneAPI; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; import baritone.api.utils.BetterBlockPos; -import net.minecraft.client.Minecraft; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.chunk.EmptyChunk; import java.util.List; @@ -116,37 +112,25 @@ public interface IPath { } /** - * Cuts off this path at the loaded chunk border, and returns the {@link CutoffResult}. + * Cuts off this path at the loaded chunk border, and returns the resulting path. Default + * implementation just returns this path, without the intended functionality. * * @return The result of this cut-off operation */ - default CutoffResult cutoffAtLoadedChunks() { - for (int i = 0; i < positions().size(); i++) { - BlockPos pos = positions().get(i); - if (Minecraft.getMinecraft().world.getChunk(pos) instanceof EmptyChunk) { - return CutoffResult.cutoffPath(this, i); - } - } - return CutoffResult.preservePath(this); + default IPath cutoffAtLoadedChunks() { + return this; } /** - * Cuts off this path using the min length and cutoff factor settings, and returns the {@link CutoffResult}. + * Cuts off this path using the min length and cutoff factor settings, and returns the resulting path. + * Default implementation just returns this path, without the intended functionality. * * @see Settings#pathCutoffMinimumLength * @see Settings#pathCutoffFactor * * @return The result of this cut-off operation */ - default CutoffResult staticCutoff(Goal destination) { - if (length() < BaritoneAPI.getSettings().pathCutoffMinimumLength.get()) { - return CutoffResult.preservePath(this); - } - if (destination == null || destination.isInGoal(getDest())) { - return CutoffResult.preservePath(this); - } - double factor = BaritoneAPI.getSettings().pathCutoffFactor.get(); - int newLength = (int) (length() * factor); - return CutoffResult.cutoffPath(this, newLength); + default IPath staticCutoff(Goal destination) { + return this; } } diff --git a/src/api/java/baritone/api/pathing/calc/IPathFinder.java b/src/api/java/baritone/api/pathing/calc/IPathFinder.java index 31fed89d..446f7e05 100644 --- a/src/api/java/baritone/api/pathing/calc/IPathFinder.java +++ b/src/api/java/baritone/api/pathing/calc/IPathFinder.java @@ -18,7 +18,6 @@ package baritone.api.pathing.calc; import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.path.IPath; import java.util.Optional; diff --git a/src/api/java/baritone/api/pathing/path/CutoffResult.java b/src/api/java/baritone/api/pathing/path/CutoffResult.java deleted file mode 100644 index d4175e85..00000000 --- a/src/api/java/baritone/api/pathing/path/CutoffResult.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.api.pathing.path; - -/** - * The result of a path cut-off operation. - * - * @author Brady - * @since 10/8/2018 - */ -public final class CutoffResult { - - /** - * The resulting path - */ - private final IPath path; - - /** - * The amount of movements that were removed - */ - private final int removed; - - private CutoffResult(IPath path, int removed) { - this.path = path; - this.removed = removed; - } - - /** - * @return Whether or not the path was cut - */ - public final boolean wasCut() { - return this.removed > 0; - } - - /** - * @return The amount of movements that were removed - */ - public final int getRemoved() { - return this.removed; - } - - /** - * @return The resulting path - */ - public final IPath getPath() { - return this.path; - } - - /** - * Creates a new result from a successful cut-off operation. - * - * @param path The input path - * @param index The index to cut the path at - * @return The result of the operation - */ - public static CutoffResult cutoffPath(IPath path, int index) { - return new CutoffResult(new CutoffPath(path, index), path.positions().size() - index - 1); - } - - /** - * Creates a new result in which no cut-off occurred. - * - * @param path The input path - * @return The result of the operation - */ - public static CutoffResult preservePath(IPath path) { - return new CutoffResult(path, 0); - } -} diff --git a/src/api/java/baritone/api/pathing/path/IPathExecutor.java b/src/api/java/baritone/api/pathing/path/IPathExecutor.java index bf701224..f72060dc 100644 --- a/src/api/java/baritone/api/pathing/path/IPathExecutor.java +++ b/src/api/java/baritone/api/pathing/path/IPathExecutor.java @@ -17,6 +17,8 @@ package baritone.api.pathing.path; +import baritone.api.pathing.calc.IPath; + /** * @author Brady * @since 10/8/2018 diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index c701e7a5..e91769b8 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -25,8 +25,8 @@ import baritone.api.event.events.RenderEvent; import baritone.api.event.events.TickEvent; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; -import baritone.api.pathing.path.CutoffResult; -import baritone.api.pathing.path.IPath; +import baritone.pathing.calc.CutoffPath; +import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.pathing.calc.AStarPathFinder; @@ -285,27 +285,27 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, Optional path = findPath(start, previous); if (Baritone.settings().cutoffAtLoadBoundary.get()) { path = path.map(p -> { - CutoffResult result = p.cutoffAtLoadedChunks(); + IPath result = p.cutoffAtLoadedChunks(); - if (result.wasCut()) { + if (result instanceof CutoffPath) { logDebug("Cutting off path at edge of loaded chunks"); - logDebug("Length decreased by " + result.getRemoved()); + logDebug("Length decreased by " + (p.length() - result.length())); } else { logDebug("Path ends within loaded chunks"); } - return result.getPath(); + return result; }); } Optional executor = path.map(p -> { - CutoffResult result = p.staticCutoff(goal); + IPath result = p.staticCutoff(goal); - if (result.wasCut()) { - logDebug("Static cutoff " + p.length() + " to " + result.getPath().length()); + if (result instanceof CutoffPath) { + logDebug("Static cutoff " + p.length() + " to " + result.length()); } - return result.getPath(); + return result; }).map(PathExecutor::new); synchronized (pathPlanLock) { diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index 3afafda9..f4adc7e2 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -20,7 +20,7 @@ package baritone.pathing.calc; import baritone.Baritone; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.ActionCosts; -import baritone.api.pathing.path.IPath; +import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import baritone.pathing.calc.openset.BinaryHeapOpenSet; import baritone.pathing.movement.CalculationContext; diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 3c033a93..424c512e 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -20,7 +20,7 @@ package baritone.pathing.calc; import baritone.Baritone; import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.path.IPath; +import baritone.api.pathing.calc.IPath; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import java.util.Optional; diff --git a/src/api/java/baritone/api/pathing/path/CutoffPath.java b/src/main/java/baritone/pathing/calc/CutoffPath.java similarity index 96% rename from src/api/java/baritone/api/pathing/path/CutoffPath.java rename to src/main/java/baritone/pathing/calc/CutoffPath.java index 1fcbdadc..bcf66b79 100644 --- a/src/api/java/baritone/api/pathing/path/CutoffPath.java +++ b/src/main/java/baritone/pathing/calc/CutoffPath.java @@ -15,10 +15,11 @@ * along with Baritone. If not, see . */ -package baritone.api.pathing.path; +package baritone.pathing.calc; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; +import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import java.util.Collections; diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 4983de54..f7bf9638 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -17,13 +17,16 @@ package baritone.pathing.calc; +import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; -import baritone.api.pathing.path.IPath; +import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; +import net.minecraft.client.Minecraft; import net.minecraft.util.math.BlockPos; +import net.minecraft.world.chunk.EmptyChunk; import java.util.ArrayList; import java.util.Collections; @@ -188,4 +191,28 @@ class Path implements IPath { public BetterBlockPos getDest() { return end; } + + @Override + public IPath cutoffAtLoadedChunks() { + for (int i = 0; i < positions().size(); i++) { + BlockPos pos = positions().get(i); + if (Minecraft.getMinecraft().world.getChunk(pos) instanceof EmptyChunk) { + return new CutoffPath(this, i); + } + } + return this; + } + + @Override + public IPath staticCutoff(Goal destination) { + if (length() < BaritoneAPI.getSettings().pathCutoffMinimumLength.get()) { + return this; + } + if (destination == null || destination.isInGoal(getDest())) { + return this; + } + double factor = BaritoneAPI.getSettings().pathCutoffFactor.get(); + int newLength = (int) (length() * factor); + return new CutoffPath(this, newLength); + } } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index cbf078fd..6fba09a3 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -22,7 +22,7 @@ import baritone.api.event.events.TickEvent; import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; -import baritone.api.pathing.path.IPath; +import baritone.api.pathing.calc.IPath; import baritone.api.pathing.path.IPathExecutor; import baritone.api.utils.BetterBlockPos; import baritone.pathing.calc.AbstractNodeCostSearch; diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index de2630c9..841876d8 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -23,7 +23,7 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.pathing.goals.GoalXZ; -import baritone.api.pathing.path.IPath; +import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.behavior.PathingBehavior; From 738ce25ff04e04c3ef95849eec8c455f4cf60e01 Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 9 Oct 2018 11:15:27 -0700 Subject: [PATCH 102/305] tighten fall column --- .../java/baritone/pathing/movement/movements/MovementFall.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index e09eb579..a761a242 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -106,7 +106,7 @@ public class MovementFall extends Movement { } } Vec3d destCenter = Utils.getBlockPosCenter(dest); // we are moving to the 0.5 center not the edge (like if we were falling on a ladder) - if (Math.abs(player().posX - destCenter.x) > 0.2 || Math.abs(player().posZ - destCenter.z) > 0.2) { + if (Math.abs(player().posX - destCenter.x) > 0.15 || Math.abs(player().posZ - destCenter.z) > 0.15) { state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); } return state; From 9e15960581affd8a19d5cc1c61ffa261c04f600e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 9 Oct 2018 16:13:46 -0700 Subject: [PATCH 103/305] fix pause stuttering, fixes #216 --- src/main/java/baritone/pathing/path/PathExecutor.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 6fba09a3..6f531857 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -19,10 +19,10 @@ package baritone.pathing.path; import baritone.Baritone; import baritone.api.event.events.TickEvent; +import baritone.api.pathing.calc.IPath; import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; -import baritone.api.pathing.calc.IPath; import baritone.api.pathing.path.IPathExecutor; import baritone.api.utils.BetterBlockPos; import baritone.pathing.calc.AbstractNodeCostSearch; @@ -244,6 +244,7 @@ public class PathExecutor implements IPathExecutor, Helper { } if (shouldPause()) { logDebug("Pausing since current best path is a backtrack"); + clearKeys(); return true; } MovementStatus movementStatus = movement.update(); @@ -342,7 +343,7 @@ public class PathExecutor implements IPathExecutor, Helper { // first and foremost, if allowSprint is off, or if we don't have enough hunger, don't try and sprint if (!new CalculationContext().canSprint()) { - Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT,false); + Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT, false); player().setSprinting(false); return; } @@ -356,7 +357,7 @@ public class PathExecutor implements IPathExecutor, Helper { } // we'll take it from here, no need for minecraft to see we're holding down control and sprint for us - Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT,false); + Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT, false); // however, descend doesn't request sprinting, beceause it doesn't know the context of what movement comes after it IMovement current = path.movements().get(pathPosition); From 22d20366578aab50d73ff7dea5a141fa99e2e676 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 9 Oct 2018 16:40:04 -0700 Subject: [PATCH 104/305] splice better, fixes #215 --- .../java/baritone/behavior/PathingBehavior.java | 9 +++++---- .../java/baritone/pathing/path/PathExecutor.java | 13 +++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index e91769b8..e2b21579 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -23,15 +23,15 @@ 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.api.pathing.calc.IPath; +import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; -import baritone.pathing.calc.CutoffPath; -import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AbstractNodeCostSearch; -import baritone.api.pathing.calc.IPathFinder; +import baritone.pathing.calc.CutoffPath; import baritone.pathing.movement.MovementHelper; import baritone.pathing.path.PathExecutor; import baritone.utils.BlockBreakHelper; @@ -123,12 +123,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, if (safe) { // a movement just ended if (next != null) { - if (next.getPath().positions().contains(playerFeet())) { + if (next.snipsnapifpossible()) { // jump directly onto the next path logDebug("Splicing into planned next path early..."); dispatchPathEvent(PathEvent.SPLICING_ONTO_NEXT_EARLY); current = next; next = null; + current.onTick(event); return; } } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 6f531857..5cc2c1dd 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -339,6 +339,19 @@ public class PathExecutor implements IPathExecutor, Helper { } } + /** + * Regardless of current path position, snap to the current player feet if possible + */ + public boolean snipsnapifpossible() { + int index = path.positions().indexOf(playerFeet()); + if (index == -1) { + return false; + } + pathPosition = index; + clearKeys(); + return true; + } + private void sprintIfRequested() { // first and foremost, if allowSprint is off, or if we don't have enough hunger, don't try and sprint From fc9d13a03c754933ac4890a8a723af0bebcd672e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 9 Oct 2018 17:36:35 -0700 Subject: [PATCH 105/305] there was literally no reason to have it like that --- src/api/java/baritone/api/Settings.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index fcf84b3a..a755786f 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -531,7 +531,7 @@ public class Settings { // here be dragons - { + Settings() { Field[] temp = getClass().getFields(); HashMap> tmpByName = new HashMap<>(); List> tmpAll = new ArrayList<>(); @@ -566,6 +566,4 @@ public class Settings { } return result; } - - Settings() { } } From d3bf4ef1983eaee5c82bf4d44a62f4379f469cf2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 9 Oct 2018 19:34:53 -0700 Subject: [PATCH 106/305] renderSelectionBoxesIgnoreDepth --- src/api/java/baritone/api/Settings.java | 5 +++++ src/main/java/baritone/utils/PathRenderer.java | 11 ++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index a755786f..a0360909 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -307,6 +307,11 @@ public class Settings { */ public Setting renderGoalIgnoreDepth = new Setting<>(false); + /** + * Ignore depth when rendering the selection boxes (to break, to place, to walk into) + */ + public Setting renderSelectionBoxesIgnoreDepth = new Setting<>(false); + /** * Line width of the path when rendered, in pixels */ diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 841876d8..cde3f1b4 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -19,11 +19,11 @@ package baritone.utils; import baritone.Baritone; import baritone.api.event.events.RenderEvent; +import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.pathing.goals.GoalXZ; -import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.behavior.PathingBehavior; @@ -187,6 +187,11 @@ public final class PathRenderer implements Helper { GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); + + if (Baritone.settings().renderSelectionBoxesIgnoreDepth.get()) { + GlStateManager.disableDepth(); + } + float expand = 0.002F; //BlockPos blockpos = movingObjectPositionIn.getBlockPos(); @@ -228,6 +233,10 @@ public final class PathRenderer implements Helper { TESSELLATOR.draw(); }); + if (Baritone.settings().renderSelectionBoxesIgnoreDepth.get()) { + GlStateManager.enableDepth(); + } + GlStateManager.depthMask(true); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); From 93158226b6bc80141f7e7ad92166a642fd82be5e Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 10 Oct 2018 14:09:41 -0500 Subject: [PATCH 107/305] The sources jar should use SRG names not MCP --- build.gradle | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index d9b78641..5f6008f0 100755 --- a/build.gradle +++ b/build.gradle @@ -61,7 +61,9 @@ minecraft { mappings = 'snapshot_20180731' tweakClass = 'baritone.launch.BaritoneTweaker' runDir = 'run' - makeObfSourceJar = false + + // The sources jar should use SRG names not MCP to ensure compatibility with all mappings + makeObfSourceJar = true } repositories { From 43b155d7b8d7b2b7eef8c8b885c10e16bd9ee3e7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 10 Oct 2018 16:27:38 -0700 Subject: [PATCH 108/305] better check than air --- src/main/java/baritone/behavior/PathingBehavior.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index e2b21579..a7400bdf 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -35,10 +35,8 @@ import baritone.pathing.calc.CutoffPath; import baritone.pathing.movement.MovementHelper; import baritone.pathing.path.PathExecutor; import baritone.utils.BlockBreakHelper; -import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.PathRenderer; -import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; @@ -259,7 +257,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, */ private BlockPos pathStart() { BetterBlockPos feet = playerFeet(); - if (BlockStateInterface.get(feet.down()).getBlock().equals(Blocks.AIR) && MovementHelper.canWalkOn(feet.down().down())) { + if (!MovementHelper.canWalkOn(feet.down()) && MovementHelper.canWalkOn(feet.down().down())) { return feet.down(); } return feet; From 5676acbba6be1b187d8638fd6fffaeae53d3c6db Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 10 Oct 2018 16:29:48 -0700 Subject: [PATCH 109/305] add off hand, fixes #206 --- .../pathing/movement/MovementHelper.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 5b5be77e..d7cce82d 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -31,6 +31,7 @@ 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.ItemPickaxe; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; @@ -457,6 +458,22 @@ public interface MovementHelper extends ActionCosts, Helper { return true; } } + if (Baritone.settings().acceptableThrowawayItems.get().contains(p.inventory.offHandInventory.get(0).getItem())) { + // main hand takes precedence over off hand + // that means that if we have block A selected in main hand and block B in off hand, right clicking places block B + // we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem + // so we need to select in the main hand something that doesn't right click + // so not a shovel, not a hoe, not a block, etc + for (byte i = 0; i < 9; i++) { + ItemStack item = inv.get(i); + if (item.isEmpty() || item.getItem() instanceof ItemPickaxe) { + if (select) { + p.inventory.currentItem = i; + } + return true; + } + } + } return false; } From 7e78ed2139fc1f4edc6d30b11f87c37ab66881fd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 10 Oct 2018 16:40:33 -0700 Subject: [PATCH 110/305] rework minebehavior threading model, fixes #217 --- .../java/baritone/behavior/MineBehavior.java | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index 205c677d..ffa3298d 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -19,7 +19,6 @@ package baritone.behavior; import baritone.Baritone; import baritone.api.behavior.IMineBehavior; -import baritone.api.event.events.PathEvent; import baritone.api.event.events.TickEvent; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; @@ -78,35 +77,37 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0) { if (event.getCount() % mineGoalUpdateInterval == 0) { - Baritone.INSTANCE.getExecutor().execute(this::updateGoal); + Baritone.INSTANCE.getExecutor().execute(this::rescan); } } - PathingBehavior.INSTANCE.revalidateGoal(); - } - - @Override - public void onPathEvent(PathEvent event) { updateGoal(); + PathingBehavior.INSTANCE.revalidateGoal(); } private void updateGoal() { if (mining == null) { return; } - if (!locationsCache.isEmpty()) { - locationsCache = prune(new ArrayList<>(locationsCache), mining, 64); - PathingBehavior.INSTANCE.setGoal(coalesce(locationsCache)); + List locs = locationsCache; + if (!locs.isEmpty()) { + locs = prune(new ArrayList<>(locs), mining, 64); + PathingBehavior.INSTANCE.setGoal(coalesce(locs)); PathingBehavior.INSTANCE.path(); + locationsCache = locs; + } + } + + private void rescan() { + if (mining == null) { + return; } List locs = scanFor(mining, 64); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); - cancel(); + mine(0, (String[]) null); return; } locationsCache = locs; - PathingBehavior.INSTANCE.setGoal(coalesce(locs)); - PathingBehavior.INSTANCE.path(); } public GoalComposite coalesce(List locs) { @@ -176,6 +177,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe this.mining = blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlock).collect(Collectors.toList()); this.quantity = quantity; this.locationsCache = new ArrayList<>(); + rescan(); updateGoal(); } @@ -184,6 +186,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe this.mining = blocks == null || blocks.length == 0 ? null : Arrays.asList(blocks); this.quantity = quantity; this.locationsCache = new ArrayList<>(); + rescan(); updateGoal(); } From fbf0f2271ceafd59238026a8fff7b55a5963c120 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 10 Oct 2018 17:05:51 -0700 Subject: [PATCH 111/305] revamp pathStart, fixes #209 --- .../baritone/behavior/PathingBehavior.java | 44 ++++++++++++++++--- .../java/baritone/utils/PathRenderer.java | 19 ++++---- 2 files changed, 48 insertions(+), 15 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index a7400bdf..35b86717 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -40,9 +40,7 @@ import baritone.utils.PathRenderer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; -import java.util.Collection; -import java.util.HashSet; -import java.util.Optional; +import java.util.*; import java.util.stream.Collectors; public final class PathingBehavior extends Behavior implements IPathingBehavior, Helper { @@ -253,12 +251,46 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } /** + * See issue #209 + * * @return The starting {@link BlockPos} for a new path */ - private BlockPos pathStart() { + public BlockPos pathStart() { BetterBlockPos feet = playerFeet(); - if (!MovementHelper.canWalkOn(feet.down()) && MovementHelper.canWalkOn(feet.down().down())) { - return feet.down(); + if (!MovementHelper.canWalkOn(feet.down())) { + if (player().onGround) { + double playerX = player().posX; + double playerZ = player().posZ; + ArrayList closest = new ArrayList<>(); + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + closest.add(new BetterBlockPos(feet.x + dx, feet.y, feet.z + dz)); + } + } + closest.sort(Comparator.comparingDouble(pos -> ((pos.x + 0.5D) - playerX) * ((pos.x + 0.5D) - playerX) + ((pos.z + 0.5D) - playerZ) * ((pos.z + 0.5D) - playerZ))); + for (int i = 0; i < 4; i++) { + BetterBlockPos possibleSupport = closest.get(i); + double xDist = Math.abs((possibleSupport.x + 0.5D) - playerX); + double zDist = Math.abs((possibleSupport.z + 0.5D) - playerZ); + if (xDist > 0.8 && zDist > 0.8) { + // can't possibly be sneaking off of this one, we're too far away + continue; + } + if (MovementHelper.canWalkOn(possibleSupport.down()) && MovementHelper.canWalkThrough(possibleSupport) && MovementHelper.canWalkThrough(possibleSupport.up())) { + // this is plausible + logDebug("Faking path start assuming player is standing off the edge of a block"); + return possibleSupport; + } + } + + } else { + // !onGround + // we're in the middle of a jump + if (MovementHelper.canWalkOn(feet.down().down())) { + logDebug("Faking path start assuming player is midair and falling"); + return feet.down(); + } + } } return feet; } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index cde3f1b4..b2720df5 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -67,12 +67,13 @@ public final class PathRenderer implements Helper { Goal goal = behavior.getGoal(); EntityPlayerSP player = mc.player; if (goal != null && Baritone.settings().renderGoal.value) { - PathRenderer.drawLitDankGoalBox(player, goal, partialTicks, Baritone.settings().colorGoalBox.get()); + drawLitDankGoalBox(player, goal, partialTicks, Baritone.settings().colorGoalBox.get()); } if (!Baritone.settings().renderPath.get()) { return; } + //drawManySelectionBoxes(player, Collections.singletonList(behavior.pathStart()), partialTicks, Color.WHITE); //long start = System.nanoTime(); @@ -84,28 +85,28 @@ public final class PathRenderer implements Helper { // Render the current path, if there is one if (current != null && current.getPath() != null) { int renderBegin = Math.max(current.getPosition() - 3, 0); - PathRenderer.drawPath(current.getPath(), renderBegin, player, partialTicks, Baritone.settings().colorCurrentPath.get(), Baritone.settings().fadePath.get(), 10, 20); + drawPath(current.getPath(), renderBegin, player, partialTicks, Baritone.settings().colorCurrentPath.get(), Baritone.settings().fadePath.get(), 10, 20); } if (next != null && next.getPath() != null) { - PathRenderer.drawPath(next.getPath(), 0, player, partialTicks, Baritone.settings().colorNextPath.get(), Baritone.settings().fadePath.get(), 10, 20); + drawPath(next.getPath(), 0, player, partialTicks, Baritone.settings().colorNextPath.get(), Baritone.settings().fadePath.get(), 10, 20); } //long split = System.nanoTime(); if (current != null) { - PathRenderer.drawManySelectionBoxes(player, current.toBreak(), partialTicks, Baritone.settings().colorBlocksToBreak.get()); - PathRenderer.drawManySelectionBoxes(player, current.toPlace(), partialTicks, Baritone.settings().colorBlocksToPlace.get()); - PathRenderer.drawManySelectionBoxes(player, current.toWalkInto(), partialTicks, Baritone.settings().colorBlocksToWalkInto.get()); + drawManySelectionBoxes(player, current.toBreak(), partialTicks, Baritone.settings().colorBlocksToBreak.get()); + drawManySelectionBoxes(player, current.toPlace(), partialTicks, Baritone.settings().colorBlocksToPlace.get()); + drawManySelectionBoxes(player, current.toWalkInto(), partialTicks, Baritone.settings().colorBlocksToWalkInto.get()); } // If there is a path calculation currently running, render the path calculation process AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(currentlyRunning -> { currentlyRunning.bestPathSoFar().ifPresent(p -> { - PathRenderer.drawPath(p, 0, player, partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20); + drawPath(p, 0, player, partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20); }); currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { - PathRenderer.drawPath(mr, 0, player, partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); - PathRenderer.drawManySelectionBoxes(player, Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); + drawPath(mr, 0, player, partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); + drawManySelectionBoxes(player, Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); }); }); //long end = System.nanoTime(); From db21045cfb86db262496395629ddd28cc2447116 Mon Sep 17 00:00:00 2001 From: leijurv Date: Wed, 10 Oct 2018 20:38:24 -0700 Subject: [PATCH 112/305] renderPathIgnoreDepth --- src/api/java/baritone/api/Settings.java | 5 +++++ src/main/java/baritone/utils/PathRenderer.java | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index a0360909..e79c5476 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -312,6 +312,11 @@ public class Settings { */ public Setting renderSelectionBoxesIgnoreDepth = new Setting<>(false); + /** + * Ignore depth when rendering the path + */ + public Setting renderPathIgnoreDepth = new Setting<>(false); + /** * Line width of the path when rendered, in pixels */ diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index b2720df5..bf73149e 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -123,6 +123,9 @@ public final class PathRenderer implements Helper { GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); + if (Baritone.settings().renderPathIgnoreDepth.get()) { + GlStateManager.disableDepth(); + } List positions = path.positions(); int next; Tessellator tessellator = Tessellator.getInstance(); @@ -163,6 +166,9 @@ public final class PathRenderer implements Helper { drawLine(player, x1, y1, z1, x2, y2, z2, partialTicks); tessellator.draw(); } + if (Baritone.settings().renderPathIgnoreDepth.get()) { + GlStateManager.enableDepth(); + } //GlStateManager.color(0.0f, 0.0f, 0.0f, 0.4f); GlStateManager.depthMask(true); GlStateManager.enableTexture2D(); From 8c0bc3e2efd085d551038b4bc02ddbef62839f63 Mon Sep 17 00:00:00 2001 From: leijurv Date: Wed, 10 Oct 2018 20:49:05 -0700 Subject: [PATCH 113/305] splice tighter, fixes #44 --- src/main/java/baritone/behavior/PathingBehavior.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 35b86717..f9916611 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -101,6 +101,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, dispatchPathEvent(PathEvent.CONTINUING_ONTO_PLANNED_NEXT); current = next; next = null; + current.onTick(event); return; } // at this point, current just ended, but we aren't in the goal and have no plan for the future From 089037663ef558fe4982dc364363f1c8edce948c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 10 Oct 2018 21:06:31 -0700 Subject: [PATCH 114/305] tweak backtrack cost favoring coefficient --- src/api/java/baritone/api/Settings.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index e79c5476..898501b3 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -156,7 +156,7 @@ public class Settings { * * @see Issue #18 */ - public Setting backtrackCostFavoringCoefficient = new Setting<>(0.1); + public Setting backtrackCostFavoringCoefficient = new Setting<>(0.5); /** * Don't repropagate cost improvements below 0.01 ticks. They're all just floating point inaccuracies, From 9bd205f1905b028bedc495bd2372a4bec00c7d2f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 10 Oct 2018 21:07:59 -0700 Subject: [PATCH 115/305] center pillar regardless of timing --- .../movement/movements/MovementPillar.java | 28 ++++++------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 60803a3c..a43fbe59 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -35,18 +35,11 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; public class MovementPillar extends Movement { - private int numTicks = 0; public MovementPillar(BetterBlockPos start, BetterBlockPos end) { super(start, end, new BetterBlockPos[]{start.up(2)}, start); } - @Override - public void reset() { - super.reset(); - numTicks = 0; - } - @Override protected double calculateCost(CalculationContext context) { return cost(context, src.x, src.y, src.z); @@ -202,24 +195,21 @@ public class MovementPillar extends Movement { return state.setStatus(MovementStatus.UNREACHABLE); } - numTicks++; // If our Y coordinate is above our goal, stop jumping state.setInput(InputOverrideHandler.Input.JUMP, player().posY < dest.getY()); 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); - 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 + double diffX = player().posX - (dest.getX() + 0.5); + double diffZ = player().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); - } + // 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); } + if (!blockIsThere) { Block fr = BlockStateInterface.get(src).getBlock(); From fec29d03fd831b26740765f164a59afe95785316 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 10 Oct 2018 21:25:21 -0700 Subject: [PATCH 116/305] automatically break block while suffocating, fixes #33 --- src/main/java/baritone/pathing/movement/Movement.java | 3 +++ .../baritone/pathing/movement/movements/MovementPillar.java | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 92a1f4db..4b537ac5 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -116,6 +116,9 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { if (BlockStateInterface.isLiquid(playerFeet())) { latestState.setInput(Input.JUMP, true); } + if (player().isEntityInsideOpaqueBlock()) { + latestState.setInput(Input.CLICK_LEFT, 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 -> diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index a43fbe59..853b34d5 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -209,7 +209,7 @@ public class MovementPillar extends Movement { // 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); } - + if (!blockIsThere) { Block fr = BlockStateInterface.get(src).getBlock(); From 8fd921c60ee48fbf5f01dfd166872ef704444e70 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 10 Oct 2018 21:28:55 -0700 Subject: [PATCH 117/305] disable cancelOnGoalInvalidation --- src/api/java/baritone/api/Settings.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 898501b3..04c396fd 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -389,7 +389,7 @@ public class Settings { *

* Also on cosmic prisons this should be set to true since you don't actually mine the ore it just gets replaced with stone. */ - public Setting cancelOnGoalInvalidation = new Setting<>(true); + public Setting cancelOnGoalInvalidation = new Setting<>(false); /** * The "axis" command (aka GoalAxis) will go to a axis, or diagonal axis, at this Y level. From 7dfe6ac3ca1df192817c67b431e56b7a363a821d Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 11 Oct 2018 12:32:42 -0500 Subject: [PATCH 118/305] Add EntityPlayerSP field to relevant events --- .../api/event/events/BlockInteractEvent.java | 2 + .../baritone/api/event/events/ChatEvent.java | 8 ++- .../api/event/events/PacketEvent.java | 10 ++- .../api/event/events/PlayerUpdateEvent.java | 7 ++- .../api/event/events/RotationMoveEvent.java | 7 ++- .../api/event/events/type/Cancellable.java | 10 +-- .../api/event/events/type/ICancellable.java | 35 +++++++++++ .../event/events/type/ManagedPlayerEvent.java | 61 +++++++++++++++++++ .../baritone/launch/mixins/MixinEntity.java | 10 +-- .../launch/mixins/MixinEntityLivingBase.java | 15 +++-- .../launch/mixins/MixinEntityPlayerSP.java | 6 +- .../launch/mixins/MixinNetworkManager.java | 8 +-- 12 files changed, 144 insertions(+), 35 deletions(-) create mode 100644 src/api/java/baritone/api/event/events/type/ICancellable.java create mode 100644 src/api/java/baritone/api/event/events/type/ManagedPlayerEvent.java diff --git a/src/api/java/baritone/api/event/events/BlockInteractEvent.java b/src/api/java/baritone/api/event/events/BlockInteractEvent.java index cc98a6ba..fbdadba1 100644 --- a/src/api/java/baritone/api/event/events/BlockInteractEvent.java +++ b/src/api/java/baritone/api/event/events/BlockInteractEvent.java @@ -20,6 +20,8 @@ package baritone.api.event.events; import net.minecraft.util.math.BlockPos; /** + * Called when the local player interacts with a block, can be either {@link Type#BREAK} or {@link Type#USE}. + * * @author Brady * @since 8/22/2018 */ diff --git a/src/api/java/baritone/api/event/events/ChatEvent.java b/src/api/java/baritone/api/event/events/ChatEvent.java index e103377f..ede83f24 100644 --- a/src/api/java/baritone/api/event/events/ChatEvent.java +++ b/src/api/java/baritone/api/event/events/ChatEvent.java @@ -17,20 +17,22 @@ package baritone.api.event.events; -import baritone.api.event.events.type.Cancellable; +import baritone.api.event.events.type.ManagedPlayerEvent; +import net.minecraft.client.entity.EntityPlayerSP; /** * @author Brady * @since 8/1/2018 6:39 PM */ -public final class ChatEvent extends Cancellable { +public final class ChatEvent extends ManagedPlayerEvent.Cancellable { /** * The message being sent */ private final String message; - public ChatEvent(String message) { + public ChatEvent(EntityPlayerSP player, String message) { + super(player); this.message = message; } diff --git a/src/api/java/baritone/api/event/events/PacketEvent.java b/src/api/java/baritone/api/event/events/PacketEvent.java index 9516db4b..91ffd41f 100644 --- a/src/api/java/baritone/api/event/events/PacketEvent.java +++ b/src/api/java/baritone/api/event/events/PacketEvent.java @@ -18,6 +18,7 @@ package baritone.api.event.events; import baritone.api.event.events.type.EventState; +import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; /** @@ -26,15 +27,22 @@ import net.minecraft.network.Packet; */ public final class PacketEvent { + private NetworkManager networkManager; + private final EventState state; private final Packet packet; - public PacketEvent(EventState state, Packet packet) { + public PacketEvent(NetworkManager networkManager, EventState state, Packet packet) { + this.networkManager = networkManager; this.state = state; this.packet = packet; } + public final NetworkManager getNetworkManager() { + return this.networkManager; + } + public final EventState getState() { return this.state; } diff --git a/src/api/java/baritone/api/event/events/PlayerUpdateEvent.java b/src/api/java/baritone/api/event/events/PlayerUpdateEvent.java index 6ac08bdd..99370552 100644 --- a/src/api/java/baritone/api/event/events/PlayerUpdateEvent.java +++ b/src/api/java/baritone/api/event/events/PlayerUpdateEvent.java @@ -18,19 +18,22 @@ package baritone.api.event.events; import baritone.api.event.events.type.EventState; +import baritone.api.event.events.type.ManagedPlayerEvent; +import net.minecraft.client.entity.EntityPlayerSP; /** * @author Brady * @since 8/21/2018 */ -public final class PlayerUpdateEvent { +public final class PlayerUpdateEvent extends ManagedPlayerEvent { /** * The state of the event */ private final EventState state; - public PlayerUpdateEvent(EventState state) { + public PlayerUpdateEvent(EntityPlayerSP player, EventState state) { + super(player); this.state = state; } diff --git a/src/api/java/baritone/api/event/events/RotationMoveEvent.java b/src/api/java/baritone/api/event/events/RotationMoveEvent.java index ef6d9b7e..7a7514db 100644 --- a/src/api/java/baritone/api/event/events/RotationMoveEvent.java +++ b/src/api/java/baritone/api/event/events/RotationMoveEvent.java @@ -18,6 +18,8 @@ package baritone.api.event.events; import baritone.api.event.events.type.EventState; +import baritone.api.event.events.type.ManagedPlayerEvent; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -25,7 +27,7 @@ import net.minecraft.entity.EntityLivingBase; * @author Brady * @since 8/21/2018 */ -public final class RotationMoveEvent { +public final class RotationMoveEvent extends ManagedPlayerEvent { /** * The type of event @@ -37,7 +39,8 @@ public final class RotationMoveEvent { */ private final EventState state; - public RotationMoveEvent(EventState state, Type type) { + public RotationMoveEvent(EntityPlayerSP player, EventState state, Type type) { + super(player); this.state = state; this.type = type; } diff --git a/src/api/java/baritone/api/event/events/type/Cancellable.java b/src/api/java/baritone/api/event/events/type/Cancellable.java index 331870c6..62ff9049 100644 --- a/src/api/java/baritone/api/event/events/type/Cancellable.java +++ b/src/api/java/baritone/api/event/events/type/Cancellable.java @@ -21,23 +21,19 @@ package baritone.api.event.events.type; * @author Brady * @since 8/1/2018 6:41 PM */ -public class Cancellable { +public class Cancellable implements ICancellable { /** * Whether or not this event has been cancelled */ private boolean cancelled; - /** - * Cancels this event - */ + @Override public final void cancel() { this.cancelled = true; } - /** - * @return Whether or not this event has been cancelled - */ + @Override public final boolean isCancelled() { return this.cancelled; } diff --git a/src/api/java/baritone/api/event/events/type/ICancellable.java b/src/api/java/baritone/api/event/events/type/ICancellable.java new file mode 100644 index 00000000..1df5cd79 --- /dev/null +++ b/src/api/java/baritone/api/event/events/type/ICancellable.java @@ -0,0 +1,35 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.event.events.type; + +/** + * @author Brady + * @since 10/11/2018 + */ +public interface ICancellable { + + /** + * Cancels this event + */ + void cancel(); + + /** + * @return Whether or not this event has been cancelled + */ + boolean isCancelled(); +} diff --git a/src/api/java/baritone/api/event/events/type/ManagedPlayerEvent.java b/src/api/java/baritone/api/event/events/type/ManagedPlayerEvent.java new file mode 100644 index 00000000..a3487a67 --- /dev/null +++ b/src/api/java/baritone/api/event/events/type/ManagedPlayerEvent.java @@ -0,0 +1,61 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.event.events.type; + +import net.minecraft.client.entity.EntityPlayerSP; + +/** + * An event that has a reference to a locally managed player. + * + * @author Brady + * @since 10/11/2018 + */ +public class ManagedPlayerEvent { + + protected final EntityPlayerSP player; + + public ManagedPlayerEvent(EntityPlayerSP player) { + this.player = player; + } + + public final EntityPlayerSP getPlayer() { + return this.player; + } + + public static class Cancellable extends ManagedPlayerEvent implements ICancellable { + + /** + * Whether or not this event has been cancelled + */ + private boolean cancelled; + + public Cancellable(EntityPlayerSP player) { + super(player); + } + + @Override + public final void cancel() { + this.cancelled = true; + } + + @Override + public final boolean isCancelled() { + return this.cancelled; + } + } +} diff --git a/src/launch/java/baritone/launch/mixins/MixinEntity.java b/src/launch/java/baritone/launch/mixins/MixinEntity.java index b96b5b41..c3c040a3 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntity.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntity.java @@ -20,7 +20,7 @@ package baritone.launch.mixins; import baritone.Baritone; import baritone.api.event.events.RotationMoveEvent; import baritone.api.event.events.type.EventState; -import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -40,8 +40,8 @@ public class MixinEntity { ) 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().onPlayerRotationMove(new RotationMoveEvent(EventState.PRE, RotationMoveEvent.Type.MOTION_UPDATE)); + if (_this instanceof EntityPlayerSP) + Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.PRE, RotationMoveEvent.Type.MOTION_UPDATE)); } @Inject( @@ -50,7 +50,7 @@ public class MixinEntity { ) 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().onPlayerRotationMove(new RotationMoveEvent(EventState.POST, RotationMoveEvent.Type.MOTION_UPDATE)); + if (_this instanceof EntityPlayerSP) + Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.POST, RotationMoveEvent.Type.MOTION_UPDATE)); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java index e840576e..b35bad3d 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -20,8 +20,7 @@ package baritone.launch.mixins; import baritone.Baritone; import baritone.api.event.events.RotationMoveEvent; import baritone.api.event.events.type.EventState; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.Entity; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.EntityLivingBase; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -40,9 +39,9 @@ public class MixinEntityLivingBase { at = @At("HEAD") ) private void preJump(CallbackInfo ci) { - Entity _this = (Entity) (Object) this; - if (_this == Minecraft.getMinecraft().player) - Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent(EventState.PRE, RotationMoveEvent.Type.JUMP)); + EntityLivingBase _this = (EntityLivingBase) (Object) this; + if (_this instanceof EntityPlayerSP) + Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.PRE, RotationMoveEvent.Type.JUMP)); } @Inject( @@ -50,8 +49,8 @@ public class MixinEntityLivingBase { at = @At("RETURN") ) private void postJump(CallbackInfo ci) { - Entity _this = (Entity) (Object) this; - if (_this == Minecraft.getMinecraft().player) - Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent(EventState.POST, RotationMoveEvent.Type.JUMP)); + EntityLivingBase _this = (EntityLivingBase) (Object) this; + if (_this instanceof EntityPlayerSP) + Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.POST, RotationMoveEvent.Type.JUMP)); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index e9a575c5..39bc8af1 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -40,7 +40,7 @@ public class MixinEntityPlayerSP { cancellable = true ) private void sendChatMessage(String msg, CallbackInfo ci) { - ChatEvent event = new ChatEvent(msg); + ChatEvent event = new ChatEvent((EntityPlayerSP) (Object) this, msg); Baritone.INSTANCE.getGameEventHandler().onSendChatMessage(event); if (event.isCancelled()) { ci.cancel(); @@ -57,7 +57,7 @@ public class MixinEntityPlayerSP { ) ) private void onPreUpdate(CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.PRE)); + Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.PRE)); } @Inject( @@ -70,6 +70,6 @@ public class MixinEntityPlayerSP { ) ) private void onPostUpdate(CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST)); + Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST)); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java index f79e007f..3f5f297b 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java @@ -54,7 +54,7 @@ public class MixinNetworkManager { ) private void preDispatchPacket(Packet inPacket, final GenericFutureListener>[] futureListeners, CallbackInfo ci) { if (this.direction == EnumPacketDirection.CLIENTBOUND) { - Baritone.INSTANCE.getGameEventHandler().onSendPacket(new PacketEvent(EventState.PRE, inPacket)); + Baritone.INSTANCE.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, inPacket)); } } @@ -64,7 +64,7 @@ public class MixinNetworkManager { ) private void postDispatchPacket(Packet inPacket, final GenericFutureListener>[] futureListeners, CallbackInfo ci) { if (this.direction == EnumPacketDirection.CLIENTBOUND) { - Baritone.INSTANCE.getGameEventHandler().onSendPacket(new PacketEvent(EventState.POST, inPacket)); + Baritone.INSTANCE.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, inPacket)); } } @@ -77,7 +77,7 @@ public class MixinNetworkManager { ) private void preProcessPacket(ChannelHandlerContext context, Packet packet, CallbackInfo ci) { if (this.direction == EnumPacketDirection.CLIENTBOUND) { - Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent(EventState.PRE, packet));} + Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet));} } @Inject( @@ -86,7 +86,7 @@ public class MixinNetworkManager { ) private void postProcessPacket(ChannelHandlerContext context, Packet packet, CallbackInfo ci) { if (this.channel.isOpen() && this.direction == EnumPacketDirection.CLIENTBOUND) { - Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent(EventState.POST, packet)); + Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, packet)); } } } From db7d3184c97e789bc354a5d8cebed96b2920c82c Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 11 Oct 2018 12:34:40 -0500 Subject: [PATCH 119/305] fINAL --- src/api/java/baritone/api/event/events/PacketEvent.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/event/events/PacketEvent.java b/src/api/java/baritone/api/event/events/PacketEvent.java index 91ffd41f..9a3d2315 100644 --- a/src/api/java/baritone/api/event/events/PacketEvent.java +++ b/src/api/java/baritone/api/event/events/PacketEvent.java @@ -27,7 +27,7 @@ import net.minecraft.network.Packet; */ public final class PacketEvent { - private NetworkManager networkManager; + private final NetworkManager networkManager; private final EventState state; From a1c0f4dbb467a63a7e0042e788fc33eb7225b656 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 11:10:59 -0700 Subject: [PATCH 120/305] keep baritone provider properly --- scripts/build.sh | 2 +- scripts/proguard.pro | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/build.sh b/scripts/build.sh index 7c0f83cb..94b02ebf 100644 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -10,7 +10,7 @@ echo "-injars 'baritone-$VERSION.jar'" >> api.pro # insert current version cat ../../scripts/proguard.pro | grep -v "this is the rt jar" | grep -v "\-injars" >> api.pro # remove default rt jar and injar lines echo "-libraryjars '$(java -verbose 2>/dev/null | sed -ne '1 s/\[Opened \(.*\)\]/\1/p')'" >> api.pro # insert correct rt.jar location tail api.pro # debug, print out what the previous two commands generated -cat api.pro | grep -v "\-keep class baritone.api" > standalone.pro # standalone doesn't keep baritone api +cat api.pro | grep -v "this is the keep api" > standalone.pro # standalone doesn't keep baritone api #instead of downloading these jars from my dropbox in a zip, just assume gradle's already got them for us mkdir -p tempLibraries diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 410fcc33..6d865fec 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -16,8 +16,9 @@ -flattenpackagehierarchy -repackageclasses 'baritone' --keep class baritone.api.** { *; } +-keep class baritone.api.** { *; } # this is the keep api -keep class baritone.BaritoneProvider +-keep class baritone.api.IBaritoneProvider # setting names are reflected from field names, so keep field names -keepclassmembers class baritone.api.Settings { From 0db18a7caf91f929244de94ccc8bafd0a8fb72cc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 11:11:19 -0700 Subject: [PATCH 121/305] v0.0.8 --- build.gradle | 2 +- scripts/proguard.pro | 2 +- src/launch/java/baritone/launch/mixins/MixinEntity.java | 4 ++-- .../java/baritone/launch/mixins/MixinEntityLivingBase.java | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 5f6008f0..daf835b9 100755 --- a/build.gradle +++ b/build.gradle @@ -20,7 +20,7 @@ import java.util.jar.JarOutputStream */ group 'baritone' -version '0.0.7' +version '0.0.8' buildscript { repositories { diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 6d865fec..7cb0bce8 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -1,4 +1,4 @@ --injars baritone-0.0.7.jar +-injars baritone-0.0.8.jar -outjars Obfuscated diff --git a/src/launch/java/baritone/launch/mixins/MixinEntity.java b/src/launch/java/baritone/launch/mixins/MixinEntity.java index c3c040a3..fe019bb7 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntity.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntity.java @@ -40,7 +40,7 @@ public class MixinEntity { ) private void preMoveRelative(float strafe, float up, float forward, float friction, CallbackInfo ci) { Entity _this = (Entity) (Object) this; - if (_this instanceof EntityPlayerSP) + if (EntityPlayerSP.class.isInstance(_this)) Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.PRE, RotationMoveEvent.Type.MOTION_UPDATE)); } @@ -50,7 +50,7 @@ public class MixinEntity { ) private void postMoveRelative(float strafe, float up, float forward, float friction, CallbackInfo ci) { Entity _this = (Entity) (Object) this; - if (_this instanceof EntityPlayerSP) + if (EntityPlayerSP.class.isInstance(_this)) Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.POST, RotationMoveEvent.Type.MOTION_UPDATE)); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java index b35bad3d..d2701cff 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -40,7 +40,7 @@ public class MixinEntityLivingBase { ) private void preJump(CallbackInfo ci) { EntityLivingBase _this = (EntityLivingBase) (Object) this; - if (_this instanceof EntityPlayerSP) + if (EntityPlayerSP.class.isInstance(_this)) Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.PRE, RotationMoveEvent.Type.JUMP)); } @@ -50,7 +50,7 @@ public class MixinEntityLivingBase { ) private void postJump(CallbackInfo ci) { EntityLivingBase _this = (EntityLivingBase) (Object) this; - if (_this instanceof EntityPlayerSP) + if (EntityPlayerSP.class.isInstance(_this)) Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.POST, RotationMoveEvent.Type.JUMP)); } } From 54215bdb18cda4e4ec32f581075c641459eb2468 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 11 Oct 2018 14:53:20 -0500 Subject: [PATCH 122/305] Just ONE tweaker When we make the next release, we need to specify in the setup files that Baritone now requires the SimpleTweaker dependency, and we need to remove the old alternate tweaker references. (Optifine and Forge) --- build.gradle | 6 +++ .../java/baritone/launch/BaritoneTweaker.java | 54 ++++++------------- .../baritone/launch/BaritoneTweakerForge.java | 44 --------------- .../launch/BaritoneTweakerOptifine.java | 34 ------------ 4 files changed, 22 insertions(+), 116 deletions(-) delete mode 100644 src/launch/java/baritone/launch/BaritoneTweakerForge.java delete mode 100644 src/launch/java/baritone/launch/BaritoneTweakerOptifine.java diff --git a/build.gradle b/build.gradle index daf835b9..776c4bea 100755 --- a/build.gradle +++ b/build.gradle @@ -73,9 +73,15 @@ repositories { name = 'spongepowered-repo' url = 'http://repo.spongepowered.org/maven/' } + + maven { + name = 'impactdevelopment-repo' + url = 'https://impactdevelopment.github.io/maven/' + } } dependencies { + runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.1') runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') { // Mixin includes a lot of dependencies that are too up-to-date exclude module: 'launchwrapper' diff --git a/src/launch/java/baritone/launch/BaritoneTweaker.java b/src/launch/java/baritone/launch/BaritoneTweaker.java index 536ecf95..e78da09f 100644 --- a/src/launch/java/baritone/launch/BaritoneTweaker.java +++ b/src/launch/java/baritone/launch/BaritoneTweaker.java @@ -17,61 +17,39 @@ package baritone.launch; -import net.minecraft.launchwrapper.ITweaker; +import io.github.impactdevelopment.simpletweaker.SimpleTweaker; +import net.minecraft.launchwrapper.Launch; 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 args; - - @Override - public void acceptOptions(List 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); - } - } +public class BaritoneTweaker extends SimpleTweaker { @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { + super.injectIntoClassLoader(classLoader); + MixinBootstrap.init(); + + // noinspection unchecked + List tweakClasses = (List) Launch.blackboard.get("TweakClasses"); + + String obfuscation = ObfuscationServiceMCP.NOTCH; + if (tweakClasses.stream().anyMatch(s -> s.contains("net.minecraftforge.fml.common.launcher"))) { + obfuscation = ObfuscationServiceMCP.SEARGE; + } + MixinEnvironment.getDefaultEnvironment().setSide(MixinEnvironment.Side.CLIENT); - MixinEnvironment.getDefaultEnvironment().setObfuscationContext(ObfuscationServiceMCP.NOTCH); + MixinEnvironment.getDefaultEnvironment().setObfuscationContext(obfuscation); + 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); - } - } } diff --git a/src/launch/java/baritone/launch/BaritoneTweakerForge.java b/src/launch/java/baritone/launch/BaritoneTweakerForge.java deleted file mode 100644 index 7623eed5..00000000 --- a/src/launch/java/baritone/launch/BaritoneTweakerForge.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -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 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); - } -} diff --git a/src/launch/java/baritone/launch/BaritoneTweakerOptifine.java b/src/launch/java/baritone/launch/BaritoneTweakerOptifine.java deleted file mode 100644 index 9f4f8380..00000000 --- a/src/launch/java/baritone/launch/BaritoneTweakerOptifine.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -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 args, File gameDir, File assetsDir, String profile) { - this.args = new ArrayList<>(); - } -} From ee954d6a4e7ac112210caff070fc79ad7ceedd91 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 13:24:23 -0700 Subject: [PATCH 123/305] break proguard less --- scripts/proguard.pro | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 7cb0bce8..8b406e69 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -33,6 +33,8 @@ -libraryjars 'tempLibraries/minecraft-1.12.2.jar' +-libraryjars 'tempLibraries/SimpleTweaker-1.1.jar' + -libraryjars 'tempLibraries/authlib-1.5.25.jar' -libraryjars 'tempLibraries/codecjorbis-20101023.jar' -libraryjars 'tempLibraries/codecwav-20101023.jar' From 130b21f73891fb0194644fb97264507c8bb4ae6f Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 11 Oct 2018 18:50:55 -0500 Subject: [PATCH 124/305] Fix issue with user input check that messed up Auto Eat --- src/launch/java/baritone/launch/mixins/MixinMinecraft.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 5d2ed420..4e2d8a52 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -147,7 +147,7 @@ public class MixinMinecraft { ) ) private boolean isAllowUserInput(GuiScreen screen) { - return (PathingBehavior.INSTANCE.getCurrent() != null && player != null) || screen.allowUserInput; + return (PathingBehavior.INSTANCE.getCurrent() != null && PathingBehavior.INSTANCE.isEnabled() && player != null) || screen.allowUserInput; } @Inject( From f33a2ef11bdddf9584f61b0e43b648d40c215be4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 18:51:33 -0700 Subject: [PATCH 125/305] fully automated reproducible space deterministic builds --- build.gradle | 34 --------------------------- scripts/Determinizer.java | 49 +++++++++++++++++++++++++++++++++++++++ scripts/build.sh | 18 ++++++++++++-- 3 files changed, 65 insertions(+), 36 deletions(-) create mode 100644 scripts/Determinizer.java diff --git a/build.gradle b/build.gradle index 776c4bea..2d3137ff 100755 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,3 @@ -import java.util.jar.JarEntry -import java.util.jar.JarFile -import java.util.jar.JarOutputStream - /* * This file is part of Baritone. * @@ -103,33 +99,3 @@ jar { preserveFileTimestamps = false reproducibleFileOrder = true } - -build { - // while "jar" supports preserveFileTimestamps false - // reobfJar doesn't, it just sets all the last modified times to that instant where it runs the reobfuscator - // so we have to set all those last modified times back to zero - doLast { - File jarFile = new File("build/libs/baritone-" + version + ".jar") - JarFile jf = new JarFile(jarFile) - JarOutputStream jos = new JarOutputStream(new FileOutputStream(new File("temp.jar"))) - jf.entries().unique { it.name }.sort { it.name }.each { - if (it.name != "META-INF/fml_cache_annotation.json" && it.name != "META-INF/fml_cache_class_versions.json") { - JarEntry clone = new JarEntry(it) - clone.time = 0 - jos.putNextEntry(clone) - copy(jf.getInputStream(it), jos) - } - } - jos.finish() - jf.close() - file("temp.jar").renameTo(jarFile) - } -} - -void copy(InputStream is, OutputStream os) { - byte[] buffer = new byte[1024] - int len = 0 - while ((len = is.read(buffer)) != -1) { - os.write(buffer, 0, len) - } -} diff --git a/scripts/Determinizer.java b/scripts/Determinizer.java new file mode 100644 index 00000000..e15f0b2c --- /dev/null +++ b/scripts/Determinizer.java @@ -0,0 +1,49 @@ +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; +import java.util.stream.Collectors; + +/** + * Make a .jar file deterministic by sorting all entries by name, and setting all the last modified times to 0. + * This makes the build 100% reproducible since the timestamp when you built it no longer affects the final file. + * @author leijurv + */ +public class Determinizer { + + public static void main(String[] args) throws IOException { + System.out.println("Input path: " + args[0] + " Output path: " + args[1]); + JarFile jarFile = new JarFile(new File(args[0])); + JarOutputStream jos = new JarOutputStream(new FileOutputStream(new File(args[1]))); + ArrayList entries = jarFile.stream().collect(Collectors.toCollection(ArrayList::new)); + entries.sort(Comparator.comparing(JarEntry::getName)); + for (JarEntry entry : entries) { + if (entry.getName().equals("META-INF/fml_cache_annotation.json")) { + continue; + } + if (entry.getName().equals("META-INF/fml_cache_class_versions.json")) { + continue; + } + JarEntry clone = new JarEntry(entry.getName()); + clone.setTime(0); + jos.putNextEntry(clone); + copy(jarFile.getInputStream(entry), jos); + } + jos.finish(); + jarFile.close(); + } + + public static void copy(InputStream is, OutputStream os) throws IOException { + byte[] buffer = new byte[1024]; + int len; + while ((len = is.read(buffer)) != -1) { + os.write(buffer, 0, len); + } + } +} diff --git a/scripts/build.sh b/scripts/build.sh index 94b02ebf..6bdb6e5e 100644 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -3,9 +3,17 @@ set -e # this makes the whole script fail immediately if any one of these comman ./gradlew build export VERSION=$(cat build.gradle | grep "version '" | cut -d "'" -f 2-2) +cd scripts +javac Determinizer.java +java Determinizer ../build/libs/baritone-$VERSION.jar temp.jar +mv temp.jar ../build/libs/baritone-$VERSION.jar +cd .. + + wget -nv https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip unzip proguard6.0.3.zip 2>&1 > /dev/null cd build/libs +rm -rf api.pro echo "-injars 'baritone-$VERSION.jar'" >> api.pro # insert current version cat ../../scripts/proguard.pro | grep -v "this is the rt jar" | grep -v "\-injars" >> api.pro # remove default rt jar and injar lines echo "-libraryjars '$(java -verbose 2>/dev/null | sed -ne '1 s/\[Opened \(.*\)\]/\1/p')'" >> api.pro # insert correct rt.jar location @@ -16,11 +24,17 @@ cat api.pro | grep -v "this is the keep api" > standalone.pro # standalone doesn mkdir -p tempLibraries cat ../../scripts/proguard.pro | grep tempLibraries | grep .jar | cut -d "/" -f 2- | cut -d "'" -f -1 | xargs -n1 -I{} bash -c "find ~/.gradle -name {}" | tee /dev/stderr | xargs -n1 -I{} cp {} tempLibraries +rm -rf ../../dist mkdir ../../dist java -jar ../../proguard6.0.3/lib/proguard.jar @api.pro -mv Obfuscated/baritone-$VERSION.jar ../../dist/baritone-api-$VERSION.jar +cd ../../scripts +java Determinizer ../build/libs/Obfuscated/baritone-$VERSION.jar ../dist/baritone-api-$VERSION.jar +cd ../build/libs +rm -rf Obfuscated/* java -jar ../../proguard6.0.3/lib/proguard.jar @standalone.pro -mv Obfuscated/baritone-$VERSION.jar ../../dist/baritone-standalone-$VERSION.jar +cd ../../scripts +java Determinizer ../build/libs/Obfuscated/baritone-$VERSION.jar ../dist/baritone-standalone-$VERSION.jar +cd ../build/libs mv baritone-$VERSION.jar ../../dist/baritone-unoptimized-$VERSION.jar cd ../../dist shasum * | tee checksums.txt From e3b80f11ad9e1c6c4962ba2df398b2b252a4af0c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 20:02:26 -0700 Subject: [PATCH 126/305] brag about how reproducible our builds are --- IMPACT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/IMPACT.md b/IMPACT.md index 6d963a34..5dfc02cb 100644 --- a/IMPACT.md +++ b/IMPACT.md @@ -18,7 +18,7 @@ For Impact 4.3, there is no Baritone integration yet, so you will want `baritone Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. -The build for `baritone-unoptimized-X.Y.Z.jar` is deterministic, and you can verify Travis did it properly by running `scripts/build.sh` yourself and comparing the shasum. The proguarded files (api and standalone) aren't yet reproducible, because proguard annoyingly includes the current timestamp into the final jar. +The build is deterministic, and you can verify Travis did it properly by running `docker build -t cabaletta/baritone. && docker run --rm -it cabaletta/baritone sh scripts/build.sh` yourself and comparing the shasum. Note that for some godawful reason this doesn't work on Mac, the shasums are different even though docker is supposed to work the same everywhere. I get the same shasums as Travis when the host is Linux though. ### Building Baritone yourself There are a few steps to this From b75bc6d03dc92959bf49d6298f146108fb72d5d2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 20:04:45 -0700 Subject: [PATCH 127/305] comment out until its back online --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ad6980f6..9565e468 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![License](https://img.shields.io/github/license/cabaletta/baritone.svg)](LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/7150d8ccf6094057b1782aa7a8f92d7d)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) -Unofficial Jenkins: [![Build Status](https://plutiejenkins.leijurv.com/job/baritone/badge/icon)](https://plutiejenkins.leijurv.com/job/baritone/lastSuccessfulBuild/) + A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). From c2adcdb0510e0977e4e107253ca35981fad9253f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 20:11:35 -0700 Subject: [PATCH 128/305] fix --- IMPACT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/IMPACT.md b/IMPACT.md index 5dfc02cb..16673103 100644 --- a/IMPACT.md +++ b/IMPACT.md @@ -18,7 +18,7 @@ For Impact 4.3, there is no Baritone integration yet, so you will want `baritone Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. -The build is deterministic, and you can verify Travis did it properly by running `docker build -t cabaletta/baritone. && docker run --rm -it cabaletta/baritone sh scripts/build.sh` yourself and comparing the shasum. Note that for some godawful reason this doesn't work on Mac, the shasums are different even though docker is supposed to work the same everywhere. I get the same shasums as Travis when the host is Linux though. +The build is deterministic, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone . && docker run --rm -it cabaletta/baritone sh scripts/build.sh` yourself and comparing the shasum. Note that for some godawful reason this doesn't work on Mac, the shasums are different even though docker is supposed to work the same everywhere. I get the same shasums as Travis when the host is Linux though. ### Building Baritone yourself There are a few steps to this From 773ad89951e5d68cacc86bb9216f7150d11ce119 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 20:36:18 -0700 Subject: [PATCH 129/305] refactor problematic area --- .../java/baritone/behavior/MineBehavior.java | 40 ++++++++++--------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index ffa3298d..c67e9ae6 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -110,28 +110,30 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe locationsCache = locs; } - public GoalComposite coalesce(List locs) { - return new GoalComposite(locs.stream().map(loc -> { - if (!Baritone.settings().forceInternalMining.get()) { + public Goal coalesce(BlockPos loc, List locs) { + if (!Baritone.settings().forceInternalMining.get()) { + return new GoalTwoBlocks(loc); + } + + boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(loc.up()) == Blocks.AIR); + boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(loc.up()) == Blocks.AIR); + if (upwardGoal) { + if (downwardGoal) { + return new GoalTwoBlocks(loc); + } else { + return new GoalBlock(loc); + } + } else { + if (downwardGoal) { + return new GoalBlock(loc.down()); + } else { return new GoalTwoBlocks(loc); } + } + } - boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(loc.up()) == Blocks.AIR); - boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(loc.up()) == Blocks.AIR); - if (upwardGoal) { - if (downwardGoal) { - return new GoalTwoBlocks(loc); - } else { - return new GoalBlock(loc); - } - } else { - if (downwardGoal) { - return new GoalBlock(loc.down()); - } else { - return new GoalTwoBlocks(loc); - } - } - }).toArray(Goal[]::new)); + public GoalComposite coalesce(List locs) { + return new GoalComposite(locs.stream().map(loc -> coalesce(loc, locs)).toArray(Goal[]::new)); } public List scanFor(List mining, int max) { From 7e4a1169af54a24668a6e5c20873d051f1c0e12f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 21:04:07 -0700 Subject: [PATCH 130/305] extract, sort, and reinsert refmap json into final jar --- scripts/build.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/build.sh b/scripts/build.sh index 6bdb6e5e..7249d14d 100644 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -3,6 +3,10 @@ set -e # this makes the whole script fail immediately if any one of these comman ./gradlew build export VERSION=$(cat build.gradle | grep "version '" | cut -d "'" -f 2-2) +unzip -p build/libs/baritone-$VERSION.jar "mixins.baritone.refmap.json" | jq -S -c -M '.' > mixins.baritone.refmap.json +zip -u build/libs/baritone-$VERSION.jar mixins.baritone.refmap.json +rm mixins.baritone.refmap.json + cd scripts javac Determinizer.java java Determinizer ../build/libs/baritone-$VERSION.jar temp.jar From 9d3d8f6c823306e3188c994cecc7f6b54f1a8e9a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 21:05:00 -0700 Subject: [PATCH 131/305] forgot install --- Dockerfile | 2 +- scripts/build.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 7f5b0199..fec88f25 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,7 @@ RUN apt install --target-release jessie-backports \ RUN apt install -qq --force-yes mesa-utils libgl1-mesa-glx libxcursor1 libxrandr2 libxxf86vm1 x11-xserver-utils xfonts-base xserver-common -RUN apt install -qq --force-yes unzip wget +RUN apt install -qq --force-yes unzip wget jq COPY . /code diff --git a/scripts/build.sh b/scripts/build.sh index 7249d14d..4f0bc608 100644 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -3,7 +3,7 @@ set -e # this makes the whole script fail immediately if any one of these comman ./gradlew build export VERSION=$(cat build.gradle | grep "version '" | cut -d "'" -f 2-2) -unzip -p build/libs/baritone-$VERSION.jar "mixins.baritone.refmap.json" | jq -S -c -M '.' > mixins.baritone.refmap.json +unzip -p build/libs/baritone-$VERSION.jar "mixins.baritone.refmap.json" | jq --sort-keys -c -M '.' > mixins.baritone.refmap.json zip -u build/libs/baritone-$VERSION.jar mixins.baritone.refmap.json rm mixins.baritone.refmap.json From 5167c0c88669e127829df762eb887fda95a584f5 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 21:12:00 -0700 Subject: [PATCH 132/305] zip too --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index fec88f25..e4fdb406 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,7 @@ RUN apt install --target-release jessie-backports \ RUN apt install -qq --force-yes mesa-utils libgl1-mesa-glx libxcursor1 libxrandr2 libxxf86vm1 x11-xserver-utils xfonts-base xserver-common -RUN apt install -qq --force-yes unzip wget jq +RUN apt install -qq --force-yes unzip wget jq zip COPY . /code From 76e4a1a6494a2615bcc58ca981e5bdb5f03d4f69 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Oct 2018 21:22:46 -0700 Subject: [PATCH 133/305] brag about reproducible builds some more --- IMPACT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/IMPACT.md b/IMPACT.md index 16673103..a6ca56f2 100644 --- a/IMPACT.md +++ b/IMPACT.md @@ -18,7 +18,7 @@ For Impact 4.3, there is no Baritone integration yet, so you will want `baritone Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. -The build is deterministic, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone . && docker run --rm -it cabaletta/baritone sh scripts/build.sh` yourself and comparing the shasum. Note that for some godawful reason this doesn't work on Mac, the shasums are different even though docker is supposed to work the same everywhere. I get the same shasums as Travis when the host is Linux though. +The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone . && docker run --rm -it cabaletta/baritone sh scripts/build.sh` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). ### Building Baritone yourself There are a few steps to this From 8a65f43a0b7b12f735e24b814fe32bee998ee384 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Oct 2018 14:12:06 -0700 Subject: [PATCH 134/305] check world border, fixes #218 --- .../pathing/calc/AStarPathFinder.java | 16 ++++++-- .../utils/pathing/BetterWorldBorder.java | 39 +++++++++++++++++++ 2 files changed, 51 insertions(+), 4 deletions(-) create mode 100644 src/main/java/baritone/utils/pathing/BetterWorldBorder.java diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index f4adc7e2..a0deae58 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -18,15 +18,16 @@ package baritone.pathing.calc; import baritone.Baritone; +import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.ActionCosts; -import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import baritone.pathing.calc.openset.BinaryHeapOpenSet; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Moves; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; +import baritone.utils.pathing.BetterWorldBorder; import baritone.utils.pathing.MutableMoveResult; import java.util.HashSet; @@ -63,6 +64,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel CalculationContext calcContext = new CalculationContext(); MutableMoveResult res = new MutableMoveResult(); HashSet favored = favoredPositions.orElse(null); + BetterWorldBorder worldBorder = new BetterWorldBorder(world().getWorldBorder()); BlockStateInterface.clearCachedChunk(); long startTime = System.nanoTime() / 1000000L; boolean slowPath = Baritone.settings().slowPath.get(); @@ -106,6 +108,9 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel continue; } } + if (!moves.dynamicXZ && !worldBorder.entirelyContains(newX, newZ)) { + continue; + } res.reset(); moves.apply(calcContext, currentNode.x, currentNode.y, currentNode.z, res); numMovementsConsidered++; @@ -113,6 +118,12 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel if (actionCost >= ActionCosts.COST_INF) { continue; } + if (actionCost <= 0) { + throw new IllegalStateException(moves + " calculated implausible cost " + actionCost); + } + if (moves.dynamicXZ && !worldBorder.entirelyContains(res.x, res.z)) { // see issue #218 + continue; + } // check destination after verifying it's not COST_INF -- some movements return a static IMPOSSIBLE object with COST_INF and destination being 0,0,0 to avoid allocating a new result for every failed calculation if (!moves.dynamicXZ && (res.x != newX || res.z != newZ)) { throw new IllegalStateException(moves + " " + res.x + " " + newX + " " + res.z + " " + newZ); @@ -120,9 +131,6 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel if (!moves.dynamicY && res.y != currentNode.y + moves.yOffset) { throw new IllegalStateException(moves + " " + res.x + " " + newX + " " + res.z + " " + newZ); } - if (actionCost <= 0) { - throw new IllegalStateException(moves + " calculated implausible cost " + actionCost); - } long hashCode = BetterBlockPos.longHash(res.x, res.y, res.z); if (favoring && favored.contains(hashCode)) { // see issue #18 diff --git a/src/main/java/baritone/utils/pathing/BetterWorldBorder.java b/src/main/java/baritone/utils/pathing/BetterWorldBorder.java new file mode 100644 index 00000000..8c105275 --- /dev/null +++ b/src/main/java/baritone/utils/pathing/BetterWorldBorder.java @@ -0,0 +1,39 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils.pathing; + +import baritone.utils.Helper; +import net.minecraft.world.border.WorldBorder; + +public class BetterWorldBorder implements Helper { + double minX; + double maxX; + double minZ; + double maxZ; + + public BetterWorldBorder(WorldBorder border) { + this.minX = border.minX(); + this.maxX = border.maxX(); + this.minZ = border.minZ(); + this.maxZ = border.maxZ(); + } + + public boolean entirelyContains(int x, int z) { + return x + 1 > minX && x < maxX && z + 1 > minZ && z < maxZ; + } +} From c5f5445f4bb780a02cb984bd8c41202c2c4278ba Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Oct 2018 14:19:11 -0700 Subject: [PATCH 135/305] fix exception when calculating descend from starting position above 256 --- src/main/java/baritone/pathing/calc/AStarPathFinder.java | 3 +++ src/main/java/baritone/pathing/movement/Moves.java | 8 ++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index a0deae58..9fbb3979 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -111,6 +111,9 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel if (!moves.dynamicXZ && !worldBorder.entirelyContains(newX, newZ)) { continue; } + if ((currentNode.y == 256 && moves.yOffset > 0) || (currentNode.y == 0 && moves.yOffset < 0)) { + continue; + } res.reset(); moves.apply(calcContext, currentNode.x, currentNode.y, currentNode.z, res); numMovementsConsidered++; diff --git a/src/main/java/baritone/pathing/movement/Moves.java b/src/main/java/baritone/pathing/movement/Moves.java index 3d53ff5b..80a6c4d5 100644 --- a/src/main/java/baritone/pathing/movement/Moves.java +++ b/src/main/java/baritone/pathing/movement/Moves.java @@ -148,7 +148,7 @@ public enum Moves { } }, - DESCEND_EAST(+1, 0, 0, false, true) { + DESCEND_EAST(+1, -1, 0, false, true) { @Override public Movement apply0(BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); @@ -166,7 +166,7 @@ public enum Moves { } }, - DESCEND_WEST(-1, 0, 0, false, true) { + DESCEND_WEST(-1, -1, 0, false, true) { @Override public Movement apply0(BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); @@ -184,7 +184,7 @@ public enum Moves { } }, - DESCEND_NORTH(0, 0, -1, false, true) { + DESCEND_NORTH(0, -1, -1, false, true) { @Override public Movement apply0(BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); @@ -202,7 +202,7 @@ public enum Moves { } }, - DESCEND_SOUTH(0, 0, +1, false, true) { + DESCEND_SOUTH(0, -1, +1, false, true) { @Override public Movement apply0(BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); From 6b7a8e2bd3f7c88e081fed8d87dba976bf1739c3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Oct 2018 14:34:33 -0700 Subject: [PATCH 136/305] better protection logic, fix placing outside worldborder --- .../pathing/movement/CalculationContext.java | 28 +++++++++++++++++++ .../pathing/movement/MovementHelper.java | 11 +------- .../movement/movements/MovementAscend.java | 2 +- .../movement/movements/MovementParkour.java | 4 +-- .../movement/movements/MovementPillar.java | 2 +- .../movement/movements/MovementTraverse.java | 2 +- .../utils/pathing/BetterWorldBorder.java | 7 +++++ 7 files changed, 41 insertions(+), 15 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 0b40539e..9f08d578 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -21,6 +21,7 @@ import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; import baritone.utils.Helper; import baritone.utils.ToolSet; +import baritone.utils.pathing.BetterWorldBorder; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; @@ -44,6 +45,7 @@ public class CalculationContext implements Helper { private final int maxFallHeightBucket; private final double waterWalkSpeed; private final double breakBlockAdditionalCost; + private final BetterWorldBorder worldBorder; public CalculationContext() { this(new ToolSet()); @@ -68,6 +70,32 @@ public class CalculationContext implements Helper { // 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. + this.worldBorder = new BetterWorldBorder(world().getWorldBorder()); + } + + public boolean canPlaceThrowawayAt(int x, int y, int z) { + if (!hasThrowaway()) { // only true if allowPlace is true, see constructor + return false; + } + if (isPossiblyProtected(x, y, z)) { + return false; + } + return worldBorder.canPlaceAt(x, z); // TODO perhaps MovementHelper.canPlaceAgainst could also use this? + } + + public boolean canBreakAt(int x, int y, int z) { + if (!allowBreak()) { + return false; + } + if (isPossiblyProtected(x, y, z)) { + return false; + } + return true; + } + + public boolean isPossiblyProtected(int x, int y, int z) { + // TODO more protection logic here; see #220 + return false; } public ToolSet getToolSet() { diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index d7cce82d..e393c92e 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -343,15 +343,6 @@ public interface MovementHelper extends ActionCosts, Helper { return state.isBlockNormalCube(); } - static double getMiningDurationTicks(CalculationContext context, BetterBlockPos position, boolean includeFalling) { - IBlockState state = BlockStateInterface.get(position); - return getMiningDurationTicks(context, position.x, position.y, position.z, state, includeFalling); - } - - static double getMiningDurationTicks(CalculationContext context, BetterBlockPos position, IBlockState state, boolean includeFalling) { - return getMiningDurationTicks(context, position.x, position.y, position.z, state, includeFalling); - } - static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, boolean includeFalling) { return getMiningDurationTicks(context, x, y, z, BlockStateInterface.get(x, y, z), includeFalling); } @@ -359,7 +350,7 @@ public interface MovementHelper extends ActionCosts, Helper { static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) { Block block = state.getBlock(); if (!canWalkThrough(x, y, z, state)) { - if (!context.allowBreak()) { + if (!context.canBreakAt(x, y, z)) { return COST_INF; } if (avoidBreaking(x, y, z, state)) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 6989179b..09271779 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -72,7 +72,7 @@ public class MovementAscend extends Movement { } boolean hasToPlace = false; if (!MovementHelper.canWalkOn(destX, y, destZ, toPlace)) { - if (!context.hasThrowaway()) { + if (!context.canPlaceThrowawayAt(destX, y, destZ)) { return COST_INF; } if (toPlace.getBlock() != Blocks.AIR && !BlockStateInterface.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y, destZ, toPlace)) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 94b7dfea..23348990 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -118,7 +118,7 @@ public class MovementParkour extends Movement { int destX = x + 4 * xDiff; int destZ = z + 4 * zDiff; IBlockState toPlace = BlockStateInterface.get(destX, y - 1, destZ); - if (!context.hasThrowaway()) { + if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { return; } if (toPlace.getBlock() != Blocks.AIR && !BlockStateInterface.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y - 1, destZ, toPlace)) { @@ -225,7 +225,7 @@ public class MovementParkour extends Movement { } state.setInput(InputOverrideHandler.Input.JUMP, true); - } else if(!playerFeet().equals(dest.offset(direction, -1))) { + } else if (!playerFeet().equals(dest.offset(direction, -1))) { state.setInput(InputOverrideHandler.Input.SPRINT, false); if (playerFeet().equals(src.offset(direction, -1))) { MovementHelper.moveTowards(state, src); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 853b34d5..799a4e9b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -76,7 +76,7 @@ public class MovementPillar extends Movement { return LADDER_UP_ONE_COST; } } - if (!context.hasThrowaway() && !ladder) { + if (!ladder && !context.canPlaceThrowawayAt(x, y, z)) { return COST_INF; } double hardness = MovementHelper.getMiningDurationTicks(context, x, y + 2, z, toBreak, true); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index f029619a..367d2c17 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -108,7 +108,7 @@ public class MovementTraverse extends Movement { if (BlockStateInterface.isWater(destOn.getBlock()) && throughWater) { return COST_INF; } - if (!context.hasThrowaway()) { + if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { return COST_INF; } double hardness1 = MovementHelper.getMiningDurationTicks(context, destX, y, destZ, pb0, false); diff --git a/src/main/java/baritone/utils/pathing/BetterWorldBorder.java b/src/main/java/baritone/utils/pathing/BetterWorldBorder.java index 8c105275..c9ffe5bd 100644 --- a/src/main/java/baritone/utils/pathing/BetterWorldBorder.java +++ b/src/main/java/baritone/utils/pathing/BetterWorldBorder.java @@ -36,4 +36,11 @@ public class BetterWorldBorder implements Helper { public boolean entirelyContains(int x, int z) { return x + 1 > minX && x < maxX && z + 1 > minZ && z < maxZ; } + + public boolean canPlaceAt(int x, int z) { + // move it in 1 block on all sides + // because we can't place a block at the very edge against a block outside the border + // it won't let us right click it + return x > minX && x + 1 < maxX && z > minZ && z + 1 < maxZ; + } } From 4892192c6c686b8557c0f29071218621ac3f2c40 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Oct 2018 15:14:39 -0700 Subject: [PATCH 137/305] remove unused functions --- .../pathing/movement/MovementHelper.java | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index e393c92e..7517cdce 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -48,10 +48,6 @@ import java.util.Optional; */ public interface MovementHelper extends ActionCosts, Helper { - static boolean avoidBreaking(BetterBlockPos pos, IBlockState state) { - return avoidBreaking(pos.x, pos.y, pos.z, state); - } - static boolean avoidBreaking(int x, int y, int z, IBlockState state) { Block b = state.getBlock(); return b == Blocks.ICE // ice becomes water, and water can mess up the path @@ -74,10 +70,6 @@ public interface MovementHelper extends ActionCosts, Helper { return canWalkThrough(pos.x, pos.y, pos.z, BlockStateInterface.get(pos)); } - static boolean canWalkThrough(BetterBlockPos pos, IBlockState state) { - return canWalkThrough(pos.x, pos.y, pos.z, state); - } - static boolean canWalkThrough(int x, int y, int z) { return canWalkThrough(x, y, z, BlockStateInterface.get(x, y, z)); } @@ -139,10 +131,6 @@ public interface MovementHelper extends ActionCosts, Helper { * * @return */ - static boolean fullyPassable(BlockPos pos) { - return fullyPassable(BlockStateInterface.get(pos)); - } - static boolean fullyPassable(int x, int y, int z) { return fullyPassable(BlockStateInterface.get(x, y, z)); } @@ -170,10 +158,6 @@ public interface MovementHelper extends ActionCosts, Helper { return block.isPassable(null, null); } - static boolean isReplacable(BlockPos pos, IBlockState state) { - return isReplacable(pos.getX(), pos.getY(), pos.getZ(), state); - } - static boolean isReplacable(int x, int y, int z, IBlockState state) { // for MovementTraverse and MovementAscend // block double plant defaults to true when the block doesn't match, so don't need to check that case From b443be1795d0fd611e62ed3ab546dea67586ee83 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Oct 2018 15:29:25 -0700 Subject: [PATCH 138/305] more accurate check --- src/main/java/baritone/pathing/calc/AStarPathFinder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index 9fbb3979..020acc34 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -111,7 +111,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel if (!moves.dynamicXZ && !worldBorder.entirelyContains(newX, newZ)) { continue; } - if ((currentNode.y == 256 && moves.yOffset > 0) || (currentNode.y == 0 && moves.yOffset < 0)) { + if (currentNode.y + moves.yOffset > 256 || currentNode.y + moves.yOffset < 0) { continue; } res.reset(); From 8fba36c05e32801856d26f7c4f7ced09926e5f88 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 17:56:09 -0500 Subject: [PATCH 139/305] Initial Proguard Task meme Working Determinizer, but it doesn't sort the JSON object keys time to rek travis --- build.gradle | 10 + buildSrc/.gitignore | 3 + buildSrc/build.gradle | 25 ++ .../java/baritone/gradle/ProguardTask.java | 314 ++++++++++++++++++ .../baritone/gradle/util/Determinizer.java | 85 +++++ scripts/proguard.pro | 12 +- 6 files changed, 441 insertions(+), 8 deletions(-) create mode 100644 buildSrc/.gitignore create mode 100644 buildSrc/build.gradle create mode 100644 buildSrc/src/main/java/baritone/gradle/ProguardTask.java create mode 100644 buildSrc/src/main/java/baritone/gradle/util/Determinizer.java diff --git a/build.gradle b/build.gradle index 2d3137ff..aa8f5763 100755 --- a/build.gradle +++ b/build.gradle @@ -37,6 +37,8 @@ buildscript { } } +import baritone.gradle.ProguardTask + apply plugin: 'java' apply plugin: 'net.minecraftforge.gradle.tweaker-client' apply plugin: 'org.spongepowered.mixin' @@ -99,3 +101,11 @@ jar { preserveFileTimestamps = false reproducibleFileOrder = true } + +task proguard(type: ProguardTask) { + url 'https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip' + extract 'proguard6.0.3/lib/proguard.jar' + versionManifest 'https://launchermeta.mojang.com/mc/game/version_manifest.json' +} + +build.finalizedBy(proguard) diff --git a/buildSrc/.gitignore b/buildSrc/.gitignore new file mode 100644 index 00000000..daf21d56 --- /dev/null +++ b/buildSrc/.gitignore @@ -0,0 +1,3 @@ +build/ +.gradle/ +out/ \ No newline at end of file diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle new file mode 100644 index 00000000..2ac49af0 --- /dev/null +++ b/buildSrc/build.gradle @@ -0,0 +1,25 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +repositories { + mavenCentral() +} + +dependencies { + compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5' + compile group: 'commons-io', name: 'commons-io', version: '2.6' +} \ No newline at end of file diff --git a/buildSrc/src/main/java/baritone/gradle/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/ProguardTask.java new file mode 100644 index 00000000..7450d471 --- /dev/null +++ b/buildSrc/src/main/java/baritone/gradle/ProguardTask.java @@ -0,0 +1,314 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.gradle; + +import baritone.gradle.util.Determinizer; +import com.google.gson.*; +import javafx.util.Pair; +import org.apache.commons.io.IOUtils; +import org.gradle.api.DefaultTask; +import org.gradle.api.artifacts.Configuration; +import org.gradle.api.artifacts.Dependency; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.TaskAction; + +import java.io.*; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; + +/** + * @author Brady + * @since 10/11/2018 + */ +public class ProguardTask extends DefaultTask { + + private static final JsonParser PARSER = new JsonParser(); + + private static final Pattern TEMP_LIBRARY_PATTERN = Pattern.compile("-libraryjars 'tempLibraries\\/([a-zA-Z0-9/_\\-\\.]+)\\.jar'"); + + private static final String + PROGUARD_ZIP = "proguard.zip", + PROGUARD_JAR = "proguard.jar", + PROGUARD_CONFIG_TEMPLATE = "scripts/proguard.pro", + PROGUARD_CONFIG_DEST = "template.pro", + PROGUARD_API_CONFIG = "api.pro", + PROGUARD_STANDALONE_CONFIG = "standalone.pro", + PROGUARD_EXPORT_PATH = "proguard_out.jar", + + VERSION_MANIFEST = "version_manifest.json", + + TEMP_LIBRARY_DIR = "tempLibraries/", + + ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar", + ARTIFACT_API = "%s-api-%s.jar", + ARTIFACT_STANDALONE = "%s-standalone-%s.jar"; + + @Input + private String url; + + @Input + private String extract; + + @Input + private String versionManifest; + + private String artifactName, artifactVersion; + private Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut; + private Map versionDownloadMap; + private List requiredLibraries; + + @TaskAction + private void exec() throws Exception { + // "Haha brady why don't you make separate tasks" + verifyArtifacts(); + processArtifact(); + downloadProguard(); + extractProguard(); + generateConfigs(); + downloadVersionManifest(); + acquireDependencies(); + proguardApi(); + proguardStandalone(); + cleanup(); + } + + private void verifyArtifacts() throws Exception { + this.artifactName = getProject().getName(); + this.artifactVersion = getProject().getVersion().toString(); + + // The compiled baritone artifact that is exported when the build task is ran + String artifactName = String.format("%s-%s.jar", this.artifactName, this.artifactVersion); + + this.artifactPath = this.getBuildFile(artifactName); + this.artifactUnoptimizedPath = this.getBuildFile(String.format(ARTIFACT_UNOPTIMIZED, this.artifactName, this.artifactVersion)); + this.artifactApiPath = this.getBuildFile(String.format(ARTIFACT_API, this.artifactName, this.artifactVersion)); + this.artifactStandalonePath = this.getBuildFile(String.format(ARTIFACT_STANDALONE, this.artifactName, this.artifactVersion)); + + this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH); + + if (!Files.exists(this.artifactPath)) { + throw new Exception("Artifact not found! Run build first!"); + } + } + + private void processArtifact() throws Exception { + if (Files.exists(this.artifactUnoptimizedPath)) { + Files.delete(this.artifactUnoptimizedPath); + } + + Determinizer.main(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString()); + } + + private void downloadProguard() throws Exception { + Path proguardZip = getTemporaryFile(PROGUARD_ZIP); + if (!Files.exists(proguardZip)) { + write(new URL(this.url).openStream(), proguardZip); + } + } + + private void extractProguard() throws Exception { + Path proguardJar = getTemporaryFile(PROGUARD_JAR); + if (!Files.exists(proguardJar)) { + ZipFile zipFile = new ZipFile(getTemporaryFile(PROGUARD_ZIP).toFile()); + ZipEntry zipJarEntry = zipFile.getEntry(this.extract); + write(zipFile.getInputStream(zipJarEntry), proguardJar); + zipFile.close(); + } + } + + private void generateConfigs() throws Exception { + Files.copy(getRelativeFile(PROGUARD_CONFIG_TEMPLATE), getTemporaryFile(PROGUARD_CONFIG_DEST), REPLACE_EXISTING); + + // Setup the template that will be used to derive the API and Standalone configs + List template = Files.readAllLines(getTemporaryFile(PROGUARD_CONFIG_DEST)); + template.removeIf(s -> s.endsWith("# this is the rt jar") || s.startsWith("-injars") || s.startsWith("-outjars")); + template.add(0, "-injars " + this.artifactPath.toString()); + template.add(1, "-outjars " + this.getTemporaryFile(PROGUARD_EXPORT_PATH)); + + // Acquire the RT jar using "java -verbose". This doesn't work on Java 9+ + Process p = new ProcessBuilder("java", "-verbose").start(); + String out = IOUtils.toString(p.getInputStream(), "UTF-8").split("\n")[0].split("Opened ")[1].replace("]", ""); + template.add(2, "-libraryjars '" + out + "'"); + + // API config doesn't require any changes from the changes that we made to the template + Files.write(getTemporaryFile(PROGUARD_API_CONFIG), template); + + // For the Standalone config, don't keep the API package + List standalone = new ArrayList<>(template); + standalone.removeIf(s -> s.contains("# this is the keep api")); + Files.write(getTemporaryFile(PROGUARD_STANDALONE_CONFIG), standalone); + + // Discover all of the libraries that we will need to acquire from gradle + this.requiredLibraries = new ArrayList<>(); + template.forEach(line -> { + if (!line.startsWith("#")) { + Matcher m = TEMP_LIBRARY_PATTERN.matcher(line); + if (m.find()) { + this.requiredLibraries.add(m.group(1)); + } + } + }); + } + + private void downloadVersionManifest() throws Exception { + Path manifestJson = getTemporaryFile(VERSION_MANIFEST); + write(new URL(this.versionManifest).openStream(), manifestJson); + + // Place all the versions in the map with their download URL + this.versionDownloadMap = new HashMap<>(); + JsonObject json = readJson(Files.readAllLines(manifestJson)).getAsJsonObject(); + JsonArray versions = json.getAsJsonArray("versions"); + versions.forEach(element -> { + JsonObject object = element.getAsJsonObject(); + this.versionDownloadMap.put(object.get("id").getAsString(), object.get("url").getAsString()); + }); + } + + private void acquireDependencies() throws Exception { + + // Create a map of all of the dependencies that we are able to access in this project + // Likely a better way to do this, I just pair the dependency with the first valid configuration + Map> dependencyLookupMap = new HashMap<>(); + getProject().getConfigurations().stream().filter(Configuration::isCanBeResolved).forEach(config -> + config.getAllDependencies().forEach(dependency -> + dependencyLookupMap.putIfAbsent(dependency.getName() + "-" + dependency.getVersion(), new Pair<>(config, dependency)))); + + // Create the directory if it doesn't already exist + Path tempLibraries = getTemporaryFile(TEMP_LIBRARY_DIR); + if (!Files.exists(tempLibraries)) { + Files.createDirectory(tempLibraries); + } + + // Iterate the required libraries to copy them to tempLibraries + for (String lib : this.requiredLibraries) { + // Download the version jar from the URL acquired from the version manifest + if (lib.startsWith("minecraft")) { + String version = lib.split("-")[1]; + Path versionJar = getTemporaryFile("tempLibraries/" + lib + ".jar"); + if (!Files.exists(versionJar)) { + write(new URL(this.versionDownloadMap.get(version)).openStream(), versionJar); + } + continue; + } + + // Find a configuration/dependency pair that matches the desired library + Pair pair = null; + for (Map.Entry> entry : dependencyLookupMap.entrySet()) { + if (entry.getKey().startsWith(lib)) { + pair = entry.getValue(); + } + } + + // The pair must be non-null + Objects.requireNonNull(pair); + + // Find the library jar file, and copy it to tempLibraries + for (File file : pair.getKey().files(pair.getValue())) { + if (file.getName().startsWith(lib)) { + Files.copy(file.toPath(), getTemporaryFile("tempLibraries/" + lib + ".jar"), REPLACE_EXISTING); + } + } + } + } + + private void proguardApi() throws Exception { + runProguard(getTemporaryFile(PROGUARD_API_CONFIG)); + Determinizer.main(this.proguardOut.toString(), this.artifactApiPath.toString()); + } + + private void proguardStandalone() throws Exception { + runProguard(getTemporaryFile(PROGUARD_STANDALONE_CONFIG)); + Determinizer.main(this.proguardOut.toString(), this.artifactStandalonePath.toString()); + } + + private void cleanup() { + try { + Files.delete(this.proguardOut); + } catch (IOException ignored) {} + } + + public void setUrl(String url) { + this.url = url; + } + + public void setExtract(String extract) { + this.extract = extract; + } + + public void setVersionManifest(String versionManifest) { + this.versionManifest = versionManifest; + } + + /* + * A LOT OF SHITTY UTIL METHODS ARE BELOW. + * + * PROCEED WITH CAUTION + */ + + private void runProguard(Path config) throws Exception { + // Delete the existing proguard output file. Proguard probably handles this already, but why not do it ourselves + if (Files.exists(this.proguardOut)) { + Files.delete(this.proguardOut); + } + + Path proguardJar = getTemporaryFile(PROGUARD_JAR); + Process p = new ProcessBuilder("java", "-jar", proguardJar.toString(), "@" + config.toString()) + .directory(getTemporaryFile("").toFile()) // Set the working directory to the temporary folder + .redirectOutput(ProcessBuilder.Redirect.INHERIT) + .redirectError(ProcessBuilder.Redirect.INHERIT) + .start(); + + // Halt the current thread until the process is complete, if the exit code isn't 0, throw an exception + int exitCode; + if ((exitCode = p.waitFor()) != 0) { + throw new Exception("Proguard exited with code " + exitCode); + } + } + + private void write(InputStream stream, Path file) throws Exception { + if (Files.exists(file)) { + Files.delete(file); + } + Files.copy(stream, file); + } + + private Path getRelativeFile(String file) { + return Paths.get(new File(file).getAbsolutePath()); + } + + private Path getTemporaryFile(String file) { + return Paths.get(new File(getTemporaryDir(), file).getAbsolutePath()); + } + + private Path getBuildFile(String file) { + return getRelativeFile("build/libs/" + file); + } + + private JsonElement readJson(List lines) { + return PARSER.parse(String.join("\n", lines)); + } +} diff --git a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java new file mode 100644 index 00000000..4b4f4748 --- /dev/null +++ b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java @@ -0,0 +1,85 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.gradle.util; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Comparator; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; +import java.util.stream.Collectors; + +/** + * Make a .jar file deterministic by sorting all entries by name, and setting all the last modified times to 0. + * This makes the build 100% reproducible since the timestamp when you built it no longer affects the final file. + * + * @author leijurv + */ +public class Determinizer { + + public static void main(String... args) throws IOException { + /* + haha yeah can't relate + + unzip -p build/libs/baritone-$VERSION.jar "mixins.baritone.refmap.json" | jq --sort-keys -c -M '.' > mixins.baritone.refmap.json + zip -u build/libs/baritone-$VERSION.jar mixins.baritone.refmap.json + rm mixins.baritone.refmap.json + */ + + System.out.println("Running Determinizer"); + System.out.println(" Input path: " + args[0]); + System.out.println(" Output path: " + args[1]); + + JarFile jarFile = new JarFile(new File(args[0])); + JarOutputStream jos = new JarOutputStream(new FileOutputStream(new File(args[1]))); + + List entries = jarFile.stream() + .sorted(Comparator.comparing(JarEntry::getName)) + .collect(Collectors.toList()); + + for (JarEntry entry : entries) { + if (entry.getName().equals("META-INF/fml_cache_annotation.json")) { + continue; + } + if (entry.getName().equals("META-INF/fml_cache_class_versions.json")) { + continue; + } + JarEntry clone = new JarEntry(entry.getName()); + clone.setTime(0); + jos.putNextEntry(clone); + copy(jarFile.getInputStream(entry), jos); + } + + jos.finish(); + jos.close(); + jarFile.close(); + } + + private static void copy(InputStream is, OutputStream os) throws IOException { + byte[] buffer = new byte[1024]; + int len; + while ((len = is.read(buffer)) != -1) { + os.write(buffer, 0, len); + } + } +} diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 8b406e69..261b47d1 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -49,7 +49,6 @@ -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.jar' -libraryjars 'tempLibraries/jinput-2.0.5.jar' -libraryjars 'tempLibraries/jna-4.4.0.jar' -libraryjars 'tempLibraries/jopt-simple-5.0.3.jar' @@ -60,13 +59,10 @@ -libraryjars 'tempLibraries/log4j-api-2.8.1.jar' -libraryjars 'tempLibraries/log4j-core-2.8.1.jar' -# linux / travis --libraryjars 'tempLibraries/lwjgl-2.9.4-nightly-20150209.jar' --libraryjars 'tempLibraries/lwjgl_util-2.9.4-nightly-20150209.jar' - -# mac -#-libraryjars 'tempLibraries/lwjgl_util-2.9.2-nightly-20140822.jar' -#-libraryjars 'tempLibraries/lwjgl-2.9.2-nightly-20140822.jar' +# startsWith is used to check the library, and mac/linux differ in which version they use +# this is FINE +-libraryjars 'tempLibraries/lwjgl-.jar' +-libraryjars 'tempLibraries/lwjgl_util-.jar' -libraryjars 'tempLibraries/netty-all-4.1.9.Final.jar' -libraryjars 'tempLibraries/oshi-core-1.1.jar' From 93286a646f2492fcbcd6e4a062a2e1f50b565886 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 18:08:15 -0500 Subject: [PATCH 140/305] Use Gradle Internal Pair --- buildSrc/src/main/java/baritone/gradle/ProguardTask.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/ProguardTask.java index 7450d471..4fec6392 100644 --- a/buildSrc/src/main/java/baritone/gradle/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/ProguardTask.java @@ -19,13 +19,13 @@ package baritone.gradle; import baritone.gradle.util.Determinizer; import com.google.gson.*; -import javafx.util.Pair; import org.apache.commons.io.IOUtils; import org.gradle.api.DefaultTask; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.Dependency; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.TaskAction; +import org.gradle.internal.Pair; import java.io.*; import java.net.URL; @@ -195,7 +195,7 @@ public class ProguardTask extends DefaultTask { Map> dependencyLookupMap = new HashMap<>(); getProject().getConfigurations().stream().filter(Configuration::isCanBeResolved).forEach(config -> config.getAllDependencies().forEach(dependency -> - dependencyLookupMap.putIfAbsent(dependency.getName() + "-" + dependency.getVersion(), new Pair<>(config, dependency)))); + dependencyLookupMap.putIfAbsent(dependency.getName() + "-" + dependency.getVersion(), Pair.of(config, dependency)))); // Create the directory if it doesn't already exist Path tempLibraries = getTemporaryFile(TEMP_LIBRARY_DIR); @@ -227,7 +227,7 @@ public class ProguardTask extends DefaultTask { Objects.requireNonNull(pair); // Find the library jar file, and copy it to tempLibraries - for (File file : pair.getKey().files(pair.getValue())) { + for (File file : pair.getLeft().files(pair.getRight())) { if (file.getName().startsWith(lib)) { Files.copy(file.toPath(), getTemporaryFile("tempLibraries/" + lib + ".jar"), REPLACE_EXISTING); } From 416fea2aa51638abe4c2d902ea2168698c865203 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 18:10:54 -0500 Subject: [PATCH 141/305] Remove unnecessary removeIf usage --- buildSrc/src/main/java/baritone/gradle/ProguardTask.java | 1 - scripts/proguard.pro | 5 ----- 2 files changed, 6 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/ProguardTask.java index 4fec6392..c7d5662a 100644 --- a/buildSrc/src/main/java/baritone/gradle/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/ProguardTask.java @@ -145,7 +145,6 @@ public class ProguardTask extends DefaultTask { // Setup the template that will be used to derive the API and Standalone configs List template = Files.readAllLines(getTemporaryFile(PROGUARD_CONFIG_DEST)); - template.removeIf(s -> s.endsWith("# this is the rt jar") || s.startsWith("-injars") || s.startsWith("-outjars")); template.add(0, "-injars " + this.artifactPath.toString()); template.add(1, "-outjars " + this.getTemporaryFile(PROGUARD_EXPORT_PATH)); diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 261b47d1..4baa4b2a 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -1,7 +1,3 @@ --injars baritone-0.0.8.jar --outjars Obfuscated - - -keepattributes Signature -keepattributes *Annotation* @@ -29,7 +25,6 @@ -keep class baritone.launch.** { *; } # copy all necessary libraries into tempLibraries to build --libraryjars '/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/rt.jar' # this is the rt jar -libraryjars 'tempLibraries/minecraft-1.12.2.jar' From 24f18f0ac2f31fce1b0cb3f50ac02f5d3e8fba89 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 19:47:13 -0500 Subject: [PATCH 142/305] Json sorting --- .../baritone/gradle/util/Determinizer.java | 124 ++++++++++++++++-- 1 file changed, 110 insertions(+), 14 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java index 4b4f4748..a4dcaca3 100644 --- a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java +++ b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java @@ -17,13 +17,16 @@ package baritone.gradle.util; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; +import com.google.gson.*; +import com.google.gson.internal.LazilyParsedNumber; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.*; +import java.util.ArrayList; import java.util.Comparator; import java.util.List; +import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; @@ -38,14 +41,6 @@ import java.util.stream.Collectors; public class Determinizer { public static void main(String... args) throws IOException { - /* - haha yeah can't relate - - unzip -p build/libs/baritone-$VERSION.jar "mixins.baritone.refmap.json" | jq --sort-keys -c -M '.' > mixins.baritone.refmap.json - zip -u build/libs/baritone-$VERSION.jar mixins.baritone.refmap.json - rm mixins.baritone.refmap.json - */ - System.out.println("Running Determinizer"); System.out.println(" Input path: " + args[0]); System.out.println(" Output path: " + args[1]); @@ -67,7 +62,12 @@ public class Determinizer { JarEntry clone = new JarEntry(entry.getName()); clone.setTime(0); jos.putNextEntry(clone); - copy(jarFile.getInputStream(entry), jos); + if (entry.getName().endsWith(".refmap.json")) { + JsonObject object = new JsonParser().parse(new InputStreamReader(jarFile.getInputStream(entry))).getAsJsonObject(); + copy(writeSorted(object), jos); + } else { + copy(jarFile.getInputStream(entry), jos); + } } jos.finish(); @@ -82,4 +82,100 @@ public class Determinizer { os.write(buffer, 0, len); } } + + private static void copy(String s, OutputStream os) throws IOException { + os.write(s.getBytes()); + } + + private static String writeSorted(JsonObject in) throws IOException { + StringWriter writer = new StringWriter(); + JsonWriter jw = new JsonWriter(writer); + JSON_ELEMENT.write(jw, in); + return writer.toString() + "\n"; + } + + /** + * All credits go to GSON and its contributors. GSON is licensed under the Apache 2.0 License. + * This implementation has been modified to write {@link JsonObject} keys in order. + * + * @see GSON License + * @see Original Source + */ + private static final TypeAdapter JSON_ELEMENT = new TypeAdapter() { + + @Override + public JsonElement read(JsonReader in) throws IOException { + switch (in.peek()) { + case STRING: + return new JsonPrimitive(in.nextString()); + case NUMBER: + String number = in.nextString(); + return new JsonPrimitive(new LazilyParsedNumber(number)); + case BOOLEAN: + return new JsonPrimitive(in.nextBoolean()); + case NULL: + in.nextNull(); + return JsonNull.INSTANCE; + case BEGIN_ARRAY: + JsonArray array = new JsonArray(); + in.beginArray(); + while (in.hasNext()) { + array.add(read(in)); + } + in.endArray(); + return array; + case BEGIN_OBJECT: + JsonObject object = new JsonObject(); + in.beginObject(); + while (in.hasNext()) { + object.add(in.nextName(), read(in)); + } + in.endObject(); + return object; + case END_DOCUMENT: + case NAME: + case END_OBJECT: + case END_ARRAY: + default: + throw new IllegalArgumentException(); + } + } + + @Override + public void write(JsonWriter out, JsonElement value) throws IOException { + if (value == null || value.isJsonNull()) { + out.nullValue(); + } else if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isNumber()) { + out.value(primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + out.value(primitive.getAsBoolean()); + } else { + out.value(primitive.getAsString()); + } + + } else if (value.isJsonArray()) { + out.beginArray(); + for (JsonElement e : value.getAsJsonArray()) { + write(out, e); + } + out.endArray(); + + } else if (value.isJsonObject()) { + out.beginObject(); + + List> entries = new ArrayList<>(value.getAsJsonObject().entrySet()); + entries.sort(Comparator.comparing(Map.Entry::getKey)); + for (Map.Entry e : entries) { + out.name(e.getKey()); + write(out, e.getValue()); + } + out.endObject(); + + } else { + throw new IllegalArgumentException("Couldn't write " + value.getClass()); + } + } + }; } From df1633b2a1446eb077a57ee7c743159240a7dd78 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 20:42:24 -0500 Subject: [PATCH 143/305] You shouldn't write a json to a jar and treat it like a jar --- buildSrc/src/main/java/baritone/gradle/ProguardTask.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/buildSrc/src/main/java/baritone/gradle/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/ProguardTask.java index c7d5662a..86e138ab 100644 --- a/buildSrc/src/main/java/baritone/gradle/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/ProguardTask.java @@ -209,7 +209,9 @@ public class ProguardTask extends DefaultTask { String version = lib.split("-")[1]; Path versionJar = getTemporaryFile("tempLibraries/" + lib + ".jar"); if (!Files.exists(versionJar)) { - write(new URL(this.versionDownloadMap.get(version)).openStream(), versionJar); + JsonObject versionJson = PARSER.parse(new InputStreamReader(new URL(this.versionDownloadMap.get(version)).openStream())).getAsJsonObject(); + String url = versionJson.getAsJsonObject("downloads").getAsJsonObject("client").getAsJsonPrimitive("url").getAsString(); + write(new URL(url).openStream(), versionJar); } continue; } From 96c66d2809292ec03e94125b9258c9557b752d32 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 21:21:16 -0500 Subject: [PATCH 144/305] CreateDist task --- .gitignore | 1 + .travis.yml | 2 +- build.gradle | 8 +- .../gradle/task/BaritoneGradleTask.java | 102 ++++++++++++++++++ .../baritone/gradle/task/CreateDistTask.java | 81 ++++++++++++++ .../gradle/{ => task}/ProguardTask.java | 95 ++++------------ scripts/Determinizer.java | 49 --------- scripts/build.sh | 45 -------- 8 files changed, 211 insertions(+), 172 deletions(-) create mode 100644 buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java create mode 100644 buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java rename buildSrc/src/main/java/baritone/gradle/{ => task}/ProguardTask.java (75%) delete mode 100644 scripts/Determinizer.java delete mode 100644 scripts/build.sh diff --git a/.gitignore b/.gitignore index 74dc7ea2..de408ec0 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ run/ autotest/ +dist/ # Gradle build/ diff --git a/.travis.yml b/.travis.yml index c54706cf..a8344ba0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,7 +9,7 @@ install: - travis_retry docker build -t cabaletta/baritone . script: -- docker run --name baritone cabaletta/baritone /bin/sh -c "set -e; /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 128x128x24 -ac +extension GLX +render; sh scripts/build.sh; DISPLAY=:99 BARITONE_AUTO_TEST=true ./gradlew runClient" +- docker run --name baritone cabaletta/baritone /bin/sh -c "set -e; /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 128x128x24 -ac +extension GLX +render; DISPLAY=:99 BARITONE_AUTO_TEST=true ./gradlew runClient" - docker cp baritone:/code/dist dist - ls dist - cat dist/checksums.txt diff --git a/build.gradle b/build.gradle index aa8f5763..34020ece 100755 --- a/build.gradle +++ b/build.gradle @@ -37,7 +37,9 @@ buildscript { } } -import baritone.gradle.ProguardTask + +import baritone.gradle.task.CreateDistTask +import baritone.gradle.task.ProguardTask apply plugin: 'java' apply plugin: 'net.minecraftforge.gradle.tweaker-client' @@ -108,4 +110,6 @@ task proguard(type: ProguardTask) { versionManifest 'https://launchermeta.mojang.com/mc/game/version_manifest.json' } -build.finalizedBy(proguard) +task createDist(type: CreateDistTask, dependsOn: proguard) + +build.finalizedBy(createDist) diff --git a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java new file mode 100644 index 00000000..22dac86e --- /dev/null +++ b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java @@ -0,0 +1,102 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.gradle.task; + +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import org.gradle.api.DefaultTask; + +import java.io.File; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +/** + * @author Brady + * @since 10/12/2018 + */ +class BaritoneGradleTask extends DefaultTask { + + static final JsonParser PARSER = new JsonParser(); + + static final String + PROGUARD_ZIP = "proguard.zip", + PROGUARD_JAR = "proguard.jar", + PROGUARD_CONFIG_TEMPLATE = "scripts/proguard.pro", + PROGUARD_CONFIG_DEST = "template.pro", + PROGUARD_API_CONFIG = "api.pro", + PROGUARD_STANDALONE_CONFIG = "standalone.pro", + PROGUARD_EXPORT_PATH = "proguard_out.jar", + + VERSION_MANIFEST = "version_manifest.json", + + TEMP_LIBRARY_DIR = "tempLibraries/", + + ARTIFACT_STANDARD = "%s-%s.jar", + ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar", + ARTIFACT_API = "%s-api-%s.jar", + ARTIFACT_STANDALONE = "%s-standalone-%s.jar"; + + String artifactName, artifactVersion; + Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut; + + void verifyArtifacts() throws Exception { + this.artifactName = getProject().getName(); + this.artifactVersion = getProject().getVersion().toString(); + + this.artifactPath = this.getBuildFile(formatVersion(ARTIFACT_STANDARD)); + this.artifactUnoptimizedPath = this.getBuildFile(formatVersion(ARTIFACT_UNOPTIMIZED)); + this.artifactApiPath = this.getBuildFile(formatVersion(ARTIFACT_API)); + this.artifactStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_STANDALONE)); + + this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH); + + if (!Files.exists(this.artifactPath)) { + throw new Exception("Artifact not found! Run build first!"); + } + } + + void write(InputStream stream, Path file) throws Exception { + if (Files.exists(file)) { + Files.delete(file); + } + Files.copy(stream, file); + } + + String formatVersion(String string) { + return String.format(string, this.artifactName, this.artifactVersion); + } + + Path getRelativeFile(String file) { + return Paths.get(new File(file).getAbsolutePath()); + } + + Path getTemporaryFile(String file) { + return Paths.get(new File(getTemporaryDir(), file).getAbsolutePath()); + } + + Path getBuildFile(String file) { + return getRelativeFile("build/libs/" + file); + } + + JsonElement readJson(List lines) { + return PARSER.parse(String.join("\n", lines)); + } +} diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java new file mode 100644 index 00000000..34c9df57 --- /dev/null +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -0,0 +1,81 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.gradle.task; + +import org.gradle.api.tasks.TaskAction; + +import javax.xml.bind.DatatypeConverter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; + +/** + * @author Brady + * @since 10/12/2018 + */ +public class CreateDistTask extends BaritoneGradleTask { + + private static MessageDigest SHA1_DIGEST; + + @TaskAction + private void exec() throws Exception { + super.verifyArtifacts(); + + // Define the distribution file paths + Path unoptimized = getRelativeFile("dist/" + formatVersion(ARTIFACT_UNOPTIMIZED)); + Path api = getRelativeFile("dist/" + formatVersion(ARTIFACT_API)); + Path standalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_STANDALONE)); + + // NIO will not automatically create directories + Path dir = getRelativeFile("dist/"); + if (!Files.exists(dir)) { + Files.createDirectory(dir); + } + + // Copy build jars to dist/ + Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING); + Files.copy(this.artifactApiPath, api, REPLACE_EXISTING); + Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING); + + // Calculate all checksums and format them like "shasum" + List shasum = Stream.of(unoptimized, api, standalone) + .map(path -> sha1(path) + " " + path.getFileName().toString()) + .collect(Collectors.toList()); + + // Write the checksums to a file + Files.write(getRelativeFile("dist/checksums.txt"), shasum); + } + + private static String sha1(Path path) { + try { + if (SHA1_DIGEST == null) { + SHA1_DIGEST = MessageDigest.getInstance("SHA-1"); + } + return DatatypeConverter.printHexBinary(SHA1_DIGEST.digest(Files.readAllBytes(path))).toLowerCase(); + } catch (Exception e) { + // haha no thanks + throw new RuntimeException(e); + } + } +} diff --git a/buildSrc/src/main/java/baritone/gradle/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java similarity index 75% rename from buildSrc/src/main/java/baritone/gradle/ProguardTask.java rename to buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java index 86e138ab..ad0db8cc 100644 --- a/buildSrc/src/main/java/baritone/gradle/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java @@ -15,12 +15,11 @@ * along with Baritone. If not, see . */ -package baritone.gradle; +package baritone.gradle.task; import baritone.gradle.util.Determinizer; import com.google.gson.*; import org.apache.commons.io.IOUtils; -import org.gradle.api.DefaultTask; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.Dependency; import org.gradle.api.tasks.Input; @@ -31,7 +30,6 @@ import java.io.*; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -44,29 +42,10 @@ import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; * @author Brady * @since 10/11/2018 */ -public class ProguardTask extends DefaultTask { - - private static final JsonParser PARSER = new JsonParser(); +public class ProguardTask extends BaritoneGradleTask { private static final Pattern TEMP_LIBRARY_PATTERN = Pattern.compile("-libraryjars 'tempLibraries\\/([a-zA-Z0-9/_\\-\\.]+)\\.jar'"); - private static final String - PROGUARD_ZIP = "proguard.zip", - PROGUARD_JAR = "proguard.jar", - PROGUARD_CONFIG_TEMPLATE = "scripts/proguard.pro", - PROGUARD_CONFIG_DEST = "template.pro", - PROGUARD_API_CONFIG = "api.pro", - PROGUARD_STANDALONE_CONFIG = "standalone.pro", - PROGUARD_EXPORT_PATH = "proguard_out.jar", - - VERSION_MANIFEST = "version_manifest.json", - - TEMP_LIBRARY_DIR = "tempLibraries/", - - ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar", - ARTIFACT_API = "%s-api-%s.jar", - ARTIFACT_STANDALONE = "%s-standalone-%s.jar"; - @Input private String url; @@ -76,15 +55,14 @@ public class ProguardTask extends DefaultTask { @Input private String versionManifest; - private String artifactName, artifactVersion; - private Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut; private Map versionDownloadMap; private List requiredLibraries; @TaskAction private void exec() throws Exception { + super.verifyArtifacts(); + // "Haha brady why don't you make separate tasks" - verifyArtifacts(); processArtifact(); downloadProguard(); extractProguard(); @@ -96,25 +74,6 @@ public class ProguardTask extends DefaultTask { cleanup(); } - private void verifyArtifacts() throws Exception { - this.artifactName = getProject().getName(); - this.artifactVersion = getProject().getVersion().toString(); - - // The compiled baritone artifact that is exported when the build task is ran - String artifactName = String.format("%s-%s.jar", this.artifactName, this.artifactVersion); - - this.artifactPath = this.getBuildFile(artifactName); - this.artifactUnoptimizedPath = this.getBuildFile(String.format(ARTIFACT_UNOPTIMIZED, this.artifactName, this.artifactVersion)); - this.artifactApiPath = this.getBuildFile(String.format(ARTIFACT_API, this.artifactName, this.artifactVersion)); - this.artifactStandalonePath = this.getBuildFile(String.format(ARTIFACT_STANDALONE, this.artifactName, this.artifactVersion)); - - this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH); - - if (!Files.exists(this.artifactPath)) { - throw new Exception("Artifact not found! Run build first!"); - } - } - private void processArtifact() throws Exception { if (Files.exists(this.artifactUnoptimizedPath)) { Files.delete(this.artifactUnoptimizedPath); @@ -264,12 +223,6 @@ public class ProguardTask extends DefaultTask { this.versionManifest = versionManifest; } - /* - * A LOT OF SHITTY UTIL METHODS ARE BELOW. - * - * PROCEED WITH CAUTION - */ - private void runProguard(Path config) throws Exception { // Delete the existing proguard output file. Proguard probably handles this already, but why not do it ourselves if (Files.exists(this.proguardOut)) { @@ -278,11 +231,13 @@ public class ProguardTask extends DefaultTask { Path proguardJar = getTemporaryFile(PROGUARD_JAR); Process p = new ProcessBuilder("java", "-jar", proguardJar.toString(), "@" + config.toString()) - .directory(getTemporaryFile("").toFile()) // Set the working directory to the temporary folder - .redirectOutput(ProcessBuilder.Redirect.INHERIT) - .redirectError(ProcessBuilder.Redirect.INHERIT) + .directory(getTemporaryFile("").toFile()) // Set the working directory to the temporary folder] .start(); + // We can't do output inherit process I/O with gradle for some reason and have it work, so we have to do this + this.printOutputLog(p.getInputStream()); + this.printOutputLog(p.getErrorStream()); + // Halt the current thread until the process is complete, if the exit code isn't 0, throw an exception int exitCode; if ((exitCode = p.waitFor()) != 0) { @@ -290,26 +245,16 @@ public class ProguardTask extends DefaultTask { } } - private void write(InputStream stream, Path file) throws Exception { - if (Files.exists(file)) { - Files.delete(file); - } - Files.copy(stream, file); - } - - private Path getRelativeFile(String file) { - return Paths.get(new File(file).getAbsolutePath()); - } - - private Path getTemporaryFile(String file) { - return Paths.get(new File(getTemporaryDir(), file).getAbsolutePath()); - } - - private Path getBuildFile(String file) { - return getRelativeFile("build/libs/" + file); - } - - private JsonElement readJson(List lines) { - return PARSER.parse(String.join("\n", lines)); + private void printOutputLog(InputStream stream) { + new Thread(() -> { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { + String line; + while ((line = reader.readLine()) != null) { + System.out.println(line); + } + } catch (final Exception e) { + e.printStackTrace(); + } + }).start(); } } diff --git a/scripts/Determinizer.java b/scripts/Determinizer.java deleted file mode 100644 index e15f0b2c..00000000 --- a/scripts/Determinizer.java +++ /dev/null @@ -1,49 +0,0 @@ -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.JarOutputStream; -import java.util.stream.Collectors; - -/** - * Make a .jar file deterministic by sorting all entries by name, and setting all the last modified times to 0. - * This makes the build 100% reproducible since the timestamp when you built it no longer affects the final file. - * @author leijurv - */ -public class Determinizer { - - public static void main(String[] args) throws IOException { - System.out.println("Input path: " + args[0] + " Output path: " + args[1]); - JarFile jarFile = new JarFile(new File(args[0])); - JarOutputStream jos = new JarOutputStream(new FileOutputStream(new File(args[1]))); - ArrayList entries = jarFile.stream().collect(Collectors.toCollection(ArrayList::new)); - entries.sort(Comparator.comparing(JarEntry::getName)); - for (JarEntry entry : entries) { - if (entry.getName().equals("META-INF/fml_cache_annotation.json")) { - continue; - } - if (entry.getName().equals("META-INF/fml_cache_class_versions.json")) { - continue; - } - JarEntry clone = new JarEntry(entry.getName()); - clone.setTime(0); - jos.putNextEntry(clone); - copy(jarFile.getInputStream(entry), jos); - } - jos.finish(); - jarFile.close(); - } - - public static void copy(InputStream is, OutputStream os) throws IOException { - byte[] buffer = new byte[1024]; - int len; - while ((len = is.read(buffer)) != -1) { - os.write(buffer, 0, len); - } - } -} diff --git a/scripts/build.sh b/scripts/build.sh deleted file mode 100644 index 4f0bc608..00000000 --- a/scripts/build.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/sh -set -e # this makes the whole script fail immediately if any one of these commands fails -./gradlew build -export VERSION=$(cat build.gradle | grep "version '" | cut -d "'" -f 2-2) - -unzip -p build/libs/baritone-$VERSION.jar "mixins.baritone.refmap.json" | jq --sort-keys -c -M '.' > mixins.baritone.refmap.json -zip -u build/libs/baritone-$VERSION.jar mixins.baritone.refmap.json -rm mixins.baritone.refmap.json - -cd scripts -javac Determinizer.java -java Determinizer ../build/libs/baritone-$VERSION.jar temp.jar -mv temp.jar ../build/libs/baritone-$VERSION.jar -cd .. - - -wget -nv https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip -unzip proguard6.0.3.zip 2>&1 > /dev/null -cd build/libs -rm -rf api.pro -echo "-injars 'baritone-$VERSION.jar'" >> api.pro # insert current version -cat ../../scripts/proguard.pro | grep -v "this is the rt jar" | grep -v "\-injars" >> api.pro # remove default rt jar and injar lines -echo "-libraryjars '$(java -verbose 2>/dev/null | sed -ne '1 s/\[Opened \(.*\)\]/\1/p')'" >> api.pro # insert correct rt.jar location -tail api.pro # debug, print out what the previous two commands generated -cat api.pro | grep -v "this is the keep api" > standalone.pro # standalone doesn't keep baritone api - -#instead of downloading these jars from my dropbox in a zip, just assume gradle's already got them for us -mkdir -p tempLibraries -cat ../../scripts/proguard.pro | grep tempLibraries | grep .jar | cut -d "/" -f 2- | cut -d "'" -f -1 | xargs -n1 -I{} bash -c "find ~/.gradle -name {}" | tee /dev/stderr | xargs -n1 -I{} cp {} tempLibraries - -rm -rf ../../dist -mkdir ../../dist -java -jar ../../proguard6.0.3/lib/proguard.jar @api.pro -cd ../../scripts -java Determinizer ../build/libs/Obfuscated/baritone-$VERSION.jar ../dist/baritone-api-$VERSION.jar -cd ../build/libs -rm -rf Obfuscated/* -java -jar ../../proguard6.0.3/lib/proguard.jar @standalone.pro -cd ../../scripts -java Determinizer ../build/libs/Obfuscated/baritone-$VERSION.jar ../dist/baritone-standalone-$VERSION.jar -cd ../build/libs -mv baritone-$VERSION.jar ../../dist/baritone-unoptimized-$VERSION.jar -cd ../../dist -shasum * | tee checksums.txt -cd .. \ No newline at end of file From d1a9012deb317488b86ebd89b0ed041f92f52cb6 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 21:24:24 -0500 Subject: [PATCH 145/305] 2 spaces --- buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index 34c9df57..2d1b2d98 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -60,7 +60,7 @@ public class CreateDistTask extends BaritoneGradleTask { // Calculate all checksums and format them like "shasum" List shasum = Stream.of(unoptimized, api, standalone) - .map(path -> sha1(path) + " " + path.getFileName().toString()) + .map(path -> sha1(path) + " " + path.getFileName().toString()) .collect(Collectors.toList()); // Write the checksums to a file From 3958dce3410386b4d41e0fbc55a1433df6a37f28 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 21:31:33 -0500 Subject: [PATCH 146/305] cancer --- .../src/main/java/baritone/gradle/task/CreateDistTask.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index 2d1b2d98..12900eb7 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -63,6 +63,9 @@ public class CreateDistTask extends BaritoneGradleTask { .map(path -> sha1(path) + " " + path.getFileName().toString()) .collect(Collectors.toList()); + System.out.println("$ > shasum im cool haha look at me"); + shasum.forEach(System.out::println); + // Write the checksums to a file Files.write(getRelativeFile("dist/checksums.txt"), shasum); } From 7efc0ae8ca75de06f9c6a83fec8aa06f62c8b19d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Oct 2018 19:33:03 -0700 Subject: [PATCH 147/305] fix snow bs --- src/main/java/baritone/pathing/movement/MovementHelper.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 7517cdce..9fd7d994 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -99,7 +99,9 @@ public interface MovementHelper extends ActionCosts, Helper { return true; } if (snow) { - return state.getValue(BlockSnow.LAYERS) < 5; // see BlockSnow.isPassable + // the check in BlockSnow.isPassable is layers < 5 + // while actually, we want < 3 because 3 or greater makes it impassable in a 2 high ceiling + return state.getValue(BlockSnow.LAYERS) < 3; } if (trapdoor) { return !state.getValue(BlockTrapDoor.OPEN); // see BlockTrapDoor.isPassable From 045504ecf79938a589be0529bf49622ebca0c4c9 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 21:38:05 -0500 Subject: [PATCH 148/305] No differences. 100% NONE --- .../main/java/baritone/gradle/task/CreateDistTask.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index 12900eb7..f0d3e547 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -43,9 +43,9 @@ public class CreateDistTask extends BaritoneGradleTask { super.verifyArtifacts(); // Define the distribution file paths - Path unoptimized = getRelativeFile("dist/" + formatVersion(ARTIFACT_UNOPTIMIZED)); Path api = getRelativeFile("dist/" + formatVersion(ARTIFACT_API)); Path standalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_STANDALONE)); + Path unoptimized = getRelativeFile("dist/" + formatVersion(ARTIFACT_UNOPTIMIZED)); // NIO will not automatically create directories Path dir = getRelativeFile("dist/"); @@ -54,18 +54,15 @@ public class CreateDistTask extends BaritoneGradleTask { } // Copy build jars to dist/ - Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING); Files.copy(this.artifactApiPath, api, REPLACE_EXISTING); Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING); + Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING); // Calculate all checksums and format them like "shasum" - List shasum = Stream.of(unoptimized, api, standalone) + List shasum = Stream.of(api, standalone, unoptimized) .map(path -> sha1(path) + " " + path.getFileName().toString()) .collect(Collectors.toList()); - System.out.println("$ > shasum im cool haha look at me"); - shasum.forEach(System.out::println); - // Write the checksums to a file Files.write(getRelativeFile("dist/checksums.txt"), shasum); } From 2fc282477ddd9393f2574c08959e32da31996f75 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 22:13:21 -0500 Subject: [PATCH 149/305] No need to override Read --- .../baritone/gradle/util/Determinizer.java | 42 ++----------------- 1 file changed, 4 insertions(+), 38 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java index a4dcaca3..21b2e50a 100644 --- a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java +++ b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java @@ -18,7 +18,6 @@ package baritone.gradle.util; import com.google.gson.*; -import com.google.gson.internal.LazilyParsedNumber; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -90,7 +89,7 @@ public class Determinizer { private static String writeSorted(JsonObject in) throws IOException { StringWriter writer = new StringWriter(); JsonWriter jw = new JsonWriter(writer); - JSON_ELEMENT.write(jw, in); + ORDERED_JSON_WRITER.write(jw, in); return writer.toString() + "\n"; } @@ -101,44 +100,11 @@ public class Determinizer { * @see GSON License * @see Original Source */ - private static final TypeAdapter JSON_ELEMENT = new TypeAdapter() { + private static final TypeAdapter ORDERED_JSON_WRITER = new TypeAdapter() { @Override - public JsonElement read(JsonReader in) throws IOException { - switch (in.peek()) { - case STRING: - return new JsonPrimitive(in.nextString()); - case NUMBER: - String number = in.nextString(); - return new JsonPrimitive(new LazilyParsedNumber(number)); - case BOOLEAN: - return new JsonPrimitive(in.nextBoolean()); - case NULL: - in.nextNull(); - return JsonNull.INSTANCE; - case BEGIN_ARRAY: - JsonArray array = new JsonArray(); - in.beginArray(); - while (in.hasNext()) { - array.add(read(in)); - } - in.endArray(); - return array; - case BEGIN_OBJECT: - JsonObject object = new JsonObject(); - in.beginObject(); - while (in.hasNext()) { - object.add(in.nextName(), read(in)); - } - in.endObject(); - return object; - case END_DOCUMENT: - case NAME: - case END_OBJECT: - case END_ARRAY: - default: - throw new IllegalArgumentException(); - } + public JsonElement read(JsonReader in) { + return null; } @Override From 6277c20e4c6c2c4c3010eb695877ef44b9195502 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 12 Oct 2018 22:15:54 -0500 Subject: [PATCH 150/305] funny number --- buildSrc/src/main/java/baritone/gradle/util/Determinizer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java index 21b2e50a..f08649d2 100644 --- a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java +++ b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java @@ -59,7 +59,7 @@ public class Determinizer { continue; } JarEntry clone = new JarEntry(entry.getName()); - clone.setTime(0); + clone.setTime(42069); jos.putNextEntry(clone); if (entry.getName().endsWith(".refmap.json")) { JsonObject object = new JsonParser().parse(new InputStreamReader(jarFile.getInputStream(entry))).getAsJsonObject(); From b6a1608e739e9ff10f6cee313cf3f81ec5b11d60 Mon Sep 17 00:00:00 2001 From: leijurv Date: Fri, 12 Oct 2018 21:19:11 -0700 Subject: [PATCH 151/305] some improvements --- .../baritone/gradle/task/CreateDistTask.java | 2 +- .../baritone/gradle/task/ProguardTask.java | 10 ++-- .../baritone/gradle/util/Determinizer.java | 58 +++++++++---------- 3 files changed, 33 insertions(+), 37 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index f0d3e547..1b8f1aa5 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -67,7 +67,7 @@ public class CreateDistTask extends BaritoneGradleTask { Files.write(getRelativeFile("dist/checksums.txt"), shasum); } - private static String sha1(Path path) { + private static synchronized String sha1(Path path) { try { if (SHA1_DIGEST == null) { SHA1_DIGEST = MessageDigest.getInstance("SHA-1"); diff --git a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java index ad0db8cc..06af0011 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java @@ -79,7 +79,7 @@ public class ProguardTask extends BaritoneGradleTask { Files.delete(this.artifactUnoptimizedPath); } - Determinizer.main(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString()); + Determinizer.determinize(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString()); } private void downloadProguard() throws Exception { @@ -197,12 +197,12 @@ public class ProguardTask extends BaritoneGradleTask { private void proguardApi() throws Exception { runProguard(getTemporaryFile(PROGUARD_API_CONFIG)); - Determinizer.main(this.proguardOut.toString(), this.artifactApiPath.toString()); + Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString()); } private void proguardStandalone() throws Exception { runProguard(getTemporaryFile(PROGUARD_STANDALONE_CONFIG)); - Determinizer.main(this.proguardOut.toString(), this.artifactStandalonePath.toString()); + Determinizer.determinize(this.proguardOut.toString(), this.artifactStandalonePath.toString()); } private void cleanup() { @@ -239,8 +239,8 @@ public class ProguardTask extends BaritoneGradleTask { this.printOutputLog(p.getErrorStream()); // Halt the current thread until the process is complete, if the exit code isn't 0, throw an exception - int exitCode; - if ((exitCode = p.waitFor()) != 0) { + int exitCode = p.waitFor(); + if (exitCode != 0) { throw new Exception("Proguard exited with code " + exitCode); } } diff --git a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java index f08649d2..d50c1e54 100644 --- a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java +++ b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java @@ -39,39 +39,39 @@ import java.util.stream.Collectors; */ public class Determinizer { - public static void main(String... args) throws IOException { + public static void determinize(String inputPath, String outputPath) throws IOException { System.out.println("Running Determinizer"); - System.out.println(" Input path: " + args[0]); - System.out.println(" Output path: " + args[1]); + System.out.println(" Input path: " + inputPath); + System.out.println(" Output path: " + outputPath); - JarFile jarFile = new JarFile(new File(args[0])); - JarOutputStream jos = new JarOutputStream(new FileOutputStream(new File(args[1]))); + try ( + JarFile jarFile = new JarFile(new File(inputPath)); + JarOutputStream jos = new JarOutputStream(new FileOutputStream(new File(outputPath))) + ) { - List entries = jarFile.stream() - .sorted(Comparator.comparing(JarEntry::getName)) - .collect(Collectors.toList()); + List entries = jarFile.stream() + .sorted(Comparator.comparing(JarEntry::getName)) + .collect(Collectors.toList()); - for (JarEntry entry : entries) { - if (entry.getName().equals("META-INF/fml_cache_annotation.json")) { - continue; - } - if (entry.getName().equals("META-INF/fml_cache_class_versions.json")) { - continue; - } - JarEntry clone = new JarEntry(entry.getName()); - clone.setTime(42069); - jos.putNextEntry(clone); - if (entry.getName().endsWith(".refmap.json")) { - JsonObject object = new JsonParser().parse(new InputStreamReader(jarFile.getInputStream(entry))).getAsJsonObject(); - copy(writeSorted(object), jos); - } else { - copy(jarFile.getInputStream(entry), jos); + for (JarEntry entry : entries) { + if (entry.getName().equals("META-INF/fml_cache_annotation.json")) { + continue; + } + if (entry.getName().equals("META-INF/fml_cache_class_versions.json")) { + continue; + } + JarEntry clone = new JarEntry(entry.getName()); + clone.setTime(42069); + jos.putNextEntry(clone); + if (entry.getName().endsWith(".refmap.json")) { + JsonObject object = new JsonParser().parse(new InputStreamReader(jarFile.getInputStream(entry))).getAsJsonObject(); + jos.write(writeSorted(object).getBytes()); + } else { + copy(jarFile.getInputStream(entry), jos); + } } + jos.finish(); } - - jos.finish(); - jos.close(); - jarFile.close(); } private static void copy(InputStream is, OutputStream os) throws IOException { @@ -82,10 +82,6 @@ public class Determinizer { } } - private static void copy(String s, OutputStream os) throws IOException { - os.write(s.getBytes()); - } - private static String writeSorted(JsonObject in) throws IOException { StringWriter writer = new StringWriter(); JsonWriter jw = new JsonWriter(writer); From 56b67cbc4712ec74c189601475dcddf8f42ab3f1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Oct 2018 21:21:51 -0700 Subject: [PATCH 152/305] no longer needed --- Dockerfile | 2 -- 1 file changed, 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index e4fdb406..321a902a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,8 +13,6 @@ RUN apt install --target-release jessie-backports \ RUN apt install -qq --force-yes mesa-utils libgl1-mesa-glx libxcursor1 libxrandr2 libxxf86vm1 x11-xserver-utils xfonts-base xserver-common -RUN apt install -qq --force-yes unzip wget jq zip - COPY . /code # this .deb is specially patched to support lwjgl From ab2fa0ba8830ae93465c754b610e2ddd8bd214f0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Oct 2018 21:36:41 -0700 Subject: [PATCH 153/305] update instructions for new build system --- IMPACT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/IMPACT.md b/IMPACT.md index a6ca56f2..75af738b 100644 --- a/IMPACT.md +++ b/IMPACT.md @@ -18,7 +18,7 @@ For Impact 4.3, there is no Baritone integration yet, so you will want `baritone Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. -The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone . && docker run --rm -it cabaletta/baritone sh scripts/build.sh` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). +The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone . && docker run --rm cabaletta/baritone cat /code/dist/checksums.txt` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). ### Building Baritone yourself There are a few steps to this From 9045791e7f53c8b0054a3f41a67670b9988a3d1c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 13 Oct 2018 12:28:20 -0700 Subject: [PATCH 154/305] cleanup --- .../src/main/java/baritone/gradle/task/CreateDistTask.java | 3 +-- buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index 1b8f1aa5..15e36314 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -23,7 +23,6 @@ import javax.xml.bind.DatatypeConverter; import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; -import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -39,7 +38,7 @@ public class CreateDistTask extends BaritoneGradleTask { private static MessageDigest SHA1_DIGEST; @TaskAction - private void exec() throws Exception { + protected void exec() throws Exception { super.verifyArtifacts(); // Define the distribution file paths diff --git a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java index 06af0011..ce0e3800 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java @@ -59,7 +59,7 @@ public class ProguardTask extends BaritoneGradleTask { private List requiredLibraries; @TaskAction - private void exec() throws Exception { + protected void exec() throws Exception { super.verifyArtifacts(); // "Haha brady why don't you make separate tasks" From de29a6532f84a1a41212d42e57518245cb7db15b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 13 Oct 2018 12:29:14 -0700 Subject: [PATCH 155/305] privatize --- .../java/baritone/utils/pathing/BetterWorldBorder.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/utils/pathing/BetterWorldBorder.java b/src/main/java/baritone/utils/pathing/BetterWorldBorder.java index c9ffe5bd..8a5c79d5 100644 --- a/src/main/java/baritone/utils/pathing/BetterWorldBorder.java +++ b/src/main/java/baritone/utils/pathing/BetterWorldBorder.java @@ -21,10 +21,10 @@ import baritone.utils.Helper; import net.minecraft.world.border.WorldBorder; public class BetterWorldBorder implements Helper { - double minX; - double maxX; - double minZ; - double maxZ; + private final double minX; + private final double maxX; + private final double minZ; + private final double maxZ; public BetterWorldBorder(WorldBorder border) { this.minX = border.minX(); From ba68990ef8cf1e04e4f8e5d73be3d477d83b4a6b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 13 Oct 2018 12:36:05 -0700 Subject: [PATCH 156/305] update codacy badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9565e468..64133d58 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Baritone [![Build Status](https://travis-ci.com/cabaletta/baritone.svg?branch=master)](https://travis-ci.com/cabaletta/baritone) [![License](https://img.shields.io/github/license/cabaletta/baritone.svg)](LICENSE) -[![Codacy Badge](https://api.codacy.com/project/badge/Grade/7150d8ccf6094057b1782aa7a8f92d7d)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) From 897483884a3397846b6348c14f2f695ce19e3fe0 Mon Sep 17 00:00:00 2001 From: leijurv Date: Sat, 13 Oct 2018 17:01:00 -0700 Subject: [PATCH 157/305] fix 2 block parkour failure on lilypads and after descends --- .../pathing/movement/movements/MovementParkour.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 23348990..3910fa62 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -223,6 +223,14 @@ public class MovementParkour extends Movement { } } } + if (dist == 3) { // this is a 2 block gap, dest = src + direction * 3 + double xDiff = (src.x + 0.5) - player().posX; + double zDiff = (src.z + 0.5) - player().posZ; + double distFromStart = Math.max(Math.abs(xDiff), Math.abs(zDiff)); + if (distFromStart < 0.7) { + return state; + } + } state.setInput(InputOverrideHandler.Input.JUMP, true); } else if (!playerFeet().equals(dest.offset(direction, -1))) { From ff652dbe40352811b7c969797549cd0dbc0557e2 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 13 Oct 2018 23:15:11 -0500 Subject: [PATCH 158/305] scanLoadedChunks -> scanChunkRadius --- src/api/java/baritone/api/cache/IWorldScanner.java | 2 +- src/main/java/baritone/cache/WorldScanner.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/cache/IWorldScanner.java b/src/api/java/baritone/api/cache/IWorldScanner.java index c35757ef..510e69ed 100644 --- a/src/api/java/baritone/api/cache/IWorldScanner.java +++ b/src/api/java/baritone/api/cache/IWorldScanner.java @@ -38,5 +38,5 @@ public interface IWorldScanner { * @param maxSearchRadius The maximum chunk search radius * @return The matching block positions */ - List scanLoadedChunks(List blocks, int max, int yLevelThreshold, int maxSearchRadius); + List scanChunkRadius(List blocks, int max, int yLevelThreshold, int maxSearchRadius); } diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index a0d905c6..6366b157 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -35,7 +35,7 @@ public enum WorldScanner implements IWorldScanner, Helper { INSTANCE; @Override - public List scanLoadedChunks(List blocks, int max, int yLevelThreshold, int maxSearchRadius) { + public List scanChunkRadius(List blocks, int max, int yLevelThreshold, int maxSearchRadius) { if (blocks.contains(null)) { throw new IllegalStateException("Invalid block name should have been caught earlier: " + blocks.toString()); } From b46fad1442db7e8cd080c644fb8f2534977f2d5d Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 13 Oct 2018 23:27:11 -0500 Subject: [PATCH 159/305] Fix bad reference --- src/main/java/baritone/behavior/MineBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index c67e9ae6..311203e8 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -153,7 +153,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe } if (!uninteresting.isEmpty()) { //long before = System.currentTimeMillis(); - locs.addAll(WorldScanner.INSTANCE.scanLoadedChunks(uninteresting, max, 10, 26)); + locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(uninteresting, max, 10, 26)); //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); } return prune(locs, mining, max); From 9654892e54a02de0cbe970a4f60f275d0e2bf9a1 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 14 Oct 2018 00:23:49 -0500 Subject: [PATCH 160/305] Make BlockStateInterface.AIR final --- src/main/java/baritone/utils/BlockStateInterface.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 068721cd..2c0384b2 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -38,7 +38,7 @@ public class BlockStateInterface implements Helper { private static Chunk prev = null; private static CachedRegion prevCached = null; - private static IBlockState AIR = Blocks.AIR.getDefaultState(); + private static final IBlockState AIR = Blocks.AIR.getDefaultState(); public static IBlockState get(BlockPos pos) { return get(pos.getX(), pos.getY(), pos.getZ()); From 83fc11e75b5b0ad6d1c27a70a01f43c7b2df5c68 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 14 Oct 2018 00:24:59 -0500 Subject: [PATCH 161/305] private static final > private final static --- src/api/java/baritone/api/BaritoneAPI.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index 29238ea7..0ffd1e98 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -36,8 +36,8 @@ import java.util.ServiceLoader; */ public final class BaritoneAPI { - private final static IBaritoneProvider baritone; - private final static Settings settings; + private static final IBaritoneProvider baritone; + private static final Settings settings; static { ServiceLoader baritoneLoader = ServiceLoader.load(IBaritoneProvider.class); From c80b855dab9384e77020c263adaad42e8b4c0198 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 14 Oct 2018 00:55:30 -0500 Subject: [PATCH 162/305] Move a lot of utils to api --- .../baritone/api}/utils/RayTraceUtils.java | 41 +++- .../baritone/api/utils/RotationUtils.java | 188 ++++++++++++++++++ .../java/baritone/api/utils/SettingsUtil.java | 1 + src/api/java/baritone/api/utils/VecUtils.java | 126 ++++++++++++ .../baritone/behavior/LookBehaviorUtils.java | 139 ------------- .../baritone/pathing/movement/Movement.java | 9 +- .../pathing/movement/MovementHelper.java | 24 +-- .../pathing/movement/MovementState.java | 3 - .../movement/movements/MovementAscend.java | 8 +- .../movement/movements/MovementFall.java | 9 +- .../movement/movements/MovementParkour.java | 7 +- .../movement/movements/MovementPillar.java | 11 +- .../movement/movements/MovementTraverse.java | 25 +-- .../baritone/pathing/path/PathExecutor.java | 5 +- .../utils/ExampleBaritoneControl.java | 3 +- src/main/java/baritone/utils/Utils.java | 133 ------------- 16 files changed, 393 insertions(+), 339 deletions(-) rename src/{main/java/baritone => api/java/baritone/api}/utils/RayTraceUtils.java (69%) create mode 100644 src/api/java/baritone/api/utils/VecUtils.java delete mode 100644 src/main/java/baritone/behavior/LookBehaviorUtils.java delete mode 100755 src/main/java/baritone/utils/Utils.java diff --git a/src/main/java/baritone/utils/RayTraceUtils.java b/src/api/java/baritone/api/utils/RayTraceUtils.java similarity index 69% rename from src/main/java/baritone/utils/RayTraceUtils.java rename to src/api/java/baritone/api/utils/RayTraceUtils.java index b313f1fe..6c35e816 100644 --- a/src/main/java/baritone/utils/RayTraceUtils.java +++ b/src/api/java/baritone/api/utils/RayTraceUtils.java @@ -15,22 +15,29 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.api.utils; -import baritone.api.utils.Rotation; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; -import static baritone.behavior.LookBehaviorUtils.calcVec3dFromRotation; +import java.util.Optional; /** * @author Brady * @since 8/25/2018 */ -public final class RayTraceUtils implements Helper { +public final class RayTraceUtils { private RayTraceUtils() {} + /** + * The {@link Minecraft} instance + */ + private static final Minecraft mc = Minecraft.getMinecraft(); + /** * Simulates a "vanilla" raytrace. A RayTraceResult returned by this method * will be that of the next render pass given that the local player's yaw and @@ -72,7 +79,7 @@ public final class RayTraceUtils implements Helper { public static RayTraceResult rayTraceTowards(Rotation rotation) { double blockReachDistance = mc.playerController.getBlockReachDistance(); Vec3d start = mc.player.getPositionEyes(1.0F); - Vec3d direction = calcVec3dFromRotation(rotation); + Vec3d direction = RotationUtils.calcVec3dFromRotation(rotation); Vec3d end = start.add( direction.x * blockReachDistance, direction.y * blockReachDistance, @@ -80,4 +87,28 @@ public final class RayTraceUtils implements Helper { ); return mc.world.rayTraceBlocks(start, end, false, false, true); } + + /** + * Returns the block that the crosshair is currently placed over. Updated once per render tick. + * + * @return The position of the highlighted block + */ + public static Optional getSelectedBlock() { + if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) { + return Optional.of(mc.objectMouseOver.getBlockPos()); + } + return Optional.empty(); + } + + /** + * Returns the entity that the crosshair is currently placed over. Updated once per render tick. + * + * @return The entity + */ + public static Optional getSelectedEntity() { + if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.ENTITY) { + return Optional.of(mc.objectMouseOver.entityHit); + } + return Optional.empty(); + } } diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index 0df4b38d..f31c3c4c 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -17,6 +17,14 @@ package baritone.api.utils; +import net.minecraft.block.BlockFire; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.util.math.*; + +import java.util.Optional; + /** * @author Brady * @since 9/25/2018 @@ -25,6 +33,33 @@ public final class RotationUtils { private RotationUtils() {} + /** + * The {@link Minecraft} instance + */ + private static final Minecraft mc = Minecraft.getMinecraft(); + + /** + * Constant that a degree value is multiplied by to get the equivalent radian value + */ + public static final double DEG_TO_RAD = Math.PI / 180.0; + + /** + * Constant that a radian value is multiplied by to get the equivalent degree value + */ + public static final double RAD_TO_DEG = 180.0 / Math.PI; + + /** + * Offsets from the root block position to the center of each side. + */ + private static final Vec3d[] BLOCK_SIDE_MULTIPLIERS = new Vec3d[]{ + new Vec3d(0.5, 0, 0.5), // Down + new Vec3d(0.5, 1, 0.5), // Up + new Vec3d(0.5, 0.5, 0), // North + new Vec3d(0.5, 0.5, 1), // South + new Vec3d(0, 0.5, 0.5), // West + new Vec3d(1, 0.5, 0.5) // East + }; + /** * Clamps the specified pitch value between -90 and 90. * @@ -51,4 +86,157 @@ public final class RotationUtils { } return newYaw; } + + /** + * Calculates the rotation from BlockPosdest to BlockPosorig + * + * @param orig The origin position + * @param dest The destination position + * @return The rotation from the origin to the destination + */ + public static Rotation calcRotationFromCoords(BlockPos orig, BlockPos dest) { + return calcRotationFromVec3d(new Vec3d(orig), new Vec3d(dest)); + } + + /** + * Wraps the target angles to a relative value from the current angles. This is done by + * subtracting the current from the target, normalizing it, and then adding the current + * angles back to it. + * + * @param current The current angles + * @param target The target angles + * @return The wrapped angles + */ + public static Rotation wrapAnglesToRelative(Rotation current, Rotation target) { + return target.subtract(current).normalize().add(current); + } + + /** + * Calculates the rotation from Vecdest to Vecorig and makes the + * return value relative to the specified current rotations. + * + * @see #wrapAnglesToRelative(Rotation, Rotation) + * + * @param orig The origin position + * @param dest The destination position + * @param current The current rotations + * @return The rotation from the origin to the destination + */ + public static Rotation calcRotationFromVec3d(Vec3d orig, Vec3d dest, Rotation current) { + return wrapAnglesToRelative(current, calcRotationFromVec3d(orig, dest)); + } + + /** + * Calculates the rotation from Vecdest to Vecorig + * + * @param orig The origin position + * @param dest The destination position + * @return The rotation from the origin to the destination + */ + 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 dist = Math.sqrt(delta[0] * delta[0] + delta[2] * delta[2]); + double pitch = MathHelper.atan2(delta[1], dist); + return new Rotation( + (float) (yaw * RAD_TO_DEG), + (float) (pitch * RAD_TO_DEG) + ); + } + + /** + * Calculates the look vector for the specified yaw/pitch rotations. + * + * @param rotation The input rotation + * @return Look vector for the rotation + */ + public static Vec3d calcVec3dFromRotation(Rotation rotation) { + float f = MathHelper.cos(-rotation.getYaw() * (float) DEG_TO_RAD - (float) Math.PI); + float f1 = MathHelper.sin(-rotation.getYaw() * (float) DEG_TO_RAD - (float) Math.PI); + float f2 = -MathHelper.cos(-rotation.getPitch() * (float) DEG_TO_RAD); + float f3 = MathHelper.sin(-rotation.getPitch() * (float) DEG_TO_RAD); + return new Vec3d((double) (f1 * f2), (double) f3, (double) (f * f2)); + } + + /** + * Determines if the specified entity is able to reach the center of any of the sides + * of the specified block. It first checks if the block center is reachable, and if so, + * that rotation will be returned. If not, it will return the first center of a given + * side that is reachable. The return type will be {@link Optional#empty()} if the entity is + * unable to reach any of the sides of the block. + * + * @param entity The viewing entity + * @param pos The target block position + * @return The optional rotation + */ + public static Optional reachable(Entity entity, BlockPos pos) { + if (pos.equals(RayTraceUtils.getSelectedBlock().orElse(null))) { + /* + * why add 0.0001? + * to indicate that we actually have a desired pitch + * the way we indicate that the pitch can be whatever and we only care about the yaw + * is by setting the desired pitch to the current pitch + * setting the desired pitch to the current pitch + 0.0001 means that we do have a desired pitch, it's + * just what it currently is + */ + return Optional.of(new Rotation(entity.rotationYaw, entity.rotationPitch + 0.0001F)); + } + Optional possibleRotation = reachableCenter(entity, pos); + //System.out.println("center: " + possibleRotation); + if (possibleRotation.isPresent()) { + return possibleRotation; + } + + IBlockState state = mc.world.getBlockState(pos); + AxisAlignedBB aabb = state.getBoundingBox(entity.world, pos); + for (Vec3d sideOffset : BLOCK_SIDE_MULTIPLIERS) { + double xDiff = aabb.minX * sideOffset.x + aabb.maxX * (1 - sideOffset.x); + double yDiff = aabb.minY * sideOffset.y + aabb.maxY * (1 - sideOffset.y); + double zDiff = aabb.minZ * sideOffset.z + aabb.maxZ * (1 - sideOffset.z); + possibleRotation = reachableOffset(entity, pos, new Vec3d(pos).add(xDiff, yDiff, zDiff)); + if (possibleRotation.isPresent()) { + return possibleRotation; + } + } + return Optional.empty(); + } + + /** + * Determines if the specified entity is able to reach the specified block with + * the given offsetted position. The return type will be {@link Optional#empty()} if + * the entity is unable to reach the block with the offset applied. + * + * @param entity The viewing entity + * @param pos The target block position + * @param offsetPos The position of the block with the offset applied. + * @return The optional rotation + */ + public static Optional reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos) { + Rotation rotation = calcRotationFromVec3d(entity.getPositionEyes(1.0F), offsetPos); + RayTraceResult result = RayTraceUtils.rayTraceTowards(rotation); + System.out.println(result); + if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { + if (result.getBlockPos().equals(pos)) { + return Optional.of(rotation); + } + if (entity.world.getBlockState(pos).getBlock() instanceof BlockFire) { + if (result.getBlockPos().equals(pos.down())) { + return Optional.of(rotation); + } + } + } + return Optional.empty(); + } + + /** + * Determines if the specified entity is able to reach the specified block where it is + * looking at the direct center of it's hitbox. + * + * @param entity The viewing entity + * @param pos The target block position + * @return The optional rotation + */ + public static Optional reachableCenter(Entity entity, BlockPos pos) { + return reachableOffset(entity, pos, VecUtils.calculateBlockCenter(pos)); + } } diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 3e11d8e5..4d13d027 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -31,6 +31,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; public class SettingsUtil { + private static final File settingsFile = new File(new File(Minecraft.getMinecraft().gameDir, "baritone"), "settings.txt"); private static final Map, SettingsIO> map; diff --git a/src/api/java/baritone/api/utils/VecUtils.java b/src/api/java/baritone/api/utils/VecUtils.java new file mode 100644 index 00000000..51279474 --- /dev/null +++ b/src/api/java/baritone/api/utils/VecUtils.java @@ -0,0 +1,126 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils; + +import net.minecraft.block.BlockFire; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; + +/** + * @author Brady + * @since 10/13/2018 + */ +public final class VecUtils { + + private VecUtils() {} + + /** + * The {@link Minecraft} instance + */ + private static final Minecraft mc = Minecraft.getMinecraft(); + + /** + * Calculates the center of the block at the specified position's bounding box + * + * @see #getBlockPosCenter(BlockPos) + * + * @param pos The block position + * @return The center of the block's bounding box + */ + public static Vec3d calculateBlockCenter(BlockPos pos) { + IBlockState b = mc.world.getBlockState(pos); + AxisAlignedBB bbox = b.getBoundingBox(mc.world, pos); + double xDiff = (bbox.minX + bbox.maxX) / 2; + double yDiff = (bbox.minY + bbox.maxY) / 2; + double zDiff = (bbox.minZ + bbox.maxZ) / 2; + if (b.getBlock() instanceof BlockFire) {//look at bottom of fire when putting it out + yDiff = 0; + } + return new Vec3d( + pos.getX() + xDiff, + pos.getY() + yDiff, + pos.getZ() + zDiff + ); + } + + /** + * Gets the assumed center position of the given block position. + * This is done by adding 0.5 to the X, Y, and Z axes. + *

+ * TODO: We may want to consider replacing many usages of this method with #calculateBlockCenter(BlockPos) + * + * @see #calculateBlockCenter(BlockPos) + * + * @param pos The block position + * @return The assumed center of the position + */ + public static Vec3d getBlockPosCenter(BlockPos pos) { + return new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); + } + + /** + * Gets the distance from the specified position to the assumed center of the specified block position. + * + * @see #getBlockPosCenter(BlockPos) + * + * @param pos The block position + * @param x The x pos + * @param y The y pos + * @param z The z pos + * @return The distance from the assumed block center to the position + */ + public static double distanceToCenter(BlockPos pos, double x, double y, double z) { + Vec3d center = getBlockPosCenter(pos); + double xdiff = x - center.x; + double ydiff = y - center.y; + double zdiff = z - center.z; + return Math.sqrt(xdiff * xdiff + ydiff * ydiff + zdiff * zdiff); + } + + /** + * Gets the distance from the specified entity's position to the assumed + * center of the specified block position. + * + * @see #getBlockPosCenter(BlockPos) + * + * @param entity The entity + * @param pos The block position + * @return The distance from the entity to the block's assumed center + */ + public static double entityDistanceToCenter(Entity entity, BlockPos pos) { + return distanceToCenter(pos, entity.posX, entity.posY, entity.posZ); + } + + /** + * Gets the distance from the specified entity's position to the assumed + * center of the specified block position, ignoring the Y axis. + * + * @see #getBlockPosCenter(BlockPos) + * + * @param entity The entity + * @param pos The block position + * @return The horizontal distance from the entity to the block's assumed center + */ + public static double entityFlatDistanceToCenter(Entity entity, BlockPos pos) { + return distanceToCenter(pos, entity.posX, pos.getY() + 0.5, entity.posZ); + } +} diff --git a/src/main/java/baritone/behavior/LookBehaviorUtils.java b/src/main/java/baritone/behavior/LookBehaviorUtils.java deleted file mode 100644 index 8cbe01ab..00000000 --- a/src/main/java/baritone/behavior/LookBehaviorUtils.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.behavior; - -import baritone.api.utils.Rotation; -import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; -import baritone.utils.RayTraceUtils; -import baritone.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; - -public final class LookBehaviorUtils implements Helper { - - /** - * Offsets from the root block position to the center of each side. - */ - private static final Vec3d[] BLOCK_SIDE_MULTIPLIERS = new Vec3d[]{ - new Vec3d(0.5, 0, 0.5), // Down - new Vec3d(0.5, 1, 0.5), // Up - new Vec3d(0.5, 0.5, 0), // North - new Vec3d(0.5, 0.5, 1), // South - new Vec3d(0, 0.5, 0.5), // West - new Vec3d(1, 0.5, 0.5) // East - }; - - /** - * Calculates a vector given a rotation array - * - * @param rotation {@link LookBehavior#target} - * @return vector of the rotation - */ - public static Vec3d calcVec3dFromRotation(Rotation rotation) { - float f = MathHelper.cos(-rotation.getYaw() * (float) DEG_TO_RAD - (float) Math.PI); - float f1 = MathHelper.sin(-rotation.getYaw() * (float) DEG_TO_RAD - (float) Math.PI); - float f2 = -MathHelper.cos(-rotation.getPitch() * (float) DEG_TO_RAD); - float f3 = MathHelper.sin(-rotation.getPitch() * (float) DEG_TO_RAD); - return new Vec3d((double) (f1 * f2), (double) f3, (double) (f * f2)); - } - - public static Optional reachable(BlockPos pos) { - if (pos.equals(getSelectedBlock().orElse(null))) { - /* - * why add 0.0001? - * to indicate that we actually have a desired pitch - * the way we indicate that the pitch can be whatever and we only care about the yaw - * is by setting the desired pitch to the current pitch - * setting the desired pitch to the current pitch + 0.0001 means that we do have a desired pitch, it's - * just what it currently is - */ - return Optional.of(new Rotation(mc.player.rotationYaw, mc.player.rotationPitch + 0.0001f)); - } - Optional possibleRotation = reachableCenter(pos); - //System.out.println("center: " + possibleRotation); - if (possibleRotation.isPresent()) { - return possibleRotation; - } - - IBlockState state = BlockStateInterface.get(pos); - AxisAlignedBB aabb = state.getBoundingBox(mc.world, pos); - for (Vec3d sideOffset : BLOCK_SIDE_MULTIPLIERS) { - double xDiff = aabb.minX * sideOffset.x + aabb.maxX * (1 - sideOffset.x); - 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()) { - return possibleRotation; - } - } - return Optional.empty(); - } - - /** - * Checks if coordinate is reachable with the given block-face rotation offset - * - * @param pos - * @param offsetPos - * @return - */ - protected static Optional reachableOffset(BlockPos pos, Vec3d offsetPos) { - Rotation rotation = Utils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F), offsetPos); - RayTraceResult result = RayTraceUtils.rayTraceTowards(rotation); - System.out.println(result); - if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { - if (result.getBlockPos().equals(pos)) { - return Optional.of(rotation); - } - if (BlockStateInterface.get(pos).getBlock() instanceof BlockFire) { - if (result.getBlockPos().equals(pos.down())) { - return Optional.of(rotation); - } - } - } - return Optional.empty(); - } - - /** - * Checks if center of block at coordinate is reachable - * - * @param pos - * @return - */ - protected static Optional reachableCenter(BlockPos pos) { - return reachableOffset(pos, Utils.calcCenterFromCoords(pos, mc.world)); - } - - /** - * The currently highlighted block. - * Updated once a tick by Minecraft. - * - * @return the position of the highlighted block - */ - public static Optional getSelectedBlock() { - if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) { - return Optional.of(mc.objectMouseOver.getBlockPos()); - } - return Optional.empty(); - } -} diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 4b537ac5..3e8519ff 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -22,8 +22,9 @@ import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; +import baritone.api.utils.RotationUtils; +import baritone.api.utils.VecUtils; import baritone.behavior.LookBehavior; -import baritone.behavior.LookBehaviorUtils; import baritone.utils.*; import net.minecraft.block.BlockLiquid; import net.minecraft.util.EnumFacing; @@ -171,7 +172,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { for (BetterBlockPos blockPos : positionsToBreak) { if (!MovementHelper.canWalkThrough(blockPos) && !(BlockStateInterface.getBlock(blockPos) instanceof BlockLiquid)) { // can't break liquid, so don't try somethingInTheWay = true; - Optional reachable = LookBehaviorUtils.reachable(blockPos); + Optional reachable = RotationUtils.reachable(player(), blockPos); if (reachable.isPresent()) { MovementHelper.switchToBestToolFor(BlockStateInterface.get(blockPos)); state.setTarget(new MovementState.MovementTarget(reachable.get(), true)).setInput(Input.CLICK_LEFT, true); @@ -181,8 +182,8 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { //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) + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(player().getPositionEyes(1.0F), + VecUtils.getBlockPosCenter(blockPos)), true) ).setInput(InputOverrideHandler.Input.CLICK_LEFT, true); return false; } diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 9fd7d994..200f8910 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -19,9 +19,7 @@ package baritone.pathing.movement; import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.Rotation; -import baritone.behavior.LookBehaviorUtils; +import baritone.api.utils.*; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.*; import net.minecraft.block.*; @@ -29,14 +27,12 @@ import net.minecraft.block.properties.PropertyBool; 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.ItemPickaxe; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.chunk.EmptyChunk; import java.util.Optional; @@ -374,23 +370,11 @@ public interface MovementHelper extends ActionCosts, Helper { return isBottomSlab(BlockStateInterface.get(pos)); } - /** - * The entity the player is currently looking at - * - * @return the entity object - */ - static Optional 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 -> { + RayTraceUtils.getSelectedBlock().ifPresent(pos -> { IBlockState state = BlockStateInterface.get(pos); if (state.getBlock().equals(Blocks.AIR)) { return; @@ -456,8 +440,8 @@ public interface MovementHelper extends ActionCosts, Helper { 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(RotationUtils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F), + VecUtils.getBlockPosCenter(pos), new Rotation(mc.player.rotationYaw, mc.player.rotationPitch)).getYaw(), mc.player.rotationPitch), false )).setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); diff --git a/src/main/java/baritone/pathing/movement/MovementState.java b/src/main/java/baritone/pathing/movement/MovementState.java index db99ce5d..8b1b0e0d 100644 --- a/src/main/java/baritone/pathing/movement/MovementState.java +++ b/src/main/java/baritone/pathing/movement/MovementState.java @@ -84,9 +84,6 @@ public class MovementState { /** * Yaw and pitch angles that must be matched - *

- * getFirst() -> YAW - * getSecond() -> PITCH */ public Rotation rotation; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 09271779..b293a17b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -20,14 +20,14 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.behavior.LookBehaviorUtils; +import baritone.api.utils.RayTraceUtils; +import baritone.api.utils.RotationUtils; 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.block.BlockFalling; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -181,10 +181,10 @@ public class MovementAscend extends Movement { 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()), true)); + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true)); EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; - LookBehaviorUtils.getSelectedBlock().ifPresent(selectedBlock -> { + RayTraceUtils.getSelectedBlock().ifPresent(selectedBlock -> { if (Objects.equals(selectedBlock, anAgainst) && selectedBlock.offset(side).equals(positionToPlace)) { ticksWithoutPlacement++; state.setInput(InputOverrideHandler.Input.SNEAK, true); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index a761a242..f7d63f17 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -19,8 +19,7 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.pathing.movement.MovementStatus; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.Rotation; +import baritone.api.utils.*; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; @@ -28,8 +27,6 @@ import baritone.pathing.movement.MovementState; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; -import baritone.utils.RayTraceUtils; -import baritone.utils.Utils; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; @@ -85,7 +82,7 @@ public class MovementFall extends Movement { if (targetRotation != null) { state.setTarget(new MovementTarget(targetRotation, true)); } else { - state.setTarget(new MovementTarget(Utils.calcRotationFromVec3d(playerHead(), Utils.getBlockPosCenter(dest)), false)); + state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.getBlockPosCenter(dest)), false)); } if (playerFeet.equals(dest) && (player().posY - playerFeet.getY() < 0.094 || BlockStateInterface.isWater(dest))) { // 0.094 because lilypads if (BlockStateInterface.isWater(dest)) { @@ -105,7 +102,7 @@ public class MovementFall extends Movement { return state.setStatus(MovementStatus.SUCCESS); } } - Vec3d destCenter = Utils.getBlockPosCenter(dest); // we are moving to the 0.5 center not the edge (like if we were falling on a ladder) + Vec3d destCenter = VecUtils.getBlockPosCenter(dest); // we are moving to the 0.5 center not the edge (like if we were falling on a ladder) if (Math.abs(player().posX - destCenter.x) > 0.15 || Math.abs(player().posZ - destCenter.z) > 0.15) { state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 3910fa62..50a59145 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -20,8 +20,9 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.RayTraceUtils; import baritone.api.utils.Rotation; -import baritone.behavior.LookBehaviorUtils; +import baritone.api.utils.RotationUtils; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; @@ -209,12 +210,12 @@ public class MovementParkour extends Movement { 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; - Rotation place = Utils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()); + Rotation place = RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()); RayTraceResult res = RayTraceUtils.rayTraceTowards(place); if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(dest.down())) { state.setTarget(new MovementState.MovementTarget(place, true)); } - LookBehaviorUtils.getSelectedBlock().ifPresent(selectedBlock -> { + RayTraceUtils.getSelectedBlock().ifPresent(selectedBlock -> { EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; if (Objects.equals(selectedBlock, against1) && selectedBlock.offset(side).equals(dest.down())) { state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 799a4e9b..480f6659 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -20,13 +20,14 @@ package baritone.pathing.movement.movements; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; +import baritone.api.utils.RotationUtils; +import baritone.api.utils.VecUtils; 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.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -149,8 +150,8 @@ public class MovementPillar extends Movement { IBlockState fromDown = BlockStateInterface.get(src); if (BlockStateInterface.isWater(fromDown.getBlock()) && BlockStateInterface.isWater(dest)) { // stay centered while swimming up a water column - state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), Utils.getBlockPosCenter(dest)), false)); - Vec3d destCenter = Utils.getBlockPosCenter(dest); + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.getBlockPosCenter(dest)), false)); + Vec3d destCenter = VecUtils.getBlockPosCenter(dest); if (Math.abs(player().posX - destCenter.x) > 0.2 || Math.abs(player().posZ - destCenter.z) > 0.2) { state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); } @@ -162,8 +163,8 @@ public class MovementPillar extends Movement { 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), + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F), + VecUtils.getBlockPosCenter(positionToPlace), new Rotation(mc.player.rotationYaw, mc.player.rotationPitch)), true)); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 367d2c17..2dabd4d7 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -19,16 +19,13 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.pathing.movement.MovementStatus; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.Rotation; -import baritone.behavior.LookBehaviorUtils; +import baritone.api.utils.*; 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.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -169,7 +166,7 @@ public class MovementTraverse extends Movement { // combine the yaw to the center of the destination, and the pitch to the specific block we're trying to break // it's safe to do this since the two blocks we break (in a traverse) are right on top of each other and so will have the same yaw - float yawToDest = Utils.calcRotationFromVec3d(playerHead(), Utils.calcCenterFromCoords(dest, world())).getYaw(); + float yawToDest = RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(dest)).getYaw(); float pitchToBreak = state.getTarget().getRotation().get().getPitch(); state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true)); @@ -194,7 +191,7 @@ public class MovementTraverse extends Movement { } if (isDoorActuallyBlockingUs) { if (!(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { - return state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), Utils.calcCenterFromCoords(positionsToBreak[0], world())), true)) + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(positionsToBreak[0])), true)) .setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } } @@ -209,7 +206,7 @@ public class MovementTraverse extends Movement { } if (blocked != null) { - return state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), Utils.calcCenterFromCoords(blocked, world())), true)) + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(blocked)), true)) .setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } } @@ -267,16 +264,16 @@ public class MovementTraverse extends Movement { 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(RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true)); EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; - if (Objects.equals(LookBehaviorUtils.getSelectedBlock().orElse(null), against1) && (Minecraft.getMinecraft().player.isSneaking() || Baritone.settings().assumeSafeWalk.get())) { - if (LookBehaviorUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { + if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (Minecraft.getMinecraft().player.isSneaking() || Baritone.settings().assumeSafeWalk.get())) { + if (RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } // wrong side? } - System.out.println("Trying to look at " + against1 + ", actually looking at" + LookBehaviorUtils.getSelectedBlock()); + System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); } } @@ -296,18 +293,18 @@ public class MovementTraverse extends Movement { // 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 - Rotation backToFace = Utils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()); + Rotation backToFace = RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()); float pitch = backToFace.getPitch(); double dist = Math.max(Math.abs(player().posX - faceX), Math.abs(player().posZ - faceZ)); if (dist < 0.29) { - float yaw = Utils.calcRotationFromVec3d(Utils.getBlockPosCenter(dest), playerHead(), playerRotations()).getYaw(); + float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), playerHead(), playerRotations()).getYaw(); state.setTarget(new MovementState.MovementTarget(new Rotation(yaw, pitch), true)); state.setInput(InputOverrideHandler.Input.MOVE_BACK, true); } else { state.setTarget(new MovementState.MovementTarget(backToFace, true)); } state.setInput(InputOverrideHandler.Input.SNEAK, true); - if (Objects.equals(LookBehaviorUtils.getSelectedBlock().orElse(null), goalLook)) { + if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), goalLook)) { return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); // wait to right click until we are able to place } // Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt()); diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 5cc2c1dd..d4fa8df2 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -25,6 +25,7 @@ import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; import baritone.api.pathing.path.IPathExecutor; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.VecUtils; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; @@ -279,7 +280,7 @@ public class PathExecutor implements IPathExecutor, Helper { double best = -1; BlockPos bestPos = null; for (BlockPos pos : path.positions()) { - double dist = Utils.playerDistanceToCenter(pos); + double dist = VecUtils.entityDistanceToCenter(player(), pos); if (dist < best || best == -1) { best = dist; bestPos = pos; @@ -327,7 +328,7 @@ public class PathExecutor implements IPathExecutor, Helper { // when we're midair in the middle of a fall, we're very far from both the beginning and the end, but we aren't actually off path if (path.movements().get(pathPosition) instanceof MovementFall) { BlockPos fallDest = path.positions().get(pathPosition + 1); // .get(pathPosition) is the block we fell off of - if (Utils.playerFlatDistanceToCenter(fallDest) < leniency) { // ignore Y by using flat distance + if (VecUtils.entityFlatDistanceToCenter(player(), fallDest) < leniency) { // ignore Y by using flat distance return false; } return true; diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 5f532b46..0be20f00 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -23,6 +23,7 @@ import baritone.api.cache.IWaypoint; import baritone.api.event.events.ChatEvent; import baritone.api.pathing.goals.*; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.utils.RayTraceUtils; import baritone.api.utils.SettingsUtil; import baritone.behavior.Behavior; import baritone.behavior.FollowBehavior; @@ -255,7 +256,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { String name = msg.substring(6).trim(); Optional toFollow = Optional.empty(); if (name.length() == 0) { - toFollow = MovementHelper.whatEntityAmILookingAt(); + toFollow = RayTraceUtils.getSelectedEntity(); } else { for (EntityPlayer pl : world().playerEntities) { String theirName = pl.getName().trim().toLowerCase(); diff --git a/src/main/java/baritone/utils/Utils.java b/src/main/java/baritone/utils/Utils.java deleted file mode 100755 index a17aa577..00000000 --- a/src/main/java/baritone/utils/Utils.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.utils; - -import baritone.api.utils.Rotation; -import net.minecraft.block.BlockFire; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; - -import static baritone.utils.Helper.HELPER; - -/** - * @author Brady - * @since 8/1/2018 12:56 AM - */ -public final class Utils { - - /** - * Constant that a degree value is multiplied by to get the equivalent radian value - */ - public static final double DEG_TO_RAD = Math.PI / 180.0; - - /** - * Constant that a radian value is multiplied by to get the equivalent degree value - */ - public static final double RAD_TO_DEG = 180.0 / Math.PI; - - public static Rotation calcRotationFromCoords(BlockPos orig, BlockPos dest) { - return calcRotationFromVec3d(vec3dFromBlockPos(orig), vec3dFromBlockPos(dest)); - } - - /** - * Calculates rotation to given Vecdest from Vecorig - * - * @param orig - * @param dest - * @return Rotation {@link Rotation} - */ - 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 dist = Math.sqrt(delta[0] * delta[0] + delta[2] * delta[2]); - double pitch = MathHelper.atan2(delta[1], dist); - return new Rotation( - (float) radToDeg(yaw), - (float) radToDeg(pitch) - ); - } - - /** - * Calculates rotation to given Vecdest from Vecorig - * - * @param orig - * @param dest - * @return Rotation {@link Rotation} - */ - public static Rotation calcRotationFromVec3d(Vec3d orig, Vec3d dest, Rotation current) { - return wrapAnglesToRelative(current, calcRotationFromVec3d(orig, dest)); - } - - public static Vec3d calcCenterFromCoords(BlockPos orig, World world) { - IBlockState b = BlockStateInterface.get(orig); - AxisAlignedBB bbox = b.getBoundingBox(world, orig); - double xDiff = (bbox.minX + bbox.maxX) / 2; - double yDiff = (bbox.minY + bbox.maxY) / 2; - double zDiff = (bbox.minZ + bbox.maxZ) / 2; - if (b.getBlock() instanceof BlockFire) {//look at bottom of fire when putting it out - yDiff = 0; - } - return new Vec3d( - orig.getX() + xDiff, - orig.getY() + yDiff, - orig.getZ() + zDiff - ); - } - - public static Vec3d getBlockPosCenter(BlockPos pos) { - return new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); - } - - public static Rotation wrapAnglesToRelative(Rotation current, Rotation target) { - return target.subtract(current).normalize().add(current); - } - - public static Vec3d vec3dFromBlockPos(BlockPos orig) { - return new Vec3d(orig.getX() + 0.0D, orig.getY() + 0.0D, orig.getZ() + 0.0D); - } - - public static double distanceToCenter(BlockPos pos, double x, double y, double z) { - double xdiff = x - (pos.getX() + 0.5D); - double ydiff = y - (pos.getY() + 0.5D); - double zdiff = z - (pos.getZ() + 0.5D); - return Math.sqrt(xdiff * xdiff + ydiff * ydiff + zdiff * zdiff); - } - - public static double playerDistanceToCenter(BlockPos pos) { - EntityPlayerSP player = HELPER.player(); - return distanceToCenter(pos, player.posX, player.posY, player.posZ); - } - - public static double playerFlatDistanceToCenter(BlockPos pos) { - EntityPlayerSP player = HELPER.player(); - return distanceToCenter(pos, player.posX, pos.getY() + 0.5, player.posZ); - } - - public static double degToRad(double deg) { - return deg * DEG_TO_RAD; - } - - public static double radToDeg(double rad) { - return rad * RAD_TO_DEG; - } -} From 6fdf845349c65e3335601532f71b554513474d14 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 14 Oct 2018 10:27:50 -0700 Subject: [PATCH 163/305] v0.0.9 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 34020ece..16a9d3eb 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '0.0.8' +version '0.0.9' buildscript { repositories { From c1076461e2ae8bcabead2739e198c053beb50435 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 14 Oct 2018 10:38:47 -0700 Subject: [PATCH 164/305] dont jump while using an item, fixes #222 --- .../pathing/movement/movements/MovementParkour.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 50a59145..38028dcf 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -27,7 +27,9 @@ import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; -import baritone.utils.*; +import baritone.utils.BlockStateInterface; +import baritone.utils.Helper; +import baritone.utils.InputOverrideHandler; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -179,6 +181,10 @@ public class MovementParkour extends Movement { if (state.getStatus() != MovementStatus.RUNNING) { return state; } + if (player().isHandActive()) { + logDebug("Pausing parkour since hand is active"); + return state; + } if (dist >= 4) { state.setInput(InputOverrideHandler.Input.SPRINT, true); } From 2f7259714ac218fac9bb06567b92d97d5da7e6e6 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 14 Oct 2018 23:46:41 -0500 Subject: [PATCH 165/305] Fix Pathing Thread crash on Forge --- src/main/java/baritone/pathing/movement/MovementHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 200f8910..08d6f916 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -179,7 +179,7 @@ public interface MovementHelper extends ActionCosts, Helper { BlockDoublePlant.EnumPlantType kek = state.getValue(BlockDoublePlant.VARIANT); return kek == BlockDoublePlant.EnumPlantType.FERN || kek == BlockDoublePlant.EnumPlantType.GRASS; } - return state.getBlock().isReplaceable(null, null); + return state.getMaterial().isReplaceable(); } static boolean isDoorPassable(BlockPos doorPos, BlockPos playerPos) { From 3cac37d1a5c87f83257d4c7c5086ffc841ee9bec Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Oct 2018 15:19:10 -0700 Subject: [PATCH 166/305] cached regions in ram should not expand without bound --- .../java/baritone/cache/CachedRegion.java | 15 +++++++ src/main/java/baritone/cache/CachedWorld.java | 42 +++++++++++++++++++ .../pathing/movement/MovementHelper.java | 7 ++-- 3 files changed, 61 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/cache/CachedRegion.java b/src/main/java/baritone/cache/CachedRegion.java index 200e0f16..c25139ac 100644 --- a/src/main/java/baritone/cache/CachedRegion.java +++ b/src/main/java/baritone/cache/CachedRegion.java @@ -319,6 +319,21 @@ public final class CachedRegion implements ICachedRegion { } } + public synchronized final CachedChunk mostRecentlyModified() { + CachedChunk recent = null; + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + if (this.chunks[x][z] == null) { + continue; + } + if (recent == null || this.chunks[x][z].cacheTimestamp > recent.cacheTimestamp) { + recent = this.chunks[x][z]; + } + } + } + return recent; + } + /** * @return The region x coordinate */ diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index cb05360b..60126fca 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -147,6 +147,7 @@ public final class CachedWorld implements ICachedWorld, Helper { region.removeExpired(); } }); // even if we aren't saving to disk, still delete expired old chunks from RAM + prune(); return; } long start = System.nanoTime() / 1000000L; @@ -157,6 +158,47 @@ public final class CachedWorld implements ICachedWorld, Helper { }); long now = System.nanoTime() / 1000000L; System.out.println("World save took " + (now - start) + "ms"); + prune(); + } + + /** + * Delete regions that are too far from the player + */ + private synchronized void prune() { + BlockPos pruneCenter = guessPosition(); + for (CachedRegion region : allRegions()) { + int distX = (region.getX() * 512 + 256) - pruneCenter.getX(); + int distZ = (region.getZ() * 512 + 256) - pruneCenter.getZ(); + double dist = Math.sqrt(distX * distX + distZ * distZ); + if (dist > 1024) { + logDebug("Deleting cached region " + region.getX() + "," + region.getZ() + " from ram"); + cachedRegions.remove(getRegionID(region.getX(), region.getZ())); + } + } + } + + /** + * If we are still in this world and dimension, return player feet, otherwise return most recently modified chunk + */ + private BlockPos guessPosition() { + WorldData data = WorldProvider.INSTANCE.getCurrentWorld(); + if (data != null && data.getCachedWorld() == this) { + return playerFeet(); + } + CachedChunk mostRecentlyModified = null; + for (CachedRegion region : allRegions()) { + CachedChunk ch = region.mostRecentlyModified(); + if (ch == null) { + continue; + } + if (mostRecentlyModified == null || mostRecentlyModified.cacheTimestamp < ch.cacheTimestamp) { + mostRecentlyModified = ch; + } + } + if (mostRecentlyModified == null) { + return new BlockPos(0, 0, 0); + } + return new BlockPos(mostRecentlyModified.x * 16 + 8, 0, mostRecentlyModified.z * 16 + 8); } private synchronized List allRegions() { diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 08d6f916..c2e3450c 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -21,7 +21,10 @@ import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; import baritone.api.utils.*; import baritone.pathing.movement.MovementState.MovementTarget; -import baritone.utils.*; +import baritone.utils.BlockStateInterface; +import baritone.utils.Helper; +import baritone.utils.InputOverrideHandler; +import baritone.utils.ToolSet; import net.minecraft.block.*; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.IBlockState; @@ -35,8 +38,6 @@ import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; -import java.util.Optional; - /** * Static helpers for cost calculation * From b41fdc2bbd26108aee3fd45c51f13f6f7f2050b0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Oct 2018 15:39:01 -0700 Subject: [PATCH 167/305] remove spammy log prints --- .../baritone/api/utils/RotationUtils.java | 21 +++++++++---------- .../movement/movements/MovementAscend.java | 2 +- .../movement/movements/MovementDescend.java | 6 +++--- .../movement/movements/MovementTraverse.java | 2 +- .../baritone/pathing/path/PathExecutor.java | 7 +++++-- src/main/java/baritone/utils/Helper.java | 4 ++-- 6 files changed, 22 insertions(+), 20 deletions(-) diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index f31c3c4c..fc1b0297 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -104,7 +104,7 @@ public final class RotationUtils { * angles back to it. * * @param current The current angles - * @param target The target angles + * @param target The target angles * @return The wrapped angles */ public static Rotation wrapAnglesToRelative(Rotation current, Rotation target) { @@ -115,12 +115,11 @@ public final class RotationUtils { * Calculates the rotation from Vecdest to Vecorig and makes the * return value relative to the specified current rotations. * - * @see #wrapAnglesToRelative(Rotation, Rotation) - * - * @param orig The origin position - * @param dest The destination position + * @param orig The origin position + * @param dest The destination position * @param current The current rotations * @return The rotation from the origin to the destination + * @see #wrapAnglesToRelative(Rotation, Rotation) */ public static Rotation calcRotationFromVec3d(Vec3d orig, Vec3d dest, Rotation current) { return wrapAnglesToRelative(current, calcRotationFromVec3d(orig, dest)); @@ -134,7 +133,7 @@ public final class RotationUtils { * @return The rotation from the origin to the destination */ public static Rotation calcRotationFromVec3d(Vec3d orig, Vec3d dest) { - double[] delta = { orig.x - dest.x, orig.y - dest.y, orig.z - dest.z }; + double[] delta = {orig.x - dest.x, orig.y - dest.y, orig.z - dest.z}; double yaw = MathHelper.atan2(delta[0], -delta[2]); double dist = Math.sqrt(delta[0] * delta[0] + delta[2] * delta[2]); double pitch = MathHelper.atan2(delta[1], dist); @@ -166,7 +165,7 @@ public final class RotationUtils { * unable to reach any of the sides of the block. * * @param entity The viewing entity - * @param pos The target block position + * @param pos The target block position * @return The optional rotation */ public static Optional reachable(Entity entity, BlockPos pos) { @@ -206,15 +205,15 @@ public final class RotationUtils { * the given offsetted position. The return type will be {@link Optional#empty()} if * the entity is unable to reach the block with the offset applied. * - * @param entity The viewing entity - * @param pos The target block position + * @param entity The viewing entity + * @param pos The target block position * @param offsetPos The position of the block with the offset applied. * @return The optional rotation */ public static Optional reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos) { Rotation rotation = calcRotationFromVec3d(entity.getPositionEyes(1.0F), offsetPos); RayTraceResult result = RayTraceUtils.rayTraceTowards(rotation); - System.out.println(result); + //System.out.println(result); if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { if (result.getBlockPos().equals(pos)) { return Optional.of(rotation); @@ -233,7 +232,7 @@ public final class RotationUtils { * looking at the direct center of it's hitbox. * * @param entity The viewing entity - * @param pos The target block position + * @param pos The target block position * @return The optional rotation */ public static Optional reachableCenter(Entity entity, BlockPos pos) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index b293a17b..52b0c78e 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -198,7 +198,7 @@ public class MovementAscend extends Movement { } else { state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); // break whatever replaceable block is in the way } - System.out.println("Trying to look at " + anAgainst + ", actually looking at" + selectedBlock); + //System.out.println("Trying to look at " + anAgainst + ", actually looking at" + selectedBlock); }); return state; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index ba3deb7d..d2e3d306 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -187,9 +187,9 @@ public class MovementDescend extends Movement { if (BlockStateInterface.isLiquid(dest) || player().posY - playerFeet.getY() < 0.094) { // lilypads // Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately return state.setStatus(MovementStatus.SUCCESS); - } else { - System.out.println(player().posY + " " + playerFeet.getY() + " " + (player().posY - playerFeet.getY())); - } + }/* else { + // System.out.println(player().posY + " " + playerFeet.getY() + " " + (player().posY - playerFeet.getY())); + }*/ } double diffX = player().posX - (dest.getX() + 0.5); double diffZ = player().posZ - (dest.getZ() + 0.5); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 2dabd4d7..a71be415 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -273,7 +273,7 @@ public class MovementTraverse extends Movement { } // wrong side? } - System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); + //System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); } } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index d4fa8df2..4acecbdc 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -30,7 +30,10 @@ import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.movements.*; -import baritone.utils.*; +import baritone.utils.BlockBreakHelper; +import baritone.utils.BlockStateInterface; +import baritone.utils.Helper; +import baritone.utils.InputOverrideHandler; import net.minecraft.init.Blocks; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; @@ -123,7 +126,7 @@ public class PathExecutor implements IPathExecutor, Helper { if (i - pathPosition > 2) { logDebug("Skipping forward " + (i - pathPosition) + " steps, to " + i); } - System.out.println("Double skip sundae"); + //System.out.println("Double skip sundae"); pathPosition = i - 1; onChangeInPathPosition(); return false; diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index f026ec38..2a34ecc0 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -86,8 +86,8 @@ public interface Helper { */ default void logDebug(String message) { if (!Baritone.settings().chatDebug.get()) { - System.out.println("Suppressed debug message:"); - System.out.println(message); + //System.out.println("Suppressed debug message:"); + //System.out.println(message); return; } logDirect(message); From 6b6ebd696854c8d0c40afaa9a45e82dac31f3a6f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Oct 2018 15:44:43 -0700 Subject: [PATCH 168/305] optimize all imports --- src/api/java/baritone/api/behavior/IPathingBehavior.java | 2 +- .../java/baritone/pathing/calc/AbstractNodeCostSearch.java | 2 +- src/main/java/baritone/pathing/calc/CutoffPath.java | 2 +- src/main/java/baritone/pathing/calc/Path.java | 2 +- src/main/java/baritone/pathing/movement/Movement.java | 5 ++++- src/main/java/baritone/utils/ExampleBaritoneControl.java | 1 - 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index cfc93d2d..7d88ae59 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -17,9 +17,9 @@ package baritone.api.behavior; +import baritone.api.pathing.calc.IPath; import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.calc.IPath; import baritone.api.pathing.path.IPathExecutor; import java.util.Optional; diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 424c512e..bbbe32ad 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -18,9 +18,9 @@ package baritone.pathing.calc; import baritone.Baritone; +import baritone.api.pathing.calc.IPath; import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.calc.IPath; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import java.util.Optional; diff --git a/src/main/java/baritone/pathing/calc/CutoffPath.java b/src/main/java/baritone/pathing/calc/CutoffPath.java index bcf66b79..53e0c560 100644 --- a/src/main/java/baritone/pathing/calc/CutoffPath.java +++ b/src/main/java/baritone/pathing/calc/CutoffPath.java @@ -17,9 +17,9 @@ package baritone.pathing.calc; +import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; -import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import java.util.Collections; diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index f7bf9638..adcd9b71 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -18,9 +18,9 @@ package baritone.pathing.calc; import baritone.api.BaritoneAPI; +import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; -import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 3e8519ff..450551d4 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -25,7 +25,10 @@ import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.VecUtils; import baritone.behavior.LookBehavior; -import baritone.utils.*; +import baritone.utils.BlockBreakHelper; +import baritone.utils.BlockStateInterface; +import baritone.utils.Helper; +import baritone.utils.InputOverrideHandler; import net.minecraft.block.BlockLiquid; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 0be20f00..17312582 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -34,7 +34,6 @@ import baritone.cache.Waypoint; import baritone.cache.WorldProvider; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.Movement; -import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.Moves; import net.minecraft.block.Block; import net.minecraft.client.multiplayer.ChunkProviderClient; From 4374619ba2497f74eaf6f7781dba05c717dac34a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Oct 2018 16:22:03 -0700 Subject: [PATCH 169/305] update install and impact information --- IMPACT.md | 92 +------------------------------------------------- INSTALL.md | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 91 deletions(-) create mode 100644 INSTALL.md diff --git a/IMPACT.md b/IMPACT.md index 75af738b..cc12252e 100644 --- a/IMPACT.md +++ b/IMPACT.md @@ -1,91 +1 @@ -# Integration between Baritone and Impact -Impact 4.4 will have Baritone included on release, however, if you're impatient, you can install Baritone into Impact 4.3 right now! - -## An Introduction -There are some basic steps to getting Baritone setup with Impact. -- Acquiring a build of Baritone -- Placing Baritone in the libraries directory -- Modifying the Impact Profile JSON to run baritone -- How to use Baritone - -## Acquiring a build of Baritone -There are 3 methods of acquiring a build of Baritone (While it is still in development) - -### Official Release (Not always up to date) -https://github.com/cabaletta/baritone/releases - -For Impact 4.3, there is no Baritone integration yet, so you will want `baritone-standalone-X.Y.Z.jar`. - -Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. - -The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone . && docker run --rm cabaletta/baritone cat /code/dist/checksums.txt` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). - -### Building Baritone yourself -There are a few steps to this -- Clone this repository -- Setup the project as instructed in the README -- Run the ``build`` gradle task. You can either do this using IntelliJ's gradle UI or through a -command line - - Windows: ``gradlew build`` - - Mac/Linux: ``./gradlew build`` -- The build should be exported into ``/build/libs/baritone-X.Y.Z.jar`` - -### Cutting Edge Release -If you want to trust @Plutie#9079, you can download an automatically generated build of the latest commit -from his Jenkins server, found here. - -## Placing Baritone in the libraries directory -``/libraries`` is a neat directory in your Minecraft Installation Directory -that contains all of the dependencies that are required from the game and some mods. This is where we will be -putting baritone. -- Locate the ``libraries`` folder, it should be in the Minecraft Installation Directory -- Create 3 new subdirectories starting from ``libraries`` - - ``cabaletta`` - - ``baritone`` - - ``X.Y.Z`` - - Copy the build of Baritone that was acquired earlier, and place it into the ``X.Y.Z`` folder - - The full path should look like ``/libraries/cabaletta/baritone/X.Y.Z/baritone-X.Y.Z.jar`` - -## Modifying the Impact Profile JSON to run baritone -The final step is "registering" the Baritone library with Impact, so that it loads on launch. -- Ensure your Minecraft launcher is closed -- Navigate back to the Minecraft Installation Directory -- Find the ``versions`` directory, and open in -- In here there should be a ``1.12.2-Impact_4.3`` folder. - - If you don't have any Impact folder or have a version older than 4.3, you can download Impact here. -- Open the folder and inside there should be a file called ``1.12.2-Impact_4.3.json`` -- Open the JSON file with a text editor that supports your system's line endings - - For example, Notepad on Windows likely will NOT work for this. You should instead use a Text Editor like - Notepad++ if you're on Windows. (For other systems, I'm not sure - what would work the best so you may have to do some research.) -- Find the ``libraries`` array in the JSON. It should look something like this. - ``` - "libraries": [ - { - "name": "net.minecraft:launchwrapper:1.12" - }, - { - "name": "com.github.ImpactDevelopment:Impact:4.3-1.12.2", - "url": "https://impactdevelopment.github.io/maven/" - }, - { - "name": "com.github.ImpactDeveloment:ClientAPI:3.0.2", - "url": "https://impactdevelopment.github.io/maven/" - }, - ... - ``` -- Create a new object in the array, between the ``Impact`` and ``ClientAPI`` dependencies preferably. - ``` - { - "name": "cabaletta:baritone:X.Y.Z" - }, - ``` -- Now find the ``"minecraftArguments": "..."`` text near the top. -- At the very end of the quotes where it says ``--tweakClass clientapi.load.ClientTweaker"``, add on the following so it looks like: - - ``--tweakClass clientapi.load.ClientTweaker --tweakClass baritone.launch.BaritoneTweakerOptifine"`` -- If you didn't close your launcher for this step, restart it now. -- You can now launch Impact 4.3 as normal, and Baritone should start up - - ## How to use Baritone - Instructions on how to use Baritone are limited, and you may have to read a little bit of code (Really nothing much - just plain English), you can view that here. +Impact 4.4 is out. See INSTALL.md \ No newline at end of file diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 00000000..3dfa7675 --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,98 @@ +# Integration between Baritone and Impact +Impact 4.4 has Baritone included. + +These instructions apply to Impact 4.3 (and potentially other hacked clients). + + +## An Introduction +There are some basic steps to getting Baritone setup with Impact. +- Acquiring a build of Baritone +- Placing Baritone in the libraries directory +- Modifying the Impact Profile JSON to run baritone +- How to use Baritone + +## Acquiring a build of Baritone +There are 3 methods of acquiring a build of Baritone (While it is still in development) + +### Official Release (Not always up to date) +https://github.com/cabaletta/baritone/releases + +For Impact 4.3, there is no Baritone integration yet, so you will want `baritone-standalone-X.Y.Z.jar`. + +Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. + +The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone . && docker run --rm cabaletta/baritone cat /code/dist/checksums.txt` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). + +### Building Baritone yourself +There are a few steps to this +- Clone this repository +- Setup the project as instructed in the README +- Run the ``build`` gradle task. You can either do this using IntelliJ's gradle UI or through a +command line + - Windows: ``gradlew build`` + - Mac/Linux: ``./gradlew build`` +- The build should be exported into ``/build/libs/baritone-X.Y.Z.jar`` + +### Cutting Edge Release +If you want to trust @Plutie#9079, you can download an automatically generated build of the latest commit +from his Jenkins server, found here. + +## Placing Baritone in the libraries directory +``/libraries`` is a neat directory in your Minecraft Installation Directory +that contains all of the dependencies that are required from the game and some mods. This is where we will be +putting baritone. +- Locate the ``libraries`` folder, it should be in the Minecraft Installation Directory +- Create 3 new subdirectories starting from ``libraries`` + - ``cabaletta`` + - ``baritone`` + - ``X.Y.Z`` + - Copy the build of Baritone that was acquired earlier, and place it into the ``X.Y.Z`` folder + - The full path should look like ``/libraries/cabaletta/baritone/X.Y.Z/baritone-X.Y.Z.jar`` + +## Modifying the Impact Profile JSON to run baritone +The final step is "registering" the Baritone library with Impact, so that it loads on launch. +- Ensure your Minecraft launcher is closed +- Navigate back to the Minecraft Installation Directory +- Find the ``versions`` directory, and open in +- In here there should be a ``1.12.2-Impact_4.3`` folder. + - If you don't have any Impact folder or have a version older than 4.3, you can download Impact here. +- Open the folder and inside there should be a file called ``1.12.2-Impact_4.3.json`` +- Open the JSON file with a text editor that supports your system's line endings + - For example, Notepad on Windows likely will NOT work for this. You should instead use a Text Editor like + Notepad++ if you're on Windows. (For other systems, I'm not sure + what would work the best so you may have to do some research.) +- Find the ``libraries`` array in the JSON. It should look something like this. + ``` + "libraries": [ + { + "name": "net.minecraft:launchwrapper:1.12" + }, + { + "name": "com.github.ImpactDevelopment:Impact:4.3-1.12.2", + "url": "https://impactdevelopment.github.io/maven/" + }, + { + "name": "com.github.ImpactDeveloment:ClientAPI:3.0.2", + "url": "https://impactdevelopment.github.io/maven/" + }, + ... + ``` +- Create two new objects in the array, between the ``Impact`` and ``ClientAPI`` dependencies preferably. + ``` + { + "name": "cabaletta:baritone:X.Y.Z" + }, + { + "name": "com.github.ImpactDevelopment:SimpleTweaker:1.1", + "url": "https://impactdevelopment.github.io/maven/" + }, + ``` +- Now find the ``"minecraftArguments": "..."`` text near the top. +- At the very end of the quotes where it says ``--tweakClass clientapi.load.ClientTweaker"``, add on the following so it looks like: + - ``--tweakClass clientapi.load.ClientTweaker --tweakClass baritone.launch.BaritoneTweakerOptifine"`` +- If you didn't close your launcher for this step, restart it now. +- You can now launch Impact 4.3 as normal, and Baritone should start up + + ## How to use Baritone + Instructions on how to use Baritone are limited, and you may have to read a little bit of code (Really nothing much + just plain English), you can view that here. From 2df97ff986923fcde9de2303f93e149aa219274d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Oct 2018 16:55:13 -0700 Subject: [PATCH 170/305] update install link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 64133d58..81e07ab3 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Here are some links to help to get started: - [Features](FEATURES.md) -- [Baritone + Impact](IMPACT.md) +- [Installation](INSTALL.md) There's also some useful information down below From 54fb2c5f817943c846d5152a48425f46b340588c Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 15 Oct 2018 19:00:52 -0500 Subject: [PATCH 171/305] Update to SimpleTweaker 1.2 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 16a9d3eb..a78e0faa 100755 --- a/build.gradle +++ b/build.gradle @@ -81,7 +81,7 @@ repositories { } dependencies { - runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.1') + runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.2') runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') { // Mixin includes a lot of dependencies that are too up-to-date exclude module: 'launchwrapper' From b9b911eb3bc55f423f6ff0666dcd527618b1cc68 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Oct 2018 17:01:29 -0700 Subject: [PATCH 172/305] add impact link --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 81e07ab3..c6037be8 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). +Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. + Here are some links to help to get started: - [Features](FEATURES.md) From 94921fe03fb8920fd6a09d12b478f010d33023c9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Oct 2018 17:21:02 -0700 Subject: [PATCH 173/305] update simpletweaker version in proguard too --- scripts/proguard.pro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 4baa4b2a..b0a41c0a 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -28,7 +28,7 @@ -libraryjars 'tempLibraries/minecraft-1.12.2.jar' --libraryjars 'tempLibraries/SimpleTweaker-1.1.jar' +-libraryjars 'tempLibraries/SimpleTweaker-1.2.jar' -libraryjars 'tempLibraries/authlib-1.5.25.jar' -libraryjars 'tempLibraries/codecjorbis-20101023.jar' From 3cb4700b1689c131ea24d410e09d3d6383f5df2a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Oct 2018 17:21:24 -0700 Subject: [PATCH 174/305] v1.0.0 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index a78e0faa..b6c1bc9d 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '0.0.9' +version '1.0.0' buildscript { repositories { From 9cb4a1779ec07733482d04e7effc628a5caa1f6c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Oct 2018 20:37:10 -0700 Subject: [PATCH 175/305] fix placement rotation during parkour --- .../baritone/pathing/movement/movements/MovementParkour.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 38028dcf..825c99f4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -202,7 +202,7 @@ public class MovementParkour extends Movement { } else if (!playerFeet().equals(src)) { if (playerFeet().equals(src.offset(direction)) || player().posY - playerFeet().getY() > 0.0001) { - if (!MovementHelper.canWalkOn(dest.down())) { + if (!MovementHelper.canWalkOn(dest.down()) && !player().onGround) { BlockPos positionToPlace = dest.down(); for (int i = 0; i < 5; i++) { BlockPos against1 = positionToPlace.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); From b0678fd259f84aa8500141782bea6740a2efe2e7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Oct 2018 10:47:44 -0700 Subject: [PATCH 176/305] better control --- .../utils/ExampleBaritoneControl.java | 120 +++++++----------- 1 file changed, 46 insertions(+), 74 deletions(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 17312582..0f03c28f 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -65,30 +65,32 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return; } } - String msg = event.getMessage().toLowerCase(Locale.US); + String msg = event.getMessage(); if (Baritone.settings().prefix.get()) { if (!msg.startsWith("#")) { return; } msg = msg.substring(1); } + runCommand(msg); + } + public boolean runCommand(String msg) { + msg = msg.toLowerCase(Locale.US).trim(); List> toggleable = Baritone.settings().getAllValuesByType(Boolean.class); for (Settings.Setting setting : toggleable) { if (msg.equalsIgnoreCase(setting.getName())) { setting.value ^= true; - event.cancel(); logDirect("Toggled " + setting.getName() + " to " + setting.value); SettingsUtil.save(Baritone.settings()); - return; + return true; } } if (msg.equals("baritone") || msg.equals("settings")) { for (Settings.Setting setting : Baritone.settings().allSettings) { logDirect(setting.toString()); } - event.cancel(); - return; + return true; } if (msg.contains(" ")) { String[] data = msg.split(" "); @@ -110,25 +112,21 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } catch (NumberFormatException e) { logDirect("Unable to parse " + data[1]); - event.cancel(); - return; + return true; } SettingsUtil.save(Baritone.settings()); logDirect(setting.toString()); - event.cancel(); - return; + return true; } } } if (Baritone.settings().byLowerName.containsKey(msg)) { Settings.Setting setting = Baritone.settings().byLowerName.get(msg); logDirect(setting.toString()); - event.cancel(); - return; + return true; } if (msg.startsWith("goal")) { - event.cancel(); String[] params = msg.substring(4).trim().split(" "); if (params[0].equals("")) { params = new String[]{}; @@ -154,15 +152,15 @@ public class ExampleBaritoneControl extends Behavior implements Helper { break; default: logDirect("unable to understand lol"); - return; + return true; } } catch (NumberFormatException ex) { logDirect("unable to parse integer " + ex); - return; + return true; } PathingBehavior.INSTANCE.setGoal(goal); logDirect("Goal: " + goal); - return; + return true; } if (msg.equals("path")) { if (!PathingBehavior.INSTANCE.path()) { @@ -176,8 +174,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } } - event.cancel(); - return; + return true; } if (msg.equals("repack") || msg.equals("rescan")) { ChunkProviderClient cli = world().getChunkProvider(); @@ -194,22 +191,19 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } logDirect("Queued " + count + " chunks for repacking"); - event.cancel(); - return; + return true; } if (msg.equals("axis")) { PathingBehavior.INSTANCE.setGoal(new GoalAxis()); PathingBehavior.INSTANCE.path(); - event.cancel(); - return; + return true; } if (msg.equals("cancel") || msg.equals("stop")) { MineBehavior.INSTANCE.cancel(); FollowBehavior.INSTANCE.cancel(); PathingBehavior.INSTANCE.cancel(); - event.cancel(); logDirect("ok canceled"); - return; + return true; } if (msg.equals("forcecancel")) { MineBehavior.INSTANCE.cancel(); @@ -217,15 +211,13 @@ public class ExampleBaritoneControl extends Behavior implements Helper { PathingBehavior.INSTANCE.cancel(); AbstractNodeCostSearch.forceCancel(); PathingBehavior.INSTANCE.forceCancel(); - event.cancel(); logDirect("ok force canceled"); - return; + return true; } if (msg.equals("gc")) { System.gc(); - event.cancel(); logDirect("Called System.gc();"); - return; + return true; } if (msg.equals("invert")) { Goal goal = PathingBehavior.INSTANCE.getGoal(); @@ -248,8 +240,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { if (!PathingBehavior.INSTANCE.path()) { logDirect("Currently executing a path. Please cancel it first."); } - event.cancel(); - return; + return true; } if (msg.startsWith("follow")) { String name = msg.substring(6).trim(); @@ -268,25 +259,21 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } if (!toFollow.isPresent()) { logDirect("Not found"); - event.cancel(); - return; + return true; } FollowBehavior.INSTANCE.follow(toFollow.get()); logDirect("Following " + toFollow.get()); - event.cancel(); - return; + return true; } if (msg.equals("reloadall")) { WorldProvider.INSTANCE.getCurrentWorld().getCachedWorld().reloadAllFromDisk(); logDirect("ok"); - event.cancel(); - return; + return true; } if (msg.equals("saveall")) { WorldProvider.INSTANCE.getCurrentWorld().getCachedWorld().save(); logDirect("ok"); - event.cancel(); - return; + return true; } if (msg.startsWith("find")) { String blockType = msg.substring(4).trim(); @@ -298,8 +285,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { System.out.println("Was looking for " + blockType + " but actually found " + actually + " " + ChunkPacker.blockToString(actually)); } } - event.cancel(); - return; + return true; } if (msg.startsWith("mine")) { String[] blockTypes = msg.substring(4).trim().split(" "); @@ -309,21 +295,18 @@ public class ExampleBaritoneControl extends Behavior implements Helper { Objects.requireNonNull(block); MineBehavior.INSTANCE.mine(quantity, block); logDirect("Will mine " + quantity + " " + blockTypes[0]); - event.cancel(); - return; + return true; } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {} for (String s : blockTypes) { if (ChunkPacker.stringToBlock(s) == null) { logDirect(s + " isn't a valid block name"); - event.cancel(); - return; + return true; } } MineBehavior.INSTANCE.mine(0, blockTypes); logDirect("Started mining blocks of type " + Arrays.toString(blockTypes)); - event.cancel(); - return; + return true; } if (msg.startsWith("thisway")) { try { @@ -333,8 +316,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } catch (NumberFormatException ex) { logDirect("Error unable to parse '" + msg.substring(7).trim() + "' to a double."); } - event.cancel(); - return; + return true; } if (msg.startsWith("list") || msg.startsWith("get ") || msg.startsWith("show")) { String waypointType = msg.substring(4).trim(); @@ -345,8 +327,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { Waypoint.Tag tag = Waypoint.Tag.fromString(waypointType); if (tag == null) { logDirect("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase()); - event.cancel(); - return; + return true; } Set waypoints = WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().getByTag(tag); // might as well show them from oldest to newest @@ -356,11 +337,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper { for (IWaypoint waypoint : sorted) { logDirect(waypoint.toString()); } - event.cancel(); - return; + return true; } if (msg.startsWith("save")) { - event.cancel(); String name = msg.substring(4).trim(); BlockPos pos = playerFeet(); if (name.contains(" ")) { @@ -368,19 +347,19 @@ public class ExampleBaritoneControl extends Behavior implements Helper { String[] parts = name.split(" "); if (parts.length != 4) { logDirect("Unable to parse, expected four things"); - return; + return true; } try { pos = new BlockPos(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3])); } catch (NumberFormatException ex) { logDirect("Unable to parse coordinate integers"); - return; + return true; } name = parts[0]; } WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, Waypoint.Tag.USER, pos)); logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto user' to set goal, say 'list user' to list."); - return; + return true; } if (msg.startsWith("goto")) { String waypointType = msg.substring(4).trim(); @@ -394,29 +373,27 @@ public class ExampleBaritoneControl extends Behavior implements Helper { String mining = waypointType; Block block = ChunkPacker.stringToBlock(mining); //logDirect("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase()); - event.cancel(); if (block == null) { waypoint = WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null); if (waypoint == null) { logDirect("No locations for " + mining + " known, cancelling"); - return; + return true; } } else { List locs = MineBehavior.INSTANCE.scanFor(Collections.singletonList(block), 64); if (locs.isEmpty()) { logDirect("No locations for " + mining + " known, cancelling"); - return; + return true; } PathingBehavior.INSTANCE.setGoal(new GoalComposite(locs.stream().map(GoalGetToBlock::new).toArray(Goal[]::new))); PathingBehavior.INSTANCE.path(); - return; + return true; } } else { waypoint = WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().getMostRecentByTag(tag); if (waypoint == null) { logDirect("None saved for tag " + tag); - event.cancel(); - return; + return true; } } Goal goal = new GoalBlock(waypoint.getLocation()); @@ -426,8 +403,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Currently executing a path. Please cancel it first."); } } - event.cancel(); - return; + return true; } if (msg.equals("spawn") || msg.equals("bed")) { IWaypoint waypoint = WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().getMostRecentByTag(Waypoint.Tag.BED); @@ -442,14 +418,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper { PathingBehavior.INSTANCE.setGoal(goal); logDirect("Set goal to most recent bed " + goal); } - event.cancel(); - return; + return true; } if (msg.equals("sethome")) { WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", Waypoint.Tag.HOME, playerFeet())); logDirect("Saved. Say home to set goal."); - event.cancel(); - return; + return true; } if (msg.equals("home")) { IWaypoint waypoint = WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().getMostRecentByTag(Waypoint.Tag.HOME); @@ -461,8 +435,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { PathingBehavior.INSTANCE.path(); logDirect("Going to saved home " + goal); } - event.cancel(); - return; + return true; } if (msg.equals("costs")) { List moves = Stream.of(Moves.values()).map(x -> x.apply0(playerFeet())).collect(Collectors.toCollection(ArrayList::new)); @@ -479,18 +452,17 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } logDirect(parts[parts.length - 1] + " " + move.getDest().getX() + "," + move.getDest().getY() + "," + move.getDest().getZ() + " " + strCost); } - event.cancel(); - return; + return true; } if (msg.equals("pause")) { boolean enabled = PathingBehavior.INSTANCE.toggle(); logDirect("Pathing Behavior has " + (enabled ? "resumed" : "paused") + "."); - event.cancel(); - return; + return true; } if (msg.equals("damn")) { logDirect("daniel"); - return; + return true; } + return false; } } From 0cd9bb658fc3afb65f8e941bcf0b59d5b7ff0fbc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Oct 2018 11:04:49 -0700 Subject: [PATCH 177/305] keep ExampleBaritoneControl --- scripts/proguard.pro | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/proguard.pro b/scripts/proguard.pro index b0a41c0a..739774ca 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -16,6 +16,8 @@ -keep class baritone.BaritoneProvider -keep class baritone.api.IBaritoneProvider +-keep class baritone.utils.ExampleBaritoneControl { *; } + # setting names are reflected from field names, so keep field names -keepclassmembers class baritone.api.Settings { public ; From 46a24af373009be83742a7bb178c202b87ec030c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Oct 2018 11:13:08 -0700 Subject: [PATCH 178/305] cancel chat event --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 0f03c28f..69c8e214 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -72,7 +72,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } msg = msg.substring(1); } - runCommand(msg); + if (runCommand(msg)) { + event.cancel(); + } } public boolean runCommand(String msg) { From 398169f68e9f7c8b31a9fd4ac1a487464fcd4ec5 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Oct 2018 11:13:35 -0700 Subject: [PATCH 179/305] special case for damn daniel --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 69c8e214..4a73011f 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -463,7 +463,6 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } if (msg.equals("damn")) { logDirect("daniel"); - return true; } return false; } From 63ce4fe0bd893d46cffb09e322273d7e89208b40 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Oct 2018 11:32:27 -0700 Subject: [PATCH 180/305] don't crash on empty region --- src/main/java/baritone/cache/CachedWorld.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 60126fca..14b66839 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -167,6 +167,9 @@ public final class CachedWorld implements ICachedWorld, Helper { private synchronized void prune() { BlockPos pruneCenter = guessPosition(); for (CachedRegion region : allRegions()) { + if (region == null) { + continue; + } int distX = (region.getX() * 512 + 256) - pruneCenter.getX(); int distZ = (region.getZ() * 512 + 256) - pruneCenter.getZ(); double dist = Math.sqrt(distX * distX + distZ * distZ); @@ -187,6 +190,9 @@ public final class CachedWorld implements ICachedWorld, Helper { } CachedChunk mostRecentlyModified = null; for (CachedRegion region : allRegions()) { + if (region == null) { + continue; + } CachedChunk ch = region.mostRecentlyModified(); if (ch == null) { continue; From ac372bc6fcce35ca5447fef0d1ced60962cce551 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Oct 2018 11:32:44 -0700 Subject: [PATCH 181/305] v1.0.0-hotfix-1 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index b6c1bc9d..81945c49 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.0.0' +version '1.0.0-hotfix-1' buildscript { repositories { From dd25527a62508eee97bc83dcc7afee221c8a969d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Oct 2018 14:19:40 -0700 Subject: [PATCH 182/305] pillar fixes for ncp --- .../movement/movements/MovementPillar.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 480f6659..62241a2b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -162,10 +162,11 @@ public class MovementPillar extends Movement { } boolean ladder = fromDown.getBlock() instanceof BlockLadder || fromDown.getBlock() instanceof BlockVine; boolean vine = fromDown.getBlock() instanceof BlockVine; + Rotation rotation = RotationUtils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F), + VecUtils.getBlockPosCenter(positionToPlace), + new Rotation(mc.player.rotationYaw, mc.player.rotationPitch)); if (!ladder) { - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F), - VecUtils.getBlockPosCenter(positionToPlace), - new Rotation(mc.player.rotationYaw, mc.player.rotationPitch)), true)); + state.setTarget(new MovementState.MovementTarget(new Rotation(mc.player.rotationYaw, rotation.getPitch()), true)); } boolean blockIsThere = MovementHelper.canWalkOn(src) || ladder; @@ -198,7 +199,8 @@ public class MovementPillar extends Movement { // If our Y coordinate is above our goal, stop jumping state.setInput(InputOverrideHandler.Input.JUMP, player().posY < dest.getY()); - state.setInput(InputOverrideHandler.Input.SNEAK, true); + state.setInput(InputOverrideHandler.Input.SNEAK, player().posY > dest.getY()); // delay placement by 1 tick for ncp compatibility + // since (lower down) we only right click once player.isSneaking, and that happens the tick after we request to sneak double diffX = player().posX - (dest.getX() + 0.5); double diffZ = player().posZ - (dest.getZ() + 0.5); @@ -209,6 +211,9 @@ public class MovementPillar extends Movement { // 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); + + // revise our target to both yaw and pitch if we're going to be moving forward + state.setTarget(new MovementState.MovementTarget(rotation, true)); } @@ -217,7 +222,7 @@ public class MovementPillar extends Movement { 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()) { + } else if (Minecraft.getMinecraft().player.isSneaking()) { // 1 tick after we're able to place state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } } From 85b038dada28c6d0046654b86fb13f5c20e72c6b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Oct 2018 16:03:51 -0700 Subject: [PATCH 183/305] v1.0.0-hotfix-2 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 81945c49..abb75959 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.0.0-hotfix-1' +version '1.0.0-hotfix-2' buildscript { repositories { From 3aa8f51015996a3edaa4541d5d4fc198c6cfcc19 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Oct 2018 17:00:37 -0700 Subject: [PATCH 184/305] print shasums on build --- buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index 15e36314..48b83421 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -62,6 +62,8 @@ public class CreateDistTask extends BaritoneGradleTask { .map(path -> sha1(path) + " " + path.getFileName().toString()) .collect(Collectors.toList()); + shasum.forEach(System.out::println); + // Write the checksums to a file Files.write(getRelativeFile("dist/checksums.txt"), shasum); } From 11ed8a2f21b9fa9078411cd2e8a1677e254eb0dd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Oct 2018 20:05:18 -0700 Subject: [PATCH 185/305] rearrange fields and constructors --- .../baritone/api/utils/RayTraceUtils.java | 7 ++--- .../baritone/api/utils/RotationUtils.java | 4 +-- src/api/java/baritone/api/utils/VecUtils.java | 30 ++++++++----------- 3 files changed, 17 insertions(+), 24 deletions(-) diff --git a/src/api/java/baritone/api/utils/RayTraceUtils.java b/src/api/java/baritone/api/utils/RayTraceUtils.java index 6c35e816..1444c7e1 100644 --- a/src/api/java/baritone/api/utils/RayTraceUtils.java +++ b/src/api/java/baritone/api/utils/RayTraceUtils.java @@ -30,14 +30,13 @@ import java.util.Optional; * @since 8/25/2018 */ public final class RayTraceUtils { - - private RayTraceUtils() {} - /** * The {@link Minecraft} instance */ private static final Minecraft mc = Minecraft.getMinecraft(); + private RayTraceUtils() {} + /** * Simulates a "vanilla" raytrace. A RayTraceResult returned by this method * will be that of the next render pass given that the local player's yaw and @@ -46,7 +45,7 @@ public final class RayTraceUtils { * thing to achieve the desired outcome (whether it is hitting and entity or placing * a block) can be done just by modifying user input. * - * @param yaw The yaw to raytrace with + * @param yaw The yaw to raytrace with * @param pitch The pitch to raytrace with * @return The calculated raytrace result */ diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index fc1b0297..bea16fc7 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -31,8 +31,6 @@ import java.util.Optional; */ public final class RotationUtils { - private RotationUtils() {} - /** * The {@link Minecraft} instance */ @@ -60,6 +58,8 @@ public final class RotationUtils { new Vec3d(1, 0.5, 0.5) // East }; + private RotationUtils() {} + /** * Clamps the specified pitch value between -90 and 90. * diff --git a/src/api/java/baritone/api/utils/VecUtils.java b/src/api/java/baritone/api/utils/VecUtils.java index 51279474..831e0937 100644 --- a/src/api/java/baritone/api/utils/VecUtils.java +++ b/src/api/java/baritone/api/utils/VecUtils.java @@ -30,21 +30,19 @@ import net.minecraft.util.math.Vec3d; * @since 10/13/2018 */ public final class VecUtils { - - private VecUtils() {} - /** * The {@link Minecraft} instance */ private static final Minecraft mc = Minecraft.getMinecraft(); + private VecUtils() {} + /** * Calculates the center of the block at the specified position's bounding box * - * @see #getBlockPosCenter(BlockPos) - * * @param pos The block position * @return The center of the block's bounding box + * @see #getBlockPosCenter(BlockPos) */ public static Vec3d calculateBlockCenter(BlockPos pos) { IBlockState b = mc.world.getBlockState(pos); @@ -68,10 +66,9 @@ public final class VecUtils { *

* TODO: We may want to consider replacing many usages of this method with #calculateBlockCenter(BlockPos) * - * @see #calculateBlockCenter(BlockPos) - * * @param pos The block position * @return The assumed center of the position + * @see #calculateBlockCenter(BlockPos) */ public static Vec3d getBlockPosCenter(BlockPos pos) { return new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); @@ -80,13 +77,12 @@ public final class VecUtils { /** * Gets the distance from the specified position to the assumed center of the specified block position. * - * @see #getBlockPosCenter(BlockPos) - * * @param pos The block position - * @param x The x pos - * @param y The y pos - * @param z The z pos + * @param x The x pos + * @param y The y pos + * @param z The z pos * @return The distance from the assumed block center to the position + * @see #getBlockPosCenter(BlockPos) */ public static double distanceToCenter(BlockPos pos, double x, double y, double z) { Vec3d center = getBlockPosCenter(pos); @@ -100,11 +96,10 @@ public final class VecUtils { * Gets the distance from the specified entity's position to the assumed * center of the specified block position. * - * @see #getBlockPosCenter(BlockPos) - * * @param entity The entity - * @param pos The block position + * @param pos The block position * @return The distance from the entity to the block's assumed center + * @see #getBlockPosCenter(BlockPos) */ public static double entityDistanceToCenter(Entity entity, BlockPos pos) { return distanceToCenter(pos, entity.posX, entity.posY, entity.posZ); @@ -114,11 +109,10 @@ public final class VecUtils { * Gets the distance from the specified entity's position to the assumed * center of the specified block position, ignoring the Y axis. * - * @see #getBlockPosCenter(BlockPos) - * * @param entity The entity - * @param pos The block position + * @param pos The block position * @return The horizontal distance from the entity to the block's assumed center + * @see #getBlockPosCenter(BlockPos) */ public static double entityFlatDistanceToCenter(Entity entity, BlockPos pos) { return distanceToCenter(pos, entity.posX, pos.getY() + 0.5, entity.posZ); From 732d8068207960b23b22f5067a15acc42c6fc496 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 17 Oct 2018 12:15:46 -0700 Subject: [PATCH 186/305] allow cutting onto next path one movement earlier --- src/main/java/baritone/pathing/path/PathExecutor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 4acecbdc..61251882 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -276,7 +276,7 @@ public class PathExecutor implements IPathExecutor, Helper { return true; } } - return false; // movement is in progress + return canCancel; // movement is in progress, but if it reports cancellable, PathingBehavior is good to cut onto the next path } private Tuple closestPathPos(IPath path) { From 313a5fddbee14983a38c9711570d4a10d5c81293 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 18 Oct 2018 14:36:14 -0700 Subject: [PATCH 187/305] add release badge --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c6037be8..eb427ab2 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # Baritone [![Build Status](https://travis-ci.com/cabaletta/baritone.svg?branch=master)](https://travis-ci.com/cabaletta/baritone) +[![Release](https://img.shields.io/github/release/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/releases) [![License](https://img.shields.io/github/license/cabaletta/baritone.svg)](LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) From 1a809fa7a3c4ba2a5fd018e29362ef8e6342136e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 18 Oct 2018 15:04:40 -0700 Subject: [PATCH 188/305] dispatch path events from main thread instead of calculation thread --- .../baritone/behavior/PathingBehavior.java | 55 ++++++++++++------- .../baritone/pathing/path/PathExecutor.java | 9 +-- 2 files changed, 38 insertions(+), 26 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index f9916611..869aac1f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -41,6 +41,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; import java.util.*; +import java.util.concurrent.LinkedBlockingQueue; import java.util.stream.Collectors; public final class PathingBehavior extends Behavior implements IPathingBehavior, Helper { @@ -59,29 +60,45 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private boolean lastAutoJump; + private final LinkedBlockingQueue toDispatch = new LinkedBlockingQueue<>(); + private PathingBehavior() {} - private void dispatchPathEvent(PathEvent event) { - Baritone.INSTANCE.getExecutor().execute(() -> Baritone.INSTANCE.getGameEventHandler().onPathEvent(event)); + private void queuePathEvent(PathEvent event) { + toDispatch.add(event); + } + + private void dispatchEvents() { + ArrayList curr = new ArrayList<>(); + toDispatch.drainTo(curr); + for (PathEvent event : curr) { + Baritone.INSTANCE.getGameEventHandler().onPathEvent(event); + } } @Override public void onTick(TickEvent event) { + dispatchEvents(); if (event.getType() == TickEvent.Type.OUT) { - this.cancel(); + cancel(); return; } mc.playerController.setPlayerCapabilities(mc.player); + tickPath(); + dispatchEvents(); + } + + private void tickPath() { if (current == null) { return; } - boolean safe = current.onTick(event); + boolean safe = current.onTick(); synchronized (pathPlanLock) { if (current.failed() || current.finished()) { current = null; if (goal == null || goal.isInGoal(playerFeet())) { logDebug("All done. At " + goal); - dispatchPathEvent(PathEvent.AT_GOAL); + queuePathEvent(PathEvent.AT_GOAL); next = null; return; } @@ -93,25 +110,25 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // 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); + queuePathEvent(PathEvent.DISCARD_NEXT); next = null; } if (next != null) { logDebug("Continuing on to planned next path"); - dispatchPathEvent(PathEvent.CONTINUING_ONTO_PLANNED_NEXT); + queuePathEvent(PathEvent.CONTINUING_ONTO_PLANNED_NEXT); current = next; next = null; - current.onTick(event); + current.onTick(); return; } // 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); + queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING); // if we aren't calculating right now return; } - dispatchPathEvent(PathEvent.CALC_STARTED); + queuePathEvent(PathEvent.CALC_STARTED); findPathInNewThread(pathStart(), true, Optional.empty()); } return; @@ -123,10 +140,10 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, if (next.snipsnapifpossible()) { // jump directly onto the next path logDebug("Splicing into planned next path early..."); - dispatchPathEvent(PathEvent.SPLICING_ONTO_NEXT_EARLY); + queuePathEvent(PathEvent.SPLICING_ONTO_NEXT_EARLY); current = next; next = null; - current.onTick(event); + current.onTick(); return; } } @@ -147,7 +164,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, if (ticksRemainingInSegment().get() < Baritone.settings().planningTickLookAhead.get()) { // and this path has 5 seconds or less left logDebug("Path almost over. Planning ahead..."); - dispatchPathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED); + queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED); findPathInNewThread(current.getPath().getDest(), false, Optional.of(current.getPath())); } } @@ -211,7 +228,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, @Override public void cancel() { - dispatchPathEvent(PathEvent.CANCELED); + queuePathEvent(PathEvent.CANCELED); current = null; next = null; Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys(); @@ -244,7 +261,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, if (isPathCalcInProgress) { return false; } - dispatchPathEvent(PathEvent.CALC_STARTED); + queuePathEvent(PathEvent.CALC_STARTED); findPathInNewThread(pathStart(), true, Optional.empty()); return true; } @@ -343,18 +360,18 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, synchronized (pathPlanLock) { if (current == null) { if (executor.isPresent()) { - dispatchPathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING); + queuePathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING); current = executor.get(); } else { - dispatchPathEvent(PathEvent.CALC_FAILED); + queuePathEvent(PathEvent.CALC_FAILED); } } else { if (next == null) { if (executor.isPresent()) { - dispatchPathEvent(PathEvent.NEXT_SEGMENT_CALC_FINISHED); + queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_FINISHED); next = executor.get(); } else { - dispatchPathEvent(PathEvent.NEXT_CALC_FAILED); + queuePathEvent(PathEvent.NEXT_CALC_FAILED); } } else { throw new IllegalStateException("I have no idea what to do with this path"); diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 61251882..045cdab9 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -18,7 +18,6 @@ package baritone.pathing.path; import baritone.Baritone; -import baritone.api.event.events.TickEvent; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.IMovement; @@ -81,14 +80,10 @@ public class PathExecutor implements IPathExecutor, Helper { /** * Tick this executor * - * @param event * @return True if a movement just finished (and the player is therefore in a "stable" state, like, * not sneaking out over lava), false otherwise */ - public boolean onTick(TickEvent event) { - if (event.getType() == TickEvent.Type.OUT) { - throw new IllegalStateException(); - } + public boolean onTick() { if (pathPosition == path.length() - 1) { pathPosition++; } @@ -261,7 +256,7 @@ public class PathExecutor implements IPathExecutor, Helper { //System.out.println("Movement done, next path"); pathPosition++; onChangeInPathPosition(); - onTick(event); + onTick(); return true; } else { sprintIfRequested(); From b55d96169f571ea2578ccc03e81792c990eb0593 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 19 Oct 2018 21:15:37 -0700 Subject: [PATCH 189/305] update some documentation --- Dockerfile | 8 ++++---- INSTALL.md | 8 +++----- scripts/proguard.pro | 3 +++ 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Dockerfile b/Dockerfile index 321a902a..bec43d69 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,10 +15,10 @@ RUN apt install -qq --force-yes mesa-utils libgl1-mesa-glx libxcursor1 libxrandr COPY . /code -# this .deb is specially patched to support lwjgl -# source: https://github.com/tectonicus/tectonicus/issues/60#issuecomment-154239173 -RUN dpkg -i /code/scripts/xvfb_1.16.4-1_amd64.deb - WORKDIR /code +# this .deb is specially patched to support lwjgl +# source: https://github.com/tectonicus/tectonicus/issues/60#issuecomment-154239173 +RUN dpkg -i scripts/xvfb_1.16.4-1_amd64.deb + RUN ./gradlew build \ No newline at end of file diff --git a/INSTALL.md b/INSTALL.md index 3dfa7675..d829ccfc 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -3,6 +3,8 @@ Impact 4.4 has Baritone included. These instructions apply to Impact 4.3 (and potentially other hacked clients). +To run Baritone on Vanilla, just follow the instructions in the README (it's `./gradlew runClient`). + ## An Introduction There are some basic steps to getting Baritone setup with Impact. @@ -12,7 +14,7 @@ There are some basic steps to getting Baritone setup with Impact. - How to use Baritone ## Acquiring a build of Baritone -There are 3 methods of acquiring a build of Baritone (While it is still in development) +There are two methods of acquiring a build of Baritone ### Official Release (Not always up to date) https://github.com/cabaletta/baritone/releases @@ -33,10 +35,6 @@ command line - Mac/Linux: ``./gradlew build`` - The build should be exported into ``/build/libs/baritone-X.Y.Z.jar`` -### Cutting Edge Release -If you want to trust @Plutie#9079, you can download an automatically generated build of the latest commit -from his Jenkins server, found here. - ## Placing Baritone in the libraries directory ``/libraries`` is a neat directory in your Minecraft Installation Directory that contains all of the dependencies that are required from the game and some mods. This is where we will be diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 739774ca..a13a0e3f 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -13,9 +13,12 @@ -repackageclasses 'baritone' -keep class baritone.api.** { *; } # this is the keep api + +# service provider needs these class names -keep class baritone.BaritoneProvider -keep class baritone.api.IBaritoneProvider +# hack -keep class baritone.utils.ExampleBaritoneControl { *; } # setting names are reflected from field names, so keep field names From 25bebdc1720217f8f1a6aef251e8cea2f32f8e9b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 20 Oct 2018 20:33:49 -0700 Subject: [PATCH 190/305] leftClickCounter shadow appears to be unneeded --- src/launch/java/baritone/launch/mixins/MixinMinecraft.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 4e2d8a52..19129a5a 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -49,8 +49,6 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Mixin(Minecraft.class) public class MixinMinecraft { - @Shadow - private int leftClickCounter; @Shadow public EntityPlayerSP player; @Shadow From a6dc156a7957001e092a27c7da210b7bab970479 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 21 Oct 2018 14:24:23 -0700 Subject: [PATCH 191/305] bump version to match build gradle --- INSTALL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/INSTALL.md b/INSTALL.md index d829ccfc..9df3d6bf 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -81,7 +81,7 @@ The final step is "registering" the Baritone library with Impact, so that it loa "name": "cabaletta:baritone:X.Y.Z" }, { - "name": "com.github.ImpactDevelopment:SimpleTweaker:1.1", + "name": "com.github.ImpactDevelopment:SimpleTweaker:1.2", "url": "https://impactdevelopment.github.io/maven/" }, ``` From af788133c2c8ee11b590fa083461c9e0ef155342 Mon Sep 17 00:00:00 2001 From: 0x22 <9968651+0-x-2-2@users.noreply.github.com> Date: Mon, 22 Oct 2018 15:42:05 -0400 Subject: [PATCH 192/305] Fixed serious issue. Determinizer description was incorrect. --- buildSrc/src/main/java/baritone/gradle/util/Determinizer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java index d50c1e54..fc268cd3 100644 --- a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java +++ b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java @@ -32,7 +32,7 @@ import java.util.jar.JarOutputStream; import java.util.stream.Collectors; /** - * Make a .jar file deterministic by sorting all entries by name, and setting all the last modified times to 0. + * Make a .jar file deterministic by sorting all entries by name, and setting all the last modified times to 42069. * This makes the build 100% reproducible since the timestamp when you built it no longer affects the final file. * * @author leijurv From 82417f4f851f62674d63450f193d1a0b1612eb90 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 22 Oct 2018 12:42:08 -0700 Subject: [PATCH 193/305] comment to explain weird thing --- .../java/baritone/launch/mixins/MixinEntityLivingBase.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java index d2701cff..6313b3a1 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -40,6 +40,8 @@ public class MixinEntityLivingBase { ) private void preJump(CallbackInfo ci) { EntityLivingBase _this = (EntityLivingBase) (Object) this; + // This uses Class.isInstance instead of instanceof since proguard optimizes out the instanceof (since MixinEntityLivingBase could never be instanceof EntityLivingBase in normal java) + // but proguard isn't smart enough to optimize out this Class.isInstance =) if (EntityPlayerSP.class.isInstance(_this)) Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.PRE, RotationMoveEvent.Type.JUMP)); } @@ -50,6 +52,7 @@ public class MixinEntityLivingBase { ) private void postJump(CallbackInfo ci) { EntityLivingBase _this = (EntityLivingBase) (Object) this; + // See above if (EntityPlayerSP.class.isInstance(_this)) Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.POST, RotationMoveEvent.Type.JUMP)); } From e5ca30dc26adfa9af1ab0f59e20b4993f515d530 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 22 Oct 2018 14:04:19 -0700 Subject: [PATCH 194/305] forgot that one --- src/main/java/baritone/cache/CachedChunk.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 317bf377..8d2188b5 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -48,6 +48,7 @@ public final class CachedChunk implements IBlockTypeAccess, Helper { add(Blocks.ENDER_CHEST); add(Blocks.FURNACE); add(Blocks.CHEST); + add(Blocks.TRAPPED_CHEST); add(Blocks.END_PORTAL); add(Blocks.END_PORTAL_FRAME); add(Blocks.MOB_SPAWNER); From ad941fcbb261edef46abc285a62e0a252dccb564 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 22 Oct 2018 18:01:55 -0500 Subject: [PATCH 195/305] Clarify anti nudge --- src/api/java/baritone/api/utils/RotationUtils.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index bea16fc7..c7ff3057 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -177,6 +177,8 @@ public final class RotationUtils { * is by setting the desired pitch to the current pitch * setting the desired pitch to the current pitch + 0.0001 means that we do have a desired pitch, it's * just what it currently is + * + * or if you're a normal person literally all this does it ensure that we don't nudge the pitch to a normal level */ return Optional.of(new Rotation(entity.rotationYaw, entity.rotationPitch + 0.0001F)); } From 9a1aecc00272b8aab8a1c64f8dd32110e6888dff Mon Sep 17 00:00:00 2001 From: ave4224 Date: Tue, 23 Oct 2018 00:41:59 -0400 Subject: [PATCH 196/305] tool set, fixes #227 --- .../pathing/movement/MovementHelper.java | 2 +- src/main/java/baritone/utils/ToolSet.java | 172 ++++++++++++------ 2 files changed, 115 insertions(+), 59 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index c2e3450c..9f785052 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -400,7 +400,7 @@ public interface MovementHelper extends ActionCosts, Helper { * @param ts previously calculated ToolSet */ static void switchToBestToolFor(IBlockState b, ToolSet ts) { - mc.player.inventory.currentItem = ts.getBestSlot(b); + mc.player.inventory.currentItem = ts.getBestSlot(b.getBlock()); } static boolean throwaway(boolean select) { diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 962ffb08..0c618294 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -23,41 +23,41 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.init.Enchantments; import net.minecraft.init.MobEffects; +import net.minecraft.item.Item.ToolMaterial; import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemTool; import java.util.HashMap; import java.util.Map; +import java.util.function.Function; /** * A cached list of the best tools on the hotbar for any block * - * @author avecowa, Brady, leijurv + * @author Avery, Brady, leijurv */ public class ToolSet implements Helper { - /** * A cache mapping a {@link Block} to how long it will take to break * with this toolset, given the optimum tool is used. */ - private Map breakStrengthCache = new HashMap<>(); + private final Map breakStrengthCache; /** - * 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 + * My buddy leijurv owned me so we have this to not create a new lambda instance. */ - public byte getBestSlot(IBlockState b) { - byte best = 0; - double value = -1; - for (byte i = 0; i < 9; i++) { - double v = calculateStrVsBlock(i, b); - if (v > value || value == -1) { - value = v; - best = i; - } + private final Function backendCalculation; + + public ToolSet() { + breakStrengthCache = new HashMap<>(); + + if (Baritone.settings().considerPotionEffects.get()) { + double amplifier = potionAmplifier(); + Function amplify = x -> amplifier * x; + backendCalculation = amplify.compose(this::getBestDestructionTime); + } else { + backendCalculation = this::getBestDestructionTime; } - return best; } /** @@ -67,14 +67,64 @@ public class ToolSet implements Helper { * @return how long it would take in ticks */ public double getStrVsBlock(IBlockState state) { - Double strength = this.breakStrengthCache.get(state.getBlock()); - if (strength != null) { - // the function will take this path >99% of the time - return strength; + return breakStrengthCache.computeIfAbsent(state.getBlock(), backendCalculation); + } + + /** + * Evaluate the material cost of a possible tool. The priority matches the + * listed order in the Item.ToolMaterial enum. + * + * @param itemStack a possibly empty ItemStack + * @return values range from -1 to 4 + */ + private int getMaterialCost(ItemStack itemStack) { + if (itemStack.getItem() instanceof ItemTool) { + ItemTool tool = (ItemTool) itemStack.getItem(); + return ToolMaterial.valueOf(tool.getToolMaterialName()).ordinal(); + } else { + return -1; } - double str = calculateStrVsBlock(getBestSlot(state), state); - this.breakStrengthCache.put(state.getBlock(), str); - return str; + } + + /** + * Calculate which tool on the hotbar is best for mining + * + * @param b the blockstate to be mined + * @return A byte containing the index in the tools array that worked best + */ + public byte getBestSlot(Block b) { + byte best = 0; + double value = Double.NEGATIVE_INFINITY; + int materialCost = Integer.MIN_VALUE; + IBlockState blockState = b.getDefaultState(); + for (byte i = 0; i < 9; i++) { + ItemStack itemStack = player().inventory.getStackInSlot(i); + double v = calculateStrVsBlock(itemStack, blockState); + if (v > value) { + value = v; + best = i; + materialCost = getMaterialCost(itemStack); + } else if (v == value) { + int c = getMaterialCost(itemStack); + if (c < materialCost) { + value = v; + best = i; + materialCost = c; + } + } + } + return best; + } + + /** + * Calculate how effectively a block can be destroyed + * + * @param b the blockstate to be mined + * @return A double containing the destruction ticks with the best tool + */ + private double getBestDestructionTime(Block b) { + ItemStack stack = player().inventory.getStackInSlot(getBestSlot(b)); + return calculateStrVsBlock(stack, b.getDefaultState()); } /** @@ -84,49 +134,55 @@ public class ToolSet implements Helper { * @param state the blockstate to be mined * @return how long it would take in ticks */ - private double calculateStrVsBlock(byte slot, IBlockState state) { - // Calculate the slot with the best item - ItemStack contents = player().inventory.getStackInSlot(slot); - - float blockHard = state.getBlockHardness(null, null); - if (blockHard < 0) { + private double calculateStrVsBlock(ItemStack item, IBlockState state) { + float hardness = state.getBlockHardness(null, null); + if (hardness < 0) { return -1; } - float speed = contents.getDestroySpeed(state); + float speed = item.getDestroySpeed(state); if (speed > 1) { - int effLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.EFFICIENCY, contents); - if (effLevel > 0 && !contents.isEmpty()) { + int effLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.EFFICIENCY, item); + if (effLevel > 0 && !item.isEmpty()) { speed += effLevel * effLevel + 1; } } - if (Baritone.settings().considerPotionEffects.get()) { - if (player().isPotionActive(MobEffects.HASTE)) { - speed *= 1 + (player().getActivePotionEffect(MobEffects.HASTE).getAmplifier() + 1) * 0.2; - } - if (player().isPotionActive(MobEffects.MINING_FATIGUE)) { - switch (player().getActivePotionEffect(MobEffects.MINING_FATIGUE).getAmplifier()) { - case 0: - speed *= 0.3; - break; - case 1: - speed *= 0.09; - break; - case 2: - speed *= 0.0027; - break; - default: - speed *= 0.00081; - break; - } - } - } - speed /= blockHard; - if (state.getMaterial().isToolNotRequired() || (!contents.isEmpty() && contents.canHarvestBlock(state))) { - return speed / 30; + speed /= hardness; + if (state.getMaterial().isToolNotRequired() || (!item.isEmpty() && item.canHarvestBlock(state))) { + speed /= 30; } else { - return speed / 100; + speed /= 100; } + return speed; + } + + /** + * Calculates any modifier to breaking time based on status effects. + * + * @return a double to scale block breaking speed. + */ + private double potionAmplifier() { + double speed = 1; + if (player().isPotionActive(MobEffects.HASTE)) { + speed *= 1 + (player().getActivePotionEffect(MobEffects.HASTE).getAmplifier() + 1) * 0.2; + } + if (player().isPotionActive(MobEffects.MINING_FATIGUE)) { + switch (player().getActivePotionEffect(MobEffects.MINING_FATIGUE).getAmplifier()) { + case 0: + speed *= 0.3; + break; + case 1: + speed *= 0.09; + break; + case 2: + speed *= 0.0027; + break; + default: + speed *= 0.00081; + break; + } + } + return speed; } } From 96e7f37799b0fca0663b3ff9ae4cac07748f85e4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 23 Oct 2018 20:41:35 -0700 Subject: [PATCH 197/305] add link to adovin's video --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eb427ab2..ccf2802f 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). -Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. +Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. Here are some links to help to get started: From 76170816375b906d7bd6347272e8f07714dd1c2b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 24 Oct 2018 23:22:19 -0700 Subject: [PATCH 198/305] no longer needed --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index ccf2802f..588a90c9 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,6 @@ [![License](https://img.shields.io/github/license/cabaletta/baritone.svg)](LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) - - A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). From a0b1cb2993b27aae3a2af716fecdc5c22bfdf182 Mon Sep 17 00:00:00 2001 From: leijurv Date: Thu, 25 Oct 2018 20:08:52 -0700 Subject: [PATCH 199/305] preliminary refactoring --- .../java/baritone/behavior/MineBehavior.java | 28 +++++++++---------- .../utils/ExampleBaritoneControl.java | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index 311203e8..3bb5e8da 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -50,8 +50,8 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe public static final MineBehavior INSTANCE = new MineBehavior(); private List mining; - private List locationsCache; - private int quantity; + private List knownOreLocations; + private int desiredQuantity; private MineBehavior() {} @@ -64,11 +64,11 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe if (mining == null) { return; } - if (quantity > 0) { + if (desiredQuantity > 0) { Item item = mining.get(0).getItemDropped(mining.get(0).getDefaultState(), new Random(), 0); int curr = player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum(); System.out.println("Currently have " + curr + " " + item); - if (curr >= quantity) { + if (curr >= desiredQuantity) { logDirect("Have " + curr + " " + item.getItemStackDisplayName(new ItemStack(item, 1))); cancel(); return; @@ -88,12 +88,12 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe if (mining == null) { return; } - List locs = locationsCache; + List locs = knownOreLocations; if (!locs.isEmpty()) { locs = prune(new ArrayList<>(locs), mining, 64); PathingBehavior.INSTANCE.setGoal(coalesce(locs)); PathingBehavior.INSTANCE.path(); - locationsCache = locs; + knownOreLocations = locs; } } @@ -101,16 +101,16 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe if (mining == null) { return; } - List locs = scanFor(mining, 64); + List locs = xrayFor(mining, 64); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); mine(0, (String[]) null); return; } - locationsCache = locs; + knownOreLocations = locs; } - public Goal coalesce(BlockPos loc, List locs) { + private static Goal coalesce(BlockPos loc, List locs) { if (!Baritone.settings().forceInternalMining.get()) { return new GoalTwoBlocks(loc); } @@ -136,7 +136,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe return new GoalComposite(locs.stream().map(loc -> coalesce(loc, locs)).toArray(Goal[]::new)); } - public List scanFor(List mining, int max) { + public List xrayFor(List mining, int max) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); //long b = System.currentTimeMillis(); @@ -177,8 +177,8 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe @Override public void mine(int quantity, String... blocks) { this.mining = blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlock).collect(Collectors.toList()); - this.quantity = quantity; - this.locationsCache = new ArrayList<>(); + this.desiredQuantity = quantity; + this.knownOreLocations = new ArrayList<>(); rescan(); updateGoal(); } @@ -186,8 +186,8 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe @Override public void mine(int quantity, Block... blocks) { this.mining = blocks == null || blocks.length == 0 ? null : Arrays.asList(blocks); - this.quantity = quantity; - this.locationsCache = new ArrayList<>(); + this.desiredQuantity = quantity; + this.knownOreLocations = new ArrayList<>(); rescan(); updateGoal(); } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 4a73011f..77132e82 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -382,7 +382,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } else { - List locs = MineBehavior.INSTANCE.scanFor(Collections.singletonList(block), 64); + List locs = MineBehavior.INSTANCE.xrayFor(Collections.singletonList(block), 64); if (locs.isEmpty()) { logDirect("No locations for " + mining + " known, cancelling"); return true; From 55091154c4970f8500cffda0da48f320e37b3c68 Mon Sep 17 00:00:00 2001 From: leijurv Date: Thu, 25 Oct 2018 21:21:42 -0700 Subject: [PATCH 200/305] start on legitMine --- src/api/java/baritone/api/Settings.java | 14 ++- .../java/baritone/behavior/MineBehavior.java | 94 +++++++++++++++---- .../baritone/behavior/PathingBehavior.java | 5 + 3 files changed, 93 insertions(+), 20 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 04c396fd..0d8529dd 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -24,8 +24,8 @@ import net.minecraft.util.text.ITextComponent; import java.awt.*; import java.lang.reflect.Field; -import java.util.*; import java.util.List; +import java.util.*; import java.util.function.Consumer; /** @@ -396,6 +396,18 @@ public class Settings { */ public Setting axisHeight = new Setting<>(120); + /** + * Allow MineBehavior to use X-Ray to see where the ores are. Turn this option off to force it to mine "legit" + * where it will only mine an ore once it can actually see it, so it won't do or know anything that a normal player + * couldn't. If you don't want it to look like you're X-Raying, turn this off + */ + public Setting legitMine = new Setting<>(false); + + /** + * What Y level to go to for legit strip mining + */ + public Setting legitMineYLevel = new Setting<>(11); + /** * When mining block of a certain type, try to mine two at once instead of one. * If the block above is also a goal block, set GoalBlock instead of GoalTwoBlocks diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index 3bb5e8da..81a18ef7 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -20,14 +20,13 @@ package baritone.behavior; import baritone.Baritone; import baritone.api.behavior.IMineBehavior; import baritone.api.event.events.TickEvent; -import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.goals.GoalBlock; -import baritone.api.pathing.goals.GoalComposite; -import baritone.api.pathing.goals.GoalTwoBlocks; +import baritone.api.pathing.goals.*; +import baritone.api.utils.RotationUtils; import baritone.cache.CachedChunk; import baritone.cache.ChunkPacker; import baritone.cache.WorldProvider; import baritone.cache.WorldScanner; +import baritone.pathing.movement.MovementHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import net.minecraft.block.Block; @@ -51,6 +50,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe private List mining; private List knownOreLocations; + private BlockPos branchPoint; private int desiredQuantity; private MineBehavior() {} @@ -80,6 +80,9 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe Baritone.INSTANCE.getExecutor().execute(this::rescan); } } + if (Baritone.settings().legitMine.get()) { + addNearby(); + } updateGoal(); PathingBehavior.INSTANCE.revalidateGoal(); } @@ -90,17 +93,42 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe } List locs = knownOreLocations; if (!locs.isEmpty()) { - locs = prune(new ArrayList<>(locs), mining, 64); - PathingBehavior.INSTANCE.setGoal(coalesce(locs)); - PathingBehavior.INSTANCE.path(); + List locs2 = prune(new ArrayList<>(locs), mining, 64); + // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final + PathingBehavior.INSTANCE.setGoalAndPath(new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new))); knownOreLocations = locs; + return; } + // we don't know any ore locations at the moment + if (!Baritone.settings().legitMine.get()) { + return; + } + // only in non-Xray mode (aka legit mode) do we do this + if (branchPoint == null) { + int y = Baritone.settings().legitMineYLevel.get(); + if (!PathingBehavior.INSTANCE.isPathing() && playerFeet().y == y) { + // cool, path is over and we are at desired y + branchPoint = playerFeet(); + } else { + PathingBehavior.INSTANCE.setGoalAndPath(new GoalYLevel(y)); + return; + } + } + + if (playerFeet().equals(branchPoint)) { + // TODO mine 1x1 shafts to either side + branchPoint = branchPoint.north(10); + } + PathingBehavior.INSTANCE.setGoalAndPath(new GoalBlock(branchPoint)); } private void rescan() { if (mining == null) { return; } + if (Baritone.settings().legitMine.get()) { + return; + } List locs = xrayFor(mining, 64); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); @@ -132,10 +160,6 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe } } - public GoalComposite coalesce(List locs) { - return new GoalComposite(locs.stream().map(loc -> coalesce(loc, locs)).toArray(Goal[]::new)); - } - public List xrayFor(List mining, int max) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); @@ -159,26 +183,57 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe return prune(locs, mining, max); } - public List prune(List locs, List mining, int max) { - BlockPos playerFeet = MineBehavior.INSTANCE.playerFeet(); - locs.sort(Comparator.comparingDouble(playerFeet::distanceSq)); + public void addNearby() { + BlockPos playerFeet = playerFeet(); + int searchDist = 4;//why four? idk + for (int x = playerFeet.getX() - searchDist; x <= playerFeet.getX() + searchDist; x++) { + for (int y = playerFeet.getY() - searchDist; y <= playerFeet.getY() + searchDist; y++) { + for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) { + BlockPos pos = new BlockPos(x, y, z); + if (mining.contains(BlockStateInterface.getBlock(pos))) { + if (RotationUtils.reachable(player(), pos).isPresent()) {//crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught + knownOreLocations.add(pos); + } + } + } + } + } + knownOreLocations = prune(knownOreLocations, mining, 64); + } + + public static List prune(List locs2, List mining, int max) { + List locs = locs2 + .stream() + + // remove any that are within loaded chunks that aren't actually what we want + .filter(pos -> MineBehavior.INSTANCE.world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock())) + + // remove any that are implausible to mine (encased in bedrock, or touching lava) + .filter(MineBehavior::plausibleToBreak) + + .sorted(Comparator.comparingDouble(Helper.HELPER.playerFeet()::distanceSq)) + .collect(Collectors.toList()); - // remove any that are within loaded chunks that aren't actually what we want - locs.removeAll(locs.stream() - .filter(pos -> !(MineBehavior.INSTANCE.world().getChunk(pos) instanceof EmptyChunk)) - .filter(pos -> !mining.contains(BlockStateInterface.get(pos).getBlock())) - .collect(Collectors.toList())); if (locs.size() > max) { return locs.subList(0, max); } return locs; } + public static boolean plausibleToBreak(BlockPos pos) { + if (MovementHelper.avoidBreaking(pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(pos))) { + return false; + } + // bedrock above and below makes it implausible, otherwise we're good + return !(BlockStateInterface.getBlock(pos.up()) == Blocks.BEDROCK && BlockStateInterface.getBlock(pos.down()) == Blocks.BEDROCK); + } + @Override public void mine(int quantity, String... blocks) { this.mining = blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlock).collect(Collectors.toList()); this.desiredQuantity = quantity; this.knownOreLocations = new ArrayList<>(); + this.branchPoint = null; rescan(); updateGoal(); } @@ -188,6 +243,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe this.mining = blocks == null || blocks.length == 0 ? null : Arrays.asList(blocks); this.desiredQuantity = quantity; this.knownOreLocations = new ArrayList<>(); + this.branchPoint = null; rescan(); updateGoal(); } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 869aac1f..f1899333 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -201,6 +201,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, this.goal = goal; } + public boolean setGoalAndPath(Goal goal) { + setGoal(goal); + return path(); + } + @Override public Goal getGoal() { return goal; From 4e1491a0ccad53791b85778608b9667990975cb2 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 26 Oct 2018 13:30:16 -0500 Subject: [PATCH 201/305] Rename xrayFor to searchWorld --- src/main/java/baritone/behavior/MineBehavior.java | 4 ++-- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index 81a18ef7..bdc44320 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -129,7 +129,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe if (Baritone.settings().legitMine.get()) { return; } - List locs = xrayFor(mining, 64); + List locs = searchWorld(mining, 64); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); mine(0, (String[]) null); @@ -160,7 +160,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe } } - public List xrayFor(List mining, int max) { + public List searchWorld(List mining, int max) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); //long b = System.currentTimeMillis(); diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 77132e82..f1f70c77 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -382,7 +382,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } else { - List locs = MineBehavior.INSTANCE.xrayFor(Collections.singletonList(block), 64); + List locs = MineBehavior.INSTANCE.searchWorld(Collections.singletonList(block), 64); if (locs.isEmpty()) { logDirect("No locations for " + mining + " known, cancelling"); return true; From 6df05f4b7f767133085d6a4363edafc7d003ea74 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 26 Oct 2018 20:04:12 -0700 Subject: [PATCH 202/305] add link to my vid --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 588a90c9..caf49113 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). -Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. +Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. Here are some links to help to get started: From ef8fd7047593e38db65d893a37fa4c056ced62b4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 27 Oct 2018 09:25:53 -0700 Subject: [PATCH 203/305] add some more badges for no reason lol --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index caf49113..2cabfd77 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@ [![Release](https://img.shields.io/github/release/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/releases) [![License](https://img.shields.io/github/license/cabaletta/baritone.svg)](LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) +[![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) +[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). From 19e0e6d962de7fb07c11ed6bb404ab57062b9ffb Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 27 Oct 2018 14:37:49 -0500 Subject: [PATCH 204/305] Feed codacy --- .../main/java/baritone/gradle/task/BaritoneGradleTask.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java index 22dac86e..7c724c9b 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java @@ -57,7 +57,7 @@ class BaritoneGradleTask extends DefaultTask { String artifactName, artifactVersion; Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut; - void verifyArtifacts() throws Exception { + void verifyArtifacts() throws IllegalStateException { this.artifactName = getProject().getName(); this.artifactVersion = getProject().getVersion().toString(); @@ -69,7 +69,7 @@ class BaritoneGradleTask extends DefaultTask { this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH); if (!Files.exists(this.artifactPath)) { - throw new Exception("Artifact not found! Run build first!"); + throw new IllegalStateException("Artifact not found! Run build first!"); } } From 8cee173f92c93986bc6b80dd458832f89b00bd4d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 27 Oct 2018 14:16:34 -0700 Subject: [PATCH 205/305] appease codacy some more --- .../gradle/task/BaritoneGradleTask.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java index 7c724c9b..0450509f 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java @@ -34,9 +34,9 @@ import java.util.List; */ class BaritoneGradleTask extends DefaultTask { - static final JsonParser PARSER = new JsonParser(); + protected static final JsonParser PARSER = new JsonParser(); - static final String + protected static final String PROGUARD_ZIP = "proguard.zip", PROGUARD_JAR = "proguard.jar", PROGUARD_CONFIG_TEMPLATE = "scripts/proguard.pro", @@ -54,10 +54,10 @@ class BaritoneGradleTask extends DefaultTask { ARTIFACT_API = "%s-api-%s.jar", ARTIFACT_STANDALONE = "%s-standalone-%s.jar"; - String artifactName, artifactVersion; - Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut; + protected String artifactName, artifactVersion; + protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut; - void verifyArtifacts() throws IllegalStateException { + protected void verifyArtifacts() throws IllegalStateException { this.artifactName = getProject().getName(); this.artifactVersion = getProject().getVersion().toString(); @@ -73,30 +73,30 @@ class BaritoneGradleTask extends DefaultTask { } } - void write(InputStream stream, Path file) throws Exception { + protected void write(InputStream stream, Path file) throws Exception { if (Files.exists(file)) { Files.delete(file); } Files.copy(stream, file); } - String formatVersion(String string) { + protected String formatVersion(String string) { return String.format(string, this.artifactName, this.artifactVersion); } - Path getRelativeFile(String file) { + protected Path getRelativeFile(String file) { return Paths.get(new File(file).getAbsolutePath()); } - Path getTemporaryFile(String file) { + protected Path getTemporaryFile(String file) { return Paths.get(new File(getTemporaryDir(), file).getAbsolutePath()); } - Path getBuildFile(String file) { + protected Path getBuildFile(String file) { return getRelativeFile("build/libs/" + file); } - JsonElement readJson(List lines) { + protected JsonElement readJson(List lines) { return PARSER.parse(String.join("\n", lines)); } } From 1dee8ef3550e0c51f4e6f18a780826986b81fd9b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 27 Oct 2018 14:41:25 -0700 Subject: [PATCH 206/305] completely submitting to codacy --- .../baritone/gradle/task/CreateDistTask.java | 2 +- .../baritone/gradle/task/ProguardTask.java | 2 +- .../baritone/api/utils/RotationUtils.java | 6 ++--- .../java/baritone/behavior/MineBehavior.java | 12 +++------ .../baritone/behavior/PathingBehavior.java | 21 ++++++--------- .../pathing/calc/AStarPathFinder.java | 10 +++---- .../movement/movements/MovementAscend.java | 26 ++++++++----------- .../movement/movements/MovementDescend.java | 9 +++---- .../movement/movements/MovementDiagonal.java | 12 +++------ .../movement/movements/MovementPillar.java | 12 +++------ .../movement/movements/MovementTraverse.java | 15 ++++------- .../baritone/pathing/path/PathExecutor.java | 12 +++------ .../utils/ExampleBaritoneControl.java | 22 ++++++---------- 13 files changed, 60 insertions(+), 101 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index 48b83421..49e2e142 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -76,7 +76,7 @@ public class CreateDistTask extends BaritoneGradleTask { return DatatypeConverter.printHexBinary(SHA1_DIGEST.digest(Files.readAllBytes(path))).toLowerCase(); } catch (Exception e) { // haha no thanks - throw new RuntimeException(e); + throw new IllegalStateException(e); } } } diff --git a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java index ce0e3800..350f7446 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java @@ -241,7 +241,7 @@ public class ProguardTask extends BaritoneGradleTask { // Halt the current thread until the process is complete, if the exit code isn't 0, throw an exception int exitCode = p.waitFor(); if (exitCode != 0) { - throw new Exception("Proguard exited with code " + exitCode); + throw new IllegalStateException("Proguard exited with code " + exitCode); } } diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index c7ff3057..a8449dc7 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -220,10 +220,8 @@ public final class RotationUtils { if (result.getBlockPos().equals(pos)) { return Optional.of(rotation); } - if (entity.world.getBlockState(pos).getBlock() instanceof BlockFire) { - if (result.getBlockPos().equals(pos.down())) { - return Optional.of(rotation); - } + if (entity.world.getBlockState(pos).getBlock() instanceof BlockFire && result.getBlockPos().equals(pos.down())) { + return Optional.of(rotation); } } return Optional.empty(); diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index bdc44320..889cb4ff 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -75,10 +75,8 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe } } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); - if (mineGoalUpdateInterval != 0) { - if (event.getCount() % mineGoalUpdateInterval == 0) { - Baritone.INSTANCE.getExecutor().execute(this::rescan); - } + if (mineGoalUpdateInterval != 0 && event.getCount() % mineGoalUpdateInterval == 0) { + Baritone.INSTANCE.getExecutor().execute(this::rescan); } if (Baritone.settings().legitMine.get()) { addNearby(); @@ -190,10 +188,8 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe for (int y = playerFeet.getY() - searchDist; y <= playerFeet.getY() + searchDist; y++) { for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) { BlockPos pos = new BlockPos(x, y, z); - if (mining.contains(BlockStateInterface.getBlock(pos))) { - if (RotationUtils.reachable(player(), pos).isPresent()) {//crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught - knownOreLocations.add(pos); - } + if (mining.contains(BlockStateInterface.getBlock(pos)) && RotationUtils.reachable(player(), pos).isPresent()) {//crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught + knownOreLocations.add(pos); } } } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index f1899333..d626ac4f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -134,19 +134,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return; } // at this point, we know current is in progress - if (safe) { - // a movement just ended - if (next != null) { - if (next.snipsnapifpossible()) { - // jump directly onto the next path - logDebug("Splicing into planned next path early..."); - queuePathEvent(PathEvent.SPLICING_ONTO_NEXT_EARLY); - current = next; - next = null; - current.onTick(); - return; - } - } + if (safe && next != null && next.snipsnapifpossible()) { + // a movement just ended; jump directly onto the next path + logDebug("Splicing into planned next path early..."); + queuePathEvent(PathEvent.SPLICING_ONTO_NEXT_EARLY); + current = next; + next = null; + current.onTick(); + return; } synchronized (pathCalcLock) { if (isPathCalcInProgress) { diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index 020acc34..dfecae2e 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -99,14 +99,12 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel for (Moves moves : Moves.values()) { int newX = currentNode.x + moves.xOffset; int newZ = currentNode.z + moves.zOffset; - if (newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) { + if ((newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) && !BlockStateInterface.isLoaded(newX, newZ)) { // only need to check if the destination is a loaded chunk if it's in a different chunk than the start of the movement - if (!BlockStateInterface.isLoaded(newX, newZ)) { - if (!moves.dynamicXZ) { // only increment the counter if the movement would have gone out of bounds guaranteed - numEmptyChunk++; - } - continue; + if (!moves.dynamicXZ) { // only increment the counter if the movement would have gone out of bounds guaranteed + numEmptyChunk++; } + continue; } if (!moves.dynamicXZ && !worldBorder.entirelyContains(newX, newZ)) { continue; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 52b0c78e..e0d41047 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -97,21 +97,19 @@ public class MovementAscend extends Movement { } } IBlockState srcUp2 = null; - if (BlockStateInterface.get(x, y + 3, z).getBlock() instanceof BlockFalling) {//it would fall on us and possibly suffocate us + if (BlockStateInterface.get(x, y + 3, z).getBlock() instanceof BlockFalling && (MovementHelper.canWalkThrough(x, y + 1, z) || !((srcUp2 = BlockStateInterface.get(x, y + 2, z)).getBlock() instanceof BlockFalling))) {//it would fall on us and possibly suffocate us // HOWEVER, we assume that we're standing in the start position // 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 - if (MovementHelper.canWalkThrough(x, y + 1, z) || !((srcUp2 = BlockStateInterface.get(x, y + 2, z)).getBlock() instanceof BlockFalling)) { - // if the lower one is can't walk through and the upper one is falling, that means that by standing on src - // (the presupposition of this Movement) - // we have necessarily already cleared the entire BlockFalling stack - // on top of our head + // if the lower one is can't walk through and the upper one is falling, that means that by standing on src + // (the presupposition of this Movement) + // we have necessarily already cleared the entire BlockFalling stack + // on top of our head - // as in, if we have a block, then two BlockFallings on top of it - // and that block is x, y+1, z, and we'd have to clear it to even start this movement - // we don't need to worry about those BlockFallings because we've already cleared them - return COST_INF; - } + // as in, if we have a block, then two BlockFallings on top of it + // and that block is x, y+1, z, and we'd have to clear it to even start this movement + // we don't need to worry about those BlockFallings because we've already cleared them + 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 @@ -206,10 +204,8 @@ public class MovementAscend extends Movement { return state.setStatus(MovementStatus.UNREACHABLE); } MovementHelper.moveTowards(state, dest); - if (MovementHelper.isBottomSlab(jumpingOnto)) { - if (!MovementHelper.isBottomSlab(src.down())) { - return state; // don't jump while walking from a non double slab into a bottom slab - } + if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(src.down())) { + return state; // don't jump while walking from a non double slab into a bottom slab } if (Baritone.settings().assumeStep.get()) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index d2e3d306..5fb78d74 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -183,11 +183,10 @@ public class MovementDescend extends Movement { } BlockPos playerFeet = playerFeet(); - if (playerFeet.equals(dest)) { - if (BlockStateInterface.isLiquid(dest) || player().posY - playerFeet.getY() < 0.094) { // lilypads - // Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately - return state.setStatus(MovementStatus.SUCCESS); - }/* else { + if (playerFeet.equals(dest) && (BlockStateInterface.isLiquid(dest) || player().posY - playerFeet.getY() < 0.094)) { // lilypads + // Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately + return state.setStatus(MovementStatus.SUCCESS); + /* else { // System.out.println(player().posY + " " + playerFeet.getY() + " " + (player().posY - playerFeet.getY())); }*/ } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 8ff681c6..19f72fca 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -101,22 +101,18 @@ public class MovementDiagonal extends Movement { return COST_INF; } IBlockState pb3 = BlockStateInterface.get(destX, y + 1, z); - if (optionA == 0) { + if (optionA == 0 && ((MovementHelper.avoidWalkingInto(pb2.getBlock()) && pb2.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb3.getBlock()) && pb3.getBlock() != Blocks.WATER))) { // at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction - if ((MovementHelper.avoidWalkingInto(pb2.getBlock()) && pb2.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb3.getBlock()) && pb3.getBlock() != Blocks.WATER)) { - return COST_INF; - } + return COST_INF; } optionB += MovementHelper.getMiningDurationTicks(context, destX, y + 1, z, pb3, true); if (optionA != 0 && optionB != 0) { // and finally, if the cost is nonzero for both ways to approach this diagonal, it's not possible return COST_INF; } - if (optionB == 0) { + if (optionB == 0 && ((MovementHelper.avoidWalkingInto(pb0.getBlock()) && pb0.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb1.getBlock()) && pb1.getBlock() != Blocks.WATER))) { // and now that option B is fully calculated, see if we can edge around that way - if ((MovementHelper.avoidWalkingInto(pb0.getBlock()) && pb0.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb1.getBlock()) && pb1.getBlock() != Blocks.WATER)) { - return COST_INF; - } + return COST_INF; } boolean water = false; if (BlockStateInterface.isWater(BlockStateInterface.getBlock(x, y, z)) || BlockStateInterface.isWater(destInto.getBlock())) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 62241a2b..c11df54a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -54,16 +54,12 @@ public class MovementPillar extends Movement { if (fromDownDown.getBlock() instanceof BlockLadder || fromDownDown.getBlock() instanceof BlockVine) { return COST_INF; } - if (fromDownDown.getBlock() instanceof BlockSlab) { - if (!((BlockSlab) fromDownDown.getBlock()).isDouble() && fromDownDown.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.BOTTOM) { - return COST_INF; // can't pillar up from a bottom slab onto a non ladder - } + if (fromDownDown.getBlock() instanceof BlockSlab && !((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 (fromDown instanceof BlockVine) { - if (!hasAgainst(x, y, z)) { - return COST_INF; - } + if (fromDown instanceof BlockVine && !hasAgainst(x, y, z)) { + return COST_INF; } IBlockState toBreak = BlockStateInterface.get(x, y + 2, z); Block toBreakBlock = toBreak.getBlock(); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index a71be415..7f9c3902 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -189,11 +189,9 @@ public class MovementTraverse extends Movement { } 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()))) { - return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(positionsToBreak[0])), true)) - .setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); - } + if (isDoorActuallyBlockingUs && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(positionsToBreak[0])), true)) + .setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } } @@ -267,11 +265,8 @@ public class MovementTraverse extends Movement { state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true)); EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; - if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (Minecraft.getMinecraft().player.isSneaking() || Baritone.settings().assumeSafeWalk.get())) { - if (RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { - return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); - } - // wrong side? + if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (Minecraft.getMinecraft().player.isSneaking() || Baritone.settings().assumeSafeWalk.get()) && RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { + return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } //System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 045cdab9..ac48a8db 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -427,15 +427,11 @@ public class PathExecutor implements IPathExecutor, Helper { } private static boolean canSprintInto(IMovement current, IMovement next) { - if (next instanceof MovementDescend) { - if (next.getDirection().equals(current.getDirection())) { - return true; - } + if (next instanceof MovementDescend && next.getDirection().equals(current.getDirection())) { + return true; } - if (next instanceof MovementTraverse) { - if (next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(next.getDest().down())) { - return true; - } + if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(next.getDest().down())) { + return true; } if (next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.get()) { return true; diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index f1f70c77..18fe9fb7 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -60,10 +60,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { @Override public void onSendChatMessage(ChatEvent event) { - if (!Baritone.settings().chatControl.get()) { - if (!Baritone.settings().removePrefix.get()) { - return; - } + if (!Baritone.settings().chatControl.get() && !Baritone.settings().removePrefix.get()) { + return; } String msg = event.getMessage(); if (Baritone.settings().prefix.get()) { @@ -77,8 +75,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } - public boolean runCommand(String msg) { - msg = msg.toLowerCase(Locale.US).trim(); + public boolean runCommand(String msg0) { + String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL List> toggleable = Baritone.settings().getAllValuesByType(Boolean.class); for (Settings.Setting setting : toggleable) { if (msg.equalsIgnoreCase(setting.getName())) { @@ -252,10 +250,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } else { for (EntityPlayer pl : world().playerEntities) { String theirName = pl.getName().trim().toLowerCase(); - if (!theirName.equals(player().getName().trim().toLowerCase())) { // don't follow ourselves lol - if (theirName.contains(name) || name.contains(theirName)) { - toFollow = Optional.of(pl); - } + if (!theirName.equals(player().getName().trim().toLowerCase()) && (theirName.contains(name) || name.contains(theirName))) { // don't follow ourselves lol + toFollow = Optional.of(pl); } } } @@ -400,10 +396,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } Goal goal = new GoalBlock(waypoint.getLocation()); PathingBehavior.INSTANCE.setGoal(goal); - if (!PathingBehavior.INSTANCE.path()) { - if (!goal.isInGoal(playerFeet())) { - logDirect("Currently executing a path. Please cancel it first."); - } + if (!PathingBehavior.INSTANCE.path() && !goal.isInGoal(playerFeet())) { + logDirect("Currently executing a path. Please cancel it first."); } return true; } From c4b0e0a81052a4acbffffd089f39781f87bac1ed Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 27 Oct 2018 16:18:03 -0700 Subject: [PATCH 207/305] codady submission complete --- src/main/java/baritone/cache/CachedChunk.java | 70 ++++++++++--------- .../pathing/movement/CalculationContext.java | 5 +- .../pathing/movement/MovementHelper.java | 7 +- .../baritone/pathing/path/PathExecutor.java | 10 +-- 4 files changed, 42 insertions(+), 50 deletions(-) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 8d2188b5..6daf2c67 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -33,41 +33,45 @@ import java.util.*; */ public final class CachedChunk implements IBlockTypeAccess, Helper { - public static final Set BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(new HashSet() {{ - 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); + public static final Set BLOCKS_TO_KEEP_TRACK_OF; - add(Blocks.ENDER_CHEST); - add(Blocks.FURNACE); - add(Blocks.CHEST); - add(Blocks.TRAPPED_CHEST); - add(Blocks.END_PORTAL); - add(Blocks.END_PORTAL_FRAME); - add(Blocks.MOB_SPAWNER); + static { + HashSet temp = new HashSet<>(); + temp.add(Blocks.DIAMOND_ORE); + temp.add(Blocks.DIAMOND_BLOCK); + //temp.add(Blocks.COAL_ORE); + temp.add(Blocks.COAL_BLOCK); + //temp.add(Blocks.IRON_ORE); + temp.add(Blocks.IRON_BLOCK); + //temp.add(Blocks.GOLD_ORE); + temp.add(Blocks.GOLD_BLOCK); + temp.add(Blocks.EMERALD_ORE); + temp.add(Blocks.EMERALD_BLOCK); + + temp.add(Blocks.ENDER_CHEST); + temp.add(Blocks.FURNACE); + temp.add(Blocks.CHEST); + temp.add(Blocks.TRAPPED_CHEST); + temp.add(Blocks.END_PORTAL); + temp.add(Blocks.END_PORTAL_FRAME); + temp.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); - add(Blocks.WEB); - add(Blocks.NETHER_WART); - }}); + temp.add(Blocks.PORTAL); + temp.add(Blocks.HOPPER); + temp.add(Blocks.BEACON); + temp.add(Blocks.BREWING_STAND); + temp.add(Blocks.SKULL); + temp.add(Blocks.ENCHANTING_TABLE); + temp.add(Blocks.ANVIL); + temp.add(Blocks.LIT_FURNACE); + temp.add(Blocks.BED); + temp.add(Blocks.DRAGON_EGG); + temp.add(Blocks.JUKEBOX); + temp.add(Blocks.END_GATEWAY); + temp.add(Blocks.WEB); + temp.add(Blocks.NETHER_WART); + BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(temp); + } /** * The size of the chunk data in bits. Equal to 16 KiB. diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 9f08d578..00c063af 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -87,10 +87,7 @@ public class CalculationContext implements Helper { if (!allowBreak()) { return false; } - if (isPossiblyProtected(x, y, z)) { - return false; - } - return true; + return !isPossiblyProtected(x, y, z); } public boolean isPossiblyProtected(int x, int y, int z) { diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 9f785052..d887a714 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -226,7 +226,7 @@ public interface MovementHelper extends ActionCosts, Helper { return true; } - return facing == playerFacing == open; + return (facing == playerFacing) == open; } static boolean avoidWalkingInto(Block block) { @@ -295,10 +295,7 @@ public interface MovementHelper extends ActionCosts, Helper { } return true; } - if (block instanceof BlockStairs) { - return true; - } - return false; + return block instanceof BlockStairs; } static boolean canWalkOn(BetterBlockPos pos, IBlockState state) { diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index ac48a8db..e5f9c864 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -326,10 +326,7 @@ public class PathExecutor implements IPathExecutor, Helper { // when we're midair in the middle of a fall, we're very far from both the beginning and the end, but we aren't actually off path if (path.movements().get(pathPosition) instanceof MovementFall) { BlockPos fallDest = path.positions().get(pathPosition + 1); // .get(pathPosition) is the block we fell off of - if (VecUtils.entityFlatDistanceToCenter(player(), fallDest) < leniency) { // ignore Y by using flat distance - return false; - } - return true; + return VecUtils.entityFlatDistanceToCenter(player(), fallDest) >= leniency; // ignore Y by using flat distance } else { return true; } @@ -433,10 +430,7 @@ public class PathExecutor implements IPathExecutor, Helper { if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(next.getDest().down())) { return true; } - if (next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.get()) { - return true; - } - return false; + return next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.get(); } private void onChangeInPathPosition() { From 1b1233d26a7a9a4ac073cafc1586bc38db396cb2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 27 Oct 2018 18:45:17 -0700 Subject: [PATCH 208/305] only one singleton --- .../launch/mixins/MixinMinecraft.java | 5 +- src/main/java/baritone/Baritone.java | 68 +++++++++++++++--- src/main/java/baritone/BaritoneProvider.java | 13 ++-- src/main/java/baritone/behavior/Behavior.java | 8 +++ .../baritone/behavior/FollowBehavior.java | 14 ++-- .../behavior/LocationTrackingBehavior.java | 10 +-- .../java/baritone/behavior/LookBehavior.java | 7 +- .../baritone/behavior/MemoryBehavior.java | 7 +- .../java/baritone/behavior/MineBehavior.java | 22 +++--- .../baritone/behavior/PathingBehavior.java | 6 +- .../baritone/pathing/movement/Movement.java | 3 +- .../java/baritone/utils/BaritoneAutoTest.java | 6 +- .../utils/ExampleBaritoneControl.java | 72 +++++++++---------- 13 files changed, 146 insertions(+), 95 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 19129a5a..30d4109b 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -22,9 +22,7 @@ import baritone.api.event.events.BlockInteractEvent; import baritone.api.event.events.TickEvent; import baritone.api.event.events.WorldEvent; import baritone.api.event.events.type.EventState; -import baritone.behavior.PathingBehavior; import baritone.utils.BaritoneAutoTest; -import baritone.utils.ExampleBaritoneControl; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiScreen; @@ -60,7 +58,6 @@ public class MixinMinecraft { ) private void postInit(CallbackInfo ci) { Baritone.INSTANCE.init(); - ExampleBaritoneControl.INSTANCE.initAndRegister(); } @Inject( @@ -145,7 +142,7 @@ public class MixinMinecraft { ) ) private boolean isAllowUserInput(GuiScreen screen) { - return (PathingBehavior.INSTANCE.getCurrent() != null && PathingBehavior.INSTANCE.isEnabled() && player != null) || screen.allowUserInput; + return (Baritone.INSTANCE.getPathingBehavior().getCurrent() != null && Baritone.INSTANCE.getPathingBehavior().isEnabled() && player != null) || screen.allowUserInput; } @Inject( diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 9b887032..25636ecb 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -18,11 +18,18 @@ package baritone; import baritone.api.BaritoneAPI; +import baritone.api.IBaritoneProvider; import baritone.api.Settings; +import baritone.api.behavior.*; +import baritone.api.cache.IWorldProvider; +import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IGameEventListener; import baritone.behavior.*; +import baritone.cache.WorldProvider; +import baritone.cache.WorldScanner; import baritone.event.GameEventHandler; import baritone.utils.BaritoneAutoTest; +import baritone.utils.ExampleBaritoneControl; import baritone.utils.InputOverrideHandler; import net.minecraft.client.Minecraft; @@ -40,7 +47,7 @@ import java.util.concurrent.TimeUnit; * @author Brady * @since 7/31/2018 10:50 PM */ -public enum Baritone { +public enum Baritone implements IBaritoneProvider { /** * Singleton instance of this class @@ -55,10 +62,17 @@ public enum Baritone { private GameEventHandler gameEventHandler; private InputOverrideHandler inputOverrideHandler; private Settings settings; - private List behaviors; private File dir; private ThreadPoolExecutor threadPool; + private List behaviors; + private PathingBehavior pathingBehavior; + private LookBehavior lookBehavior; + private MemoryBehavior memoryBehavior; + private LocationTrackingBehavior locationTrackingBehavior; + private FollowBehavior followBehavior; + private MineBehavior mineBehavior; + /** * Whether or not Baritone is active */ @@ -81,12 +95,14 @@ public enum Baritone { this.behaviors = new ArrayList<>(); { - registerBehavior(PathingBehavior.INSTANCE); - registerBehavior(LookBehavior.INSTANCE); - registerBehavior(MemoryBehavior.INSTANCE); - registerBehavior(LocationTrackingBehavior.INSTANCE); - registerBehavior(FollowBehavior.INSTANCE); - registerBehavior(MineBehavior.INSTANCE); + // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist + pathingBehavior = new PathingBehavior(this); + lookBehavior = new LookBehavior(this); + memoryBehavior = new MemoryBehavior(this); + locationTrackingBehavior = new LocationTrackingBehavior(this); + followBehavior = new FollowBehavior(this); + mineBehavior = new MineBehavior(this); + new ExampleBaritoneControl(this); } if (BaritoneAutoTest.ENABLE_AUTO_TEST) { registerEventListener(BaritoneAutoTest.INSTANCE); @@ -127,6 +143,42 @@ public enum Baritone { this.registerEventListener(behavior); } + @Override + public IFollowBehavior getFollowBehavior() { + return followBehavior; + } + + @Override + public ILookBehavior getLookBehavior() { + return lookBehavior; + } + + @Override + public IMemoryBehavior getMemoryBehavior() { + return memoryBehavior; + } + + @Override + public IMineBehavior getMineBehavior() { + return mineBehavior; + } + + @Override + public IPathingBehavior getPathingBehavior() { + return pathingBehavior; + } + + @Override + public IWorldProvider getWorldProvider() { + return WorldProvider.INSTANCE; + } + + @Override + public IWorldScanner getWorldScanner() { + return WorldScanner.INSTANCE; + } + + @Override public void registerEventListener(IGameEventListener listener) { this.gameEventHandler.registerEventListener(listener); } diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index d9dfe624..2e9b3b30 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -22,11 +22,12 @@ import baritone.api.behavior.*; import baritone.api.cache.IWorldProvider; import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IGameEventListener; -import baritone.behavior.*; import baritone.cache.WorldProvider; import baritone.cache.WorldScanner; /** + * todo fix this cancer + * * @author Brady * @since 9/29/2018 */ @@ -34,27 +35,27 @@ public final class BaritoneProvider implements IBaritoneProvider { @Override public IFollowBehavior getFollowBehavior() { - return FollowBehavior.INSTANCE; + return Baritone.INSTANCE.getFollowBehavior(); } @Override public ILookBehavior getLookBehavior() { - return LookBehavior.INSTANCE; + return Baritone.INSTANCE.getLookBehavior(); } @Override public IMemoryBehavior getMemoryBehavior() { - return MemoryBehavior.INSTANCE; + return Baritone.INSTANCE.getMemoryBehavior(); } @Override public IMineBehavior getMineBehavior() { - return MineBehavior.INSTANCE; + return Baritone.INSTANCE.getMineBehavior(); } @Override public IPathingBehavior getPathingBehavior() { - return PathingBehavior.INSTANCE; + return Baritone.INSTANCE.getPathingBehavior(); } @Override diff --git a/src/main/java/baritone/behavior/Behavior.java b/src/main/java/baritone/behavior/Behavior.java index b856e423..0f8d8cb7 100644 --- a/src/main/java/baritone/behavior/Behavior.java +++ b/src/main/java/baritone/behavior/Behavior.java @@ -17,6 +17,7 @@ package baritone.behavior; +import baritone.Baritone; import baritone.api.behavior.IBehavior; /** @@ -27,6 +28,13 @@ import baritone.api.behavior.IBehavior; */ public class Behavior implements IBehavior { + public final Baritone baritone; + + protected Behavior(Baritone baritone) { + this.baritone = baritone; + baritone.registerBehavior(this); + } + /** * Whether or not this behavior is enabled */ diff --git a/src/main/java/baritone/behavior/FollowBehavior.java b/src/main/java/baritone/behavior/FollowBehavior.java index 83ca5135..00fbe1c5 100644 --- a/src/main/java/baritone/behavior/FollowBehavior.java +++ b/src/main/java/baritone/behavior/FollowBehavior.java @@ -33,11 +33,11 @@ import net.minecraft.util.math.BlockPos; */ public final class FollowBehavior extends Behavior implements IFollowBehavior, Helper { - public static final FollowBehavior INSTANCE = new FollowBehavior(); - private Entity following; - private FollowBehavior() {} + public FollowBehavior(Baritone baritone) { + super(baritone); + } @Override public void onTick(TickEvent event) { @@ -56,9 +56,9 @@ public final class FollowBehavior extends Behavior implements IFollowBehavior, H GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.get(), Baritone.settings().followOffsetDistance.get()); pos = new BlockPos(g.getX(), following.posY, g.getZ()); } - PathingBehavior.INSTANCE.setGoal(new GoalNear(pos, Baritone.settings().followRadius.get())); - PathingBehavior.INSTANCE.revalidateGoal(); - PathingBehavior.INSTANCE.path(); + baritone.getPathingBehavior().setGoal(new GoalNear(pos, Baritone.settings().followRadius.get())); + ((PathingBehavior) baritone.getPathingBehavior()).revalidateGoal(); + baritone.getPathingBehavior().path(); } @Override @@ -73,7 +73,7 @@ public final class FollowBehavior extends Behavior implements IFollowBehavior, H @Override public void cancel() { - PathingBehavior.INSTANCE.cancel(); + baritone.getPathingBehavior().cancel(); follow(null); } } diff --git a/src/main/java/baritone/behavior/LocationTrackingBehavior.java b/src/main/java/baritone/behavior/LocationTrackingBehavior.java index dee74e79..28c1ee70 100644 --- a/src/main/java/baritone/behavior/LocationTrackingBehavior.java +++ b/src/main/java/baritone/behavior/LocationTrackingBehavior.java @@ -17,6 +17,7 @@ package baritone.behavior; +import baritone.Baritone; import baritone.api.event.events.BlockInteractEvent; import baritone.cache.Waypoint; import baritone.cache.WorldProvider; @@ -28,16 +29,15 @@ 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 + * @see Waypoint * @since 8/22/2018 */ public final class LocationTrackingBehavior extends Behavior implements Helper { - public static final LocationTrackingBehavior INSTANCE = new LocationTrackingBehavior(); - - private LocationTrackingBehavior() {} + public LocationTrackingBehavior(Baritone baritone) { + super(baritone); + } @Override public void onBlockInteract(BlockInteractEvent event) { diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index a42a1e50..ac3a4698 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -26,9 +26,6 @@ import baritone.api.utils.Rotation; import baritone.utils.Helper; public final class LookBehavior extends Behavior implements ILookBehavior, Helper { - - public static final LookBehavior INSTANCE = new LookBehavior(); - /** * Target's values are as follows: *

@@ -49,7 +46,9 @@ public final class LookBehavior extends Behavior implements ILookBehavior, Helpe */ private float lastYaw; - private LookBehavior() {} + public LookBehavior(Baritone baritone) { + super(baritone); + } @Override public void updateTarget(Rotation target, boolean force) { diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index a684556e..08f933f4 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -17,6 +17,7 @@ package baritone.behavior; +import baritone.Baritone; import baritone.api.behavior.IMemoryBehavior; import baritone.api.behavior.memory.IRememberedInventory; import baritone.api.cache.IWorldData; @@ -43,11 +44,11 @@ import java.util.*; */ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, Helper { - public static MemoryBehavior INSTANCE = new MemoryBehavior(); - private final Map worldDataContainers = new HashMap<>(); - private MemoryBehavior() {} + public MemoryBehavior(Baritone baritone) { + super(baritone); + } @Override public synchronized void onPlayerUpdate(PlayerUpdateEvent event) { diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index 889cb4ff..c6683f07 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -46,14 +46,14 @@ import java.util.stream.Collectors; */ public final class MineBehavior extends Behavior implements IMineBehavior, Helper { - public static final MineBehavior INSTANCE = new MineBehavior(); - private List mining; private List knownOreLocations; private BlockPos branchPoint; private int desiredQuantity; - private MineBehavior() {} + public MineBehavior(Baritone baritone) { + super(baritone); + } @Override public void onTick(TickEvent event) { @@ -82,7 +82,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe addNearby(); } updateGoal(); - PathingBehavior.INSTANCE.revalidateGoal(); + ((PathingBehavior) baritone.getPathingBehavior()).revalidateGoal(); } private void updateGoal() { @@ -93,7 +93,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe if (!locs.isEmpty()) { List locs2 = prune(new ArrayList<>(locs), mining, 64); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final - PathingBehavior.INSTANCE.setGoalAndPath(new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new))); + ((PathingBehavior) baritone.getPathingBehavior()).setGoalAndPath(new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new))); knownOreLocations = locs; return; } @@ -104,11 +104,11 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe // only in non-Xray mode (aka legit mode) do we do this if (branchPoint == null) { int y = Baritone.settings().legitMineYLevel.get(); - if (!PathingBehavior.INSTANCE.isPathing() && playerFeet().y == y) { + if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) { // cool, path is over and we are at desired y branchPoint = playerFeet(); } else { - PathingBehavior.INSTANCE.setGoalAndPath(new GoalYLevel(y)); + ((PathingBehavior) baritone.getPathingBehavior()).setGoalAndPath(new GoalYLevel(y)); return; } } @@ -117,7 +117,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe // TODO mine 1x1 shafts to either side branchPoint = branchPoint.north(10); } - PathingBehavior.INSTANCE.setGoalAndPath(new GoalBlock(branchPoint)); + ((PathingBehavior) baritone.getPathingBehavior()).setGoalAndPath(new GoalBlock(branchPoint)); } private void rescan() { @@ -197,12 +197,12 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe knownOreLocations = prune(knownOreLocations, mining, 64); } - public static List prune(List locs2, List mining, int max) { + public List prune(List locs2, List mining, int max) { List locs = locs2 .stream() // remove any that are within loaded chunks that aren't actually what we want - .filter(pos -> MineBehavior.INSTANCE.world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock())) + .filter(pos -> world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock())) // remove any that are implausible to mine (encased in bedrock, or touching lava) .filter(MineBehavior::plausibleToBreak) @@ -247,6 +247,6 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe @Override public void cancel() { mine(0, (String[]) null); - PathingBehavior.INSTANCE.cancel(); + baritone.getPathingBehavior().cancel(); } } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index d626ac4f..a5845146 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -46,8 +46,6 @@ import java.util.stream.Collectors; public final class PathingBehavior extends Behavior implements IPathingBehavior, Helper { - public static final PathingBehavior INSTANCE = new PathingBehavior(); - private PathExecutor current; private PathExecutor next; @@ -62,7 +60,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private final LinkedBlockingQueue toDispatch = new LinkedBlockingQueue<>(); - private PathingBehavior() {} + public PathingBehavior(Baritone baritone) { + super(baritone); + } private void queuePathEvent(PathEvent event) { toDispatch.add(event); diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 450551d4..16ceeefe 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -24,7 +24,6 @@ import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.VecUtils; -import baritone.behavior.LookBehavior; import baritone.utils.BlockBreakHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; @@ -126,7 +125,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { // If the movement target has to force the new rotations, or we aren't using silent move, then force the rotations latestState.getTarget().getRotation().ifPresent(rotation -> - LookBehavior.INSTANCE.updateTarget( + Baritone.INSTANCE.getLookBehavior().updateTarget( rotation, latestState.getTarget().hasToForceRotations())); diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index 1c11c937..70e1a70e 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -17,11 +17,11 @@ package baritone.utils; +import baritone.Baritone; import baritone.api.event.events.TickEvent; import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; -import baritone.behavior.PathingBehavior; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.settings.GameSettings; @@ -105,8 +105,8 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { } // Setup Baritone's pathing goal and (if needed) begin pathing - PathingBehavior.INSTANCE.setGoal(GOAL); - PathingBehavior.INSTANCE.path(); + Baritone.INSTANCE.getPathingBehavior().setGoal(GOAL); + Baritone.INSTANCE.getPathingBehavior().path(); // If we have reached our goal, print a message and safely close the game if (GOAL.isInGoal(playerFeet())) { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 18fe9fb7..e9ebab2d 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -26,7 +26,6 @@ import baritone.api.pathing.movement.ActionCosts; import baritone.api.utils.RayTraceUtils; import baritone.api.utils.SettingsUtil; import baritone.behavior.Behavior; -import baritone.behavior.FollowBehavior; import baritone.behavior.MineBehavior; import baritone.behavior.PathingBehavior; import baritone.cache.ChunkPacker; @@ -48,14 +47,8 @@ import java.util.stream.Stream; public class ExampleBaritoneControl extends Behavior implements Helper { - public static ExampleBaritoneControl INSTANCE = new ExampleBaritoneControl(); - - private ExampleBaritoneControl() { - - } - - public void initAndRegister() { - Baritone.INSTANCE.registerBehavior(this); + public ExampleBaritoneControl(Baritone baritone) { + super(baritone); } @Override @@ -77,6 +70,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { public boolean runCommand(String msg0) { String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL + PathingBehavior pathingBehavior = (PathingBehavior) baritone.getPathingBehavior(); List> toggleable = Baritone.settings().getAllValuesByType(Boolean.class); for (Settings.Setting setting : toggleable) { if (msg.equalsIgnoreCase(setting.getName())) { @@ -158,16 +152,16 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("unable to parse integer " + ex); return true; } - PathingBehavior.INSTANCE.setGoal(goal); + pathingBehavior.setGoal(goal); logDirect("Goal: " + goal); return true; } if (msg.equals("path")) { - if (!PathingBehavior.INSTANCE.path()) { - if (PathingBehavior.INSTANCE.getGoal() == null) { + if (!pathingBehavior.path()) { + if (pathingBehavior.getGoal() == null) { logDirect("No goal."); } else { - if (PathingBehavior.INSTANCE.getGoal().isInGoal(playerFeet())) { + if (pathingBehavior.getGoal().isInGoal(playerFeet())) { logDirect("Already in goal"); } else { logDirect("Currently executing a path. Please cancel it first."); @@ -194,23 +188,23 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("axis")) { - PathingBehavior.INSTANCE.setGoal(new GoalAxis()); - PathingBehavior.INSTANCE.path(); + pathingBehavior.setGoal(new GoalAxis()); + pathingBehavior.path(); return true; } if (msg.equals("cancel") || msg.equals("stop")) { - MineBehavior.INSTANCE.cancel(); - FollowBehavior.INSTANCE.cancel(); - PathingBehavior.INSTANCE.cancel(); + baritone.getMineBehavior().cancel(); + baritone.getFollowBehavior().cancel(); + pathingBehavior.cancel(); logDirect("ok canceled"); return true; } if (msg.equals("forcecancel")) { - MineBehavior.INSTANCE.cancel(); - FollowBehavior.INSTANCE.cancel(); - PathingBehavior.INSTANCE.cancel(); + baritone.getMineBehavior().cancel(); + baritone.getFollowBehavior().cancel(); + pathingBehavior.cancel(); AbstractNodeCostSearch.forceCancel(); - PathingBehavior.INSTANCE.forceCancel(); + pathingBehavior.forceCancel(); logDirect("ok force canceled"); return true; } @@ -220,7 +214,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("invert")) { - Goal goal = PathingBehavior.INSTANCE.getGoal(); + Goal goal = pathingBehavior.getGoal(); BlockPos runAwayFrom; if (goal instanceof GoalXZ) { runAwayFrom = new BlockPos(((GoalXZ) goal).getX(), 0, ((GoalXZ) goal).getZ()); @@ -231,13 +225,13 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Inverting goal of player feet"); runAwayFrom = playerFeet(); } - PathingBehavior.INSTANCE.setGoal(new GoalRunAway(1, runAwayFrom) { + pathingBehavior.setGoal(new GoalRunAway(1, runAwayFrom) { @Override public boolean isInGoal(BlockPos pos) { return false; } }); - if (!PathingBehavior.INSTANCE.path()) { + if (!pathingBehavior.path()) { logDirect("Currently executing a path. Please cancel it first."); } return true; @@ -259,7 +253,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Not found"); return true; } - FollowBehavior.INSTANCE.follow(toFollow.get()); + baritone.getFollowBehavior().follow(toFollow.get()); logDirect("Following " + toFollow.get()); return true; } @@ -291,7 +285,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { int quantity = Integer.parseInt(blockTypes[1]); Block block = ChunkPacker.stringToBlock(blockTypes[0]); Objects.requireNonNull(block); - MineBehavior.INSTANCE.mine(quantity, block); + baritone.getMineBehavior().mine(quantity, block); logDirect("Will mine " + quantity + " " + blockTypes[0]); return true; } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {} @@ -302,14 +296,14 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } - MineBehavior.INSTANCE.mine(0, blockTypes); + baritone.getMineBehavior().mine(0, blockTypes); logDirect("Started mining blocks of type " + Arrays.toString(blockTypes)); return true; } if (msg.startsWith("thisway")) { try { Goal goal = GoalXZ.fromDirection(playerFeetAsVec(), player().rotationYaw, Double.parseDouble(msg.substring(7).trim())); - PathingBehavior.INSTANCE.setGoal(goal); + pathingBehavior.setGoal(goal); logDirect("Goal: " + goal); } catch (NumberFormatException ex) { logDirect("Error unable to parse '" + msg.substring(7).trim() + "' to a double."); @@ -378,13 +372,13 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } else { - List locs = MineBehavior.INSTANCE.searchWorld(Collections.singletonList(block), 64); + List locs = ((MineBehavior) baritone.getMineBehavior()).searchWorld(Collections.singletonList(block), 64); if (locs.isEmpty()) { logDirect("No locations for " + mining + " known, cancelling"); return true; } - PathingBehavior.INSTANCE.setGoal(new GoalComposite(locs.stream().map(GoalGetToBlock::new).toArray(Goal[]::new))); - PathingBehavior.INSTANCE.path(); + pathingBehavior.setGoal(new GoalComposite(locs.stream().map(GoalGetToBlock::new).toArray(Goal[]::new))); + pathingBehavior.path(); return true; } } else { @@ -395,8 +389,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } Goal goal = new GoalBlock(waypoint.getLocation()); - PathingBehavior.INSTANCE.setGoal(goal); - if (!PathingBehavior.INSTANCE.path() && !goal.isInGoal(playerFeet())) { + pathingBehavior.setGoal(goal); + if (!pathingBehavior.path() && !goal.isInGoal(playerFeet())) { logDirect("Currently executing a path. Please cancel it first."); } return true; @@ -408,10 +402,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper { // for some reason the default spawnpoint is underground sometimes Goal goal = new GoalXZ(spawnPoint.getX(), spawnPoint.getZ()); logDirect("spawn not saved, defaulting to world spawn. set goal to " + goal); - PathingBehavior.INSTANCE.setGoal(goal); + pathingBehavior.setGoal(goal); } else { Goal goal = new GoalBlock(waypoint.getLocation()); - PathingBehavior.INSTANCE.setGoal(goal); + pathingBehavior.setGoal(goal); logDirect("Set goal to most recent bed " + goal); } return true; @@ -427,8 +421,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("home not saved"); } else { Goal goal = new GoalBlock(waypoint.getLocation()); - PathingBehavior.INSTANCE.setGoal(goal); - PathingBehavior.INSTANCE.path(); + pathingBehavior.setGoal(goal); + pathingBehavior.path(); logDirect("Going to saved home " + goal); } return true; @@ -451,7 +445,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("pause")) { - boolean enabled = PathingBehavior.INSTANCE.toggle(); + boolean enabled = pathingBehavior.toggle(); logDirect("Pathing Behavior has " + (enabled ? "resumed" : "paused") + "."); return true; } From 3d4a856bb2bc70de87c7bdbc1c0e55f76c454bac Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 27 Oct 2018 23:21:30 -0500 Subject: [PATCH 209/305] Remove unnecessary casts --- src/main/java/baritone/Baritone.java | 14 +++++++------- src/main/java/baritone/behavior/MineBehavior.java | 8 ++++---- .../baritone/utils/ExampleBaritoneControl.java | 4 ++-- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 25636ecb..e8d0b0ea 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -144,37 +144,37 @@ public enum Baritone implements IBaritoneProvider { } @Override - public IFollowBehavior getFollowBehavior() { + public FollowBehavior getFollowBehavior() { return followBehavior; } @Override - public ILookBehavior getLookBehavior() { + public LookBehavior getLookBehavior() { return lookBehavior; } @Override - public IMemoryBehavior getMemoryBehavior() { + public MemoryBehavior getMemoryBehavior() { return memoryBehavior; } @Override - public IMineBehavior getMineBehavior() { + public MineBehavior getMineBehavior() { return mineBehavior; } @Override - public IPathingBehavior getPathingBehavior() { + public PathingBehavior getPathingBehavior() { return pathingBehavior; } @Override - public IWorldProvider getWorldProvider() { + public WorldProvider getWorldProvider() { return WorldProvider.INSTANCE; } @Override - public IWorldScanner getWorldScanner() { + public WorldScanner getWorldScanner() { return WorldScanner.INSTANCE; } diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index c6683f07..d76f0dc1 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -82,7 +82,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe addNearby(); } updateGoal(); - ((PathingBehavior) baritone.getPathingBehavior()).revalidateGoal(); + baritone.getPathingBehavior().revalidateGoal(); } private void updateGoal() { @@ -93,7 +93,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe if (!locs.isEmpty()) { List locs2 = prune(new ArrayList<>(locs), mining, 64); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final - ((PathingBehavior) baritone.getPathingBehavior()).setGoalAndPath(new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new))); + baritone.getPathingBehavior().setGoalAndPath(new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new))); knownOreLocations = locs; return; } @@ -108,7 +108,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe // cool, path is over and we are at desired y branchPoint = playerFeet(); } else { - ((PathingBehavior) baritone.getPathingBehavior()).setGoalAndPath(new GoalYLevel(y)); + baritone.getPathingBehavior().setGoalAndPath(new GoalYLevel(y)); return; } } @@ -117,7 +117,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe // TODO mine 1x1 shafts to either side branchPoint = branchPoint.north(10); } - ((PathingBehavior) baritone.getPathingBehavior()).setGoalAndPath(new GoalBlock(branchPoint)); + baritone.getPathingBehavior().setGoalAndPath(new GoalBlock(branchPoint)); } private void rescan() { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index e9ebab2d..659b454a 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -70,7 +70,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { public boolean runCommand(String msg0) { String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL - PathingBehavior pathingBehavior = (PathingBehavior) baritone.getPathingBehavior(); + PathingBehavior pathingBehavior = baritone.getPathingBehavior(); List> toggleable = Baritone.settings().getAllValuesByType(Boolean.class); for (Settings.Setting setting : toggleable) { if (msg.equalsIgnoreCase(setting.getName())) { @@ -372,7 +372,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } else { - List locs = ((MineBehavior) baritone.getMineBehavior()).searchWorld(Collections.singletonList(block), 64); + List locs = baritone.getMineBehavior().searchWorld(Collections.singletonList(block), 64); if (locs.isEmpty()) { logDirect("No locations for " + mining + " known, cancelling"); return true; From be5df2677b1fe62c2ab0bc3334939743eeee3dfb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 28 Oct 2018 13:55:03 -0700 Subject: [PATCH 210/305] finally add shulkers lol --- src/main/java/baritone/cache/CachedChunk.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 6daf2c67..c554b926 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -55,7 +55,24 @@ public final class CachedChunk implements IBlockTypeAccess, Helper { temp.add(Blocks.END_PORTAL); temp.add(Blocks.END_PORTAL_FRAME); temp.add(Blocks.MOB_SPAWNER); - // TODO add all shulker colors + temp.add(Blocks.BARRIER); + temp.add(Blocks.OBSERVER); + temp.add(Blocks.WHITE_SHULKER_BOX); + temp.add(Blocks.ORANGE_SHULKER_BOX); + temp.add(Blocks.MAGENTA_SHULKER_BOX); + temp.add(Blocks.LIGHT_BLUE_SHULKER_BOX); + temp.add(Blocks.YELLOW_SHULKER_BOX); + temp.add(Blocks.LIME_SHULKER_BOX); + temp.add(Blocks.PINK_SHULKER_BOX); + temp.add(Blocks.GRAY_SHULKER_BOX); + temp.add(Blocks.SILVER_SHULKER_BOX); + temp.add(Blocks.CYAN_SHULKER_BOX); + temp.add(Blocks.PURPLE_SHULKER_BOX); + temp.add(Blocks.BLUE_SHULKER_BOX); + temp.add(Blocks.BROWN_SHULKER_BOX); + temp.add(Blocks.GREEN_SHULKER_BOX); + temp.add(Blocks.RED_SHULKER_BOX); + temp.add(Blocks.BLACK_SHULKER_BOX); temp.add(Blocks.PORTAL); temp.add(Blocks.HOPPER); temp.add(Blocks.BEACON); From f0226f1ea7cb65afdb0c3609d220cb46a656ba9b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 28 Oct 2018 15:23:34 -0700 Subject: [PATCH 211/305] brady doesn't know how to do imports --- src/main/java/baritone/Baritone.java | 3 --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 1 - 2 files changed, 4 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index e8d0b0ea..aae0d63c 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -20,9 +20,6 @@ package baritone; import baritone.api.BaritoneAPI; import baritone.api.IBaritoneProvider; import baritone.api.Settings; -import baritone.api.behavior.*; -import baritone.api.cache.IWorldProvider; -import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IGameEventListener; import baritone.behavior.*; import baritone.cache.WorldProvider; diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 659b454a..978709e0 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -26,7 +26,6 @@ import baritone.api.pathing.movement.ActionCosts; import baritone.api.utils.RayTraceUtils; import baritone.api.utils.SettingsUtil; import baritone.behavior.Behavior; -import baritone.behavior.MineBehavior; import baritone.behavior.PathingBehavior; import baritone.cache.ChunkPacker; import baritone.cache.Waypoint; From adbb03e5cb685050c69b0df6ebd83ecbfd617522 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 28 Oct 2018 15:24:23 -0700 Subject: [PATCH 212/305] unused lol --- src/main/java/baritone/Baritone.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index aae0d63c..18b6798c 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -66,7 +66,6 @@ public enum Baritone implements IBaritoneProvider { private PathingBehavior pathingBehavior; private LookBehavior lookBehavior; private MemoryBehavior memoryBehavior; - private LocationTrackingBehavior locationTrackingBehavior; private FollowBehavior followBehavior; private MineBehavior mineBehavior; @@ -96,7 +95,7 @@ public enum Baritone implements IBaritoneProvider { pathingBehavior = new PathingBehavior(this); lookBehavior = new LookBehavior(this); memoryBehavior = new MemoryBehavior(this); - locationTrackingBehavior = new LocationTrackingBehavior(this); + new LocationTrackingBehavior(this); followBehavior = new FollowBehavior(this); mineBehavior = new MineBehavior(this); new ExampleBaritoneControl(this); From 77db4cd19f6e3ff6412393d13596e3aa882d9957 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 28 Oct 2018 15:24:52 -0700 Subject: [PATCH 213/305] codacy --- src/main/java/baritone/behavior/Behavior.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/behavior/Behavior.java b/src/main/java/baritone/behavior/Behavior.java index 0f8d8cb7..82bde67d 100644 --- a/src/main/java/baritone/behavior/Behavior.java +++ b/src/main/java/baritone/behavior/Behavior.java @@ -29,17 +29,17 @@ import baritone.api.behavior.IBehavior; public class Behavior implements IBehavior { public final Baritone baritone; + + /** + * Whether or not this behavior is enabled + */ + private boolean enabled = true; protected Behavior(Baritone baritone) { this.baritone = baritone; baritone.registerBehavior(this); } - /** - * Whether or not this behavior is enabled - */ - private boolean enabled = true; - /** * Toggles the enabled state of this {@link Behavior}. * From 24d24728dc3c12f41318e55391c33d176fae0cb2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 28 Oct 2018 16:05:08 -0700 Subject: [PATCH 214/305] intellij be like --- src/main/java/baritone/behavior/Behavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/Behavior.java b/src/main/java/baritone/behavior/Behavior.java index 82bde67d..713e98f0 100644 --- a/src/main/java/baritone/behavior/Behavior.java +++ b/src/main/java/baritone/behavior/Behavior.java @@ -29,7 +29,7 @@ import baritone.api.behavior.IBehavior; public class Behavior implements IBehavior { public final Baritone baritone; - + /** * Whether or not this behavior is enabled */ From ed1941abdb7f153b6ca8a3ac5ea946532d72f0e5 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 28 Oct 2018 18:37:21 -0500 Subject: [PATCH 215/305] Fix desynchronized allowFlying state --- .../launch/mixins/MixinEntityPlayerSP.java | 15 +++++++++++++++ .../java/baritone/behavior/PathingBehavior.java | 1 - .../java/baritone/pathing/movement/Movement.java | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index 39bc8af1..dd121ead 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -21,10 +21,13 @@ import baritone.Baritone; import baritone.api.event.events.ChatEvent; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.type.EventState; +import baritone.behavior.PathingBehavior; import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.entity.player.PlayerCapabilities; 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.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /** @@ -72,4 +75,16 @@ public class MixinEntityPlayerSP { private void onPostUpdate(CallbackInfo ci) { Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST)); } + + @Redirect( + method = "onLivingUpdate", + at = @At( + value = "FIELD", + target = "net/minecraft/entity/player/PlayerCapabilities.allowFlying:Z" + ) + ) + private boolean isAllowFlying(PlayerCapabilities capabilities) { + PathingBehavior pathingBehavior = Baritone.INSTANCE.getPathingBehavior(); + return (!pathingBehavior.isEnabled() || !pathingBehavior.isPathing()) && capabilities.allowFlying; + } } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index a5845146..65fa6cd5 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -83,7 +83,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, cancel(); return; } - mc.playerController.setPlayerCapabilities(mc.player); tickPath(); dispatchEvents(); } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 16ceeefe..a2edb2c9 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -114,7 +114,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { */ @Override public MovementStatus update() { - player().capabilities.allowFlying = false; + player().capabilities.isFlying = false; MovementState latestState = updateState(currentState); if (BlockStateInterface.isLiquid(playerFeet())) { latestState.setInput(Input.JUMP, true); From f6043f4ac6fa8856eef485dd88fe8374ad4abb65 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 28 Oct 2018 16:44:47 -0700 Subject: [PATCH 216/305] changed wording --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 978709e0..02c48885 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -349,7 +349,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { name = parts[0]; } WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, Waypoint.Tag.USER, pos)); - logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto user' to set goal, say 'list user' to list."); + logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto " + name + "' to set goal, say 'list user' to list custom waypoints."); return true; } if (msg.startsWith("goto")) { From 19ecb1bbb3640f0cfc5a4c9e5622ab9b2206cb82 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 29 Oct 2018 16:43:03 -0500 Subject: [PATCH 217/305] Merge LocationTrackingBehavior into MemoryBehavior Fixes #242 --- src/main/java/baritone/Baritone.java | 1 - .../behavior/LocationTrackingBehavior.java | 53 ------------------- .../baritone/behavior/MemoryBehavior.java | 16 ++++++ 3 files changed, 16 insertions(+), 54 deletions(-) delete mode 100644 src/main/java/baritone/behavior/LocationTrackingBehavior.java diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 18b6798c..a0d5ba84 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -95,7 +95,6 @@ public enum Baritone implements IBaritoneProvider { pathingBehavior = new PathingBehavior(this); lookBehavior = new LookBehavior(this); memoryBehavior = new MemoryBehavior(this); - new LocationTrackingBehavior(this); followBehavior = new FollowBehavior(this); mineBehavior = new MineBehavior(this); new ExampleBaritoneControl(this); diff --git a/src/main/java/baritone/behavior/LocationTrackingBehavior.java b/src/main/java/baritone/behavior/LocationTrackingBehavior.java deleted file mode 100644 index 28c1ee70..00000000 --- a/src/main/java/baritone/behavior/LocationTrackingBehavior.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.behavior; - -import baritone.Baritone; -import baritone.api.event.events.BlockInteractEvent; -import baritone.cache.Waypoint; -import baritone.cache.WorldProvider; -import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; -import net.minecraft.block.BlockBed; - -/** - * A collection of event methods that are used to interact with Baritone's - * waypoint system. This class probably needs a better name. - * - * @author Brady - * @see Waypoint - * @since 8/22/2018 - */ -public final class LocationTrackingBehavior extends Behavior implements Helper { - - public LocationTrackingBehavior(Baritone baritone) { - super(baritone); - } - - @Override - public void onBlockInteract(BlockInteractEvent event) { - if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(event.getPos()) instanceof BlockBed) { - WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos())); - } - } - - @Override - public void onPlayerDeath() { - WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, playerFeet())); - } -} diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 08f933f4..510cecff 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -21,11 +21,15 @@ import baritone.Baritone; import baritone.api.behavior.IMemoryBehavior; import baritone.api.behavior.memory.IRememberedInventory; import baritone.api.cache.IWorldData; +import baritone.api.event.events.BlockInteractEvent; import baritone.api.event.events.PacketEvent; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.type.EventState; +import baritone.cache.Waypoint; import baritone.cache.WorldProvider; +import baritone.utils.BlockStateInterface; import baritone.utils.Helper; +import net.minecraft.block.BlockBed; import net.minecraft.item.ItemStack; import net.minecraft.network.Packet; import net.minecraft.network.play.client.CPacketCloseWindow; @@ -115,6 +119,18 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H } } + @Override + public void onBlockInteract(BlockInteractEvent event) { + if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(event.getPos()) instanceof BlockBed) { + WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos())); + } + } + + @Override + public void onPlayerDeath() { + WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, playerFeet())); + } + private Optional getInventoryFromWindow(int windowId) { return this.getCurrentContainer().rememberedInventories.values().stream().filter(i -> i.windowId == windowId).findFirst(); } From b9b33b5351cabdb0a372018fda4c596791c89728 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 29 Oct 2018 18:58:52 -0700 Subject: [PATCH 218/305] move calculation context construction to main thread --- src/main/java/baritone/behavior/PathingBehavior.java | 8 +++++--- src/main/java/baritone/pathing/calc/AStarPathFinder.java | 5 +++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 65fa6cd5..d8bf9a1d 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -32,6 +32,7 @@ import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.calc.CutoffPath; +import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.pathing.path.PathExecutor; import baritone.utils.BlockBreakHelper; @@ -325,12 +326,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } isPathCalcInProgress = true; } + CalculationContext context = new CalculationContext(); // not safe to create on the other thread, it looks up a lot of stuff in minecraft Baritone.INSTANCE.getExecutor().execute(() -> { if (talkAboutIt) { logDebug("Starting to search for path from " + start + " to " + goal); } - Optional path = findPath(start, previous); + Optional path = findPath(start, previous, context); if (Baritone.settings().cutoffAtLoadBoundary.get()) { path = path.map(p -> { IPath result = p.cutoffAtLoadedChunks(); @@ -398,7 +400,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * @param start * @return */ - private Optional findPath(BlockPos start, Optional previous) { + private Optional findPath(BlockPos start, Optional previous, CalculationContext context) { Goal goal = this.goal; if (goal == null) { logDebug("no goal"); @@ -428,7 +430,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, favoredPositions = previous.map(IPath::positions).map(Collection::stream).map(x -> x.map(BetterBlockPos::longHash)).map(x -> x.collect(Collectors.toList())).map(HashSet::new); // <-- okay this is EPIC } try { - IPathFinder pf = new AStarPathFinder(start.getX(), start.getY(), start.getZ(), goal, favoredPositions); + IPathFinder pf = new AStarPathFinder(start.getX(), start.getY(), start.getZ(), goal, favoredPositions, context); return pf.calculate(timeout); } catch (Exception e) { logDebug("Pathing exception: " + e); diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index dfecae2e..f9a15e36 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -41,10 +41,12 @@ import java.util.Optional; public final class AStarPathFinder extends AbstractNodeCostSearch implements Helper { private final Optional> favoredPositions; + private final CalculationContext calcContext; - public AStarPathFinder(int startX, int startY, int startZ, Goal goal, Optional> favoredPositions) { + public AStarPathFinder(int startX, int startY, int startZ, Goal goal, Optional> favoredPositions, CalculationContext context) { super(startX, startY, startZ, goal); this.favoredPositions = favoredPositions; + this.calcContext = context; } @Override @@ -61,7 +63,6 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel bestHeuristicSoFar[i] = startNode.estimatedCostToGoal; bestSoFar[i] = startNode; } - CalculationContext calcContext = new CalculationContext(); MutableMoveResult res = new MutableMoveResult(); HashSet favored = favoredPositions.orElse(null); BetterWorldBorder worldBorder = new BetterWorldBorder(world().getWorldBorder()); From 97fd3df8f7b2ae84bacc7e8e202295ddd98654e6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 30 Oct 2018 19:06:42 -0700 Subject: [PATCH 219/305] minecraft version badge --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2cabfd77..5e0ee4bd 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) [![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) +[![Minecraft](https://img.shields.io/badge/MC-1.12.2-brightgreen.svg)](https://minecraft.gamepedia.com/1.12.2) A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). From 8da7406e8fec8d8c24100ee112ee25eb92d3ad9f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 31 Oct 2018 20:37:18 -0700 Subject: [PATCH 220/305] green --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e0ee4bd..f980eaa1 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) [![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) -[![Minecraft](https://img.shields.io/badge/MC-1.12.2-brightgreen.svg)](https://minecraft.gamepedia.com/1.12.2) +[![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). From 20405716bc97587225683144463fdc7350507cbe Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 1 Nov 2018 14:07:08 -0700 Subject: [PATCH 221/305] fix impact 4.4 compatibility and add help message --- .../utils/ExampleBaritoneControl.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 02c48885..4fc09491 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -46,8 +46,41 @@ import java.util.stream.Stream; public class ExampleBaritoneControl extends Behavior implements Helper { + public static ExampleBaritoneControl INSTANCE; // compatibility with impact 4.4 + + private static final String HELP_MSG = + "baritone - Output settings into chat\n" + + "settings - Same as baritone\n" + + "goal - Create a goal (one number is '', two is ' ', three is ' , 'clear' to clear)\n" + + "path - Go towards goal\n" + + "repack - (debug) Repacks chunk cache\n" + + "rescan - (debug) Same as repack\n" + + "axis - Paths towards the closest axis or diagonal axis, at y=120\n" + + "cancel - Cancels current path\n" + + "forcecancel - sudo cancel (only use if very glitched, try toggling 'pause' first)\n" + + "gc - Calls System.gc();\n" + + "invert - Runs away from goal (broken, dont use)\n" + + "follow - Follows a player 'follow username'\n" + + "reloadall - (debug) Reloads chunk cache\n" + + "saveall - (debug) Saves chunk cache\n" + + "find - (debug) outputs how many blocks of a certain type are within the cache\n" + + "mine - Paths to and mines specified blocks 'mine x_ore y_ore ...'\n" + + "thisway - Creates a goal X blocks where you're facing\n" + + "list - Lists waypoints under a category\n" + + "get - Same as list\n" + + "show - Same as list\n" + + "save - Saves a waypoint (works but don't try to make sense of it)\n" + + "goto - Paths towards specified block or waypoint\n" + + "spawn - Paths towards world spawn or your most recent bed right-click\n" + + "sethome - Sets \"home\"\n" + + "home - Paths towards \"home\" \n" + + "costs - (debug) all movement costs from current location\n" + + "pause - Toggle pause\n" + + "damn - Daniel "; + public ExampleBaritoneControl(Baritone baritone) { super(baritone); + INSTANCE = this; } @Override @@ -85,6 +118,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } return true; } + if (msg.equals("") || msg.equals("help") || msg.equals("?")) { + for (String line : HELP_MSG.split("\n")) { + logDirect(line); + } + return false; + } if (msg.contains(" ")) { String[] data = msg.split(" "); if (data.length == 2) { From 0fbfa32e6bc72fae45594e9a3842dbed3bc128c7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 1 Nov 2018 15:30:33 -0700 Subject: [PATCH 222/305] fix exception in pathfinder --- src/main/java/baritone/pathing/calc/AStarPathFinder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index f9a15e36..83830ac0 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -131,7 +131,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel throw new IllegalStateException(moves + " " + res.x + " " + newX + " " + res.z + " " + newZ); } if (!moves.dynamicY && res.y != currentNode.y + moves.yOffset) { - throw new IllegalStateException(moves + " " + res.x + " " + newX + " " + res.z + " " + newZ); + throw new IllegalStateException(moves + " " + res.y + " " + (currentNode.y + moves.yOffset)); } long hashCode = BetterBlockPos.longHash(res.x, res.y, res.z); if (favoring && favored.contains(hashCode)) { From 88e3bcdf637b9493a5dff0f146308f776eb66eba Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 1 Nov 2018 15:32:58 -0700 Subject: [PATCH 223/305] what --- .../java/baritone/pathing/movement/CalculationContext.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 00c063af..ca6936a5 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -48,11 +48,7 @@ public class CalculationContext implements Helper { private final BetterWorldBorder worldBorder; public CalculationContext() { - this(new ToolSet()); - } - - public CalculationContext(ToolSet toolSet) { - this.toolSet = toolSet; + this.toolSet = new ToolSet(); this.hasThrowaway = Baritone.settings().allowPlace.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; From b65a199e54b2f22e6467c4fe88ed5c9eb9db279e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 1 Nov 2018 15:36:32 -0700 Subject: [PATCH 224/305] move all checks from BlockStateInterface to MovementHelper --- .../baritone/pathing/movement/Movement.java | 2 +- .../pathing/movement/MovementHelper.java | 55 +++++++++++++++++-- .../movement/movements/MovementAscend.java | 2 +- .../movement/movements/MovementDescend.java | 4 +- .../movement/movements/MovementDiagonal.java | 8 +-- .../movement/movements/MovementFall.java | 7 +-- .../movement/movements/MovementParkour.java | 2 +- .../movement/movements/MovementPillar.java | 8 +-- .../movement/movements/MovementTraverse.java | 8 +-- .../baritone/utils/BlockStateInterface.java | 44 --------------- 10 files changed, 69 insertions(+), 71 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index a2edb2c9..aacd7f9f 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -116,7 +116,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { public MovementStatus update() { player().capabilities.isFlying = false; MovementState latestState = updateState(currentState); - if (BlockStateInterface.isLiquid(playerFeet())) { + if (MovementHelper.isLiquid(playerFeet())) { latestState.setInput(Input.JUMP, true); } if (player().isEntityInsideOpaqueBlock()) { diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index d887a714..f52d8882 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -105,7 +105,7 @@ public interface MovementHelper extends ActionCosts, Helper { } throw new IllegalStateException(); } - if (BlockStateInterface.isFlowing(state)) { + if (isFlowing(state)) { return false; // Don't walk through flowing liquids } if (block instanceof BlockLiquid) { @@ -254,7 +254,7 @@ public interface MovementHelper extends ActionCosts, Helper { return false; } if (state.isBlockNormalCube()) { - if (BlockStateInterface.isLava(block) || BlockStateInterface.isWater(block)) { + if (isLava(block) || isWater(block)) { throw new IllegalStateException(); } return true; @@ -268,20 +268,20 @@ public interface MovementHelper extends ActionCosts, Helper { if (block == Blocks.ENDER_CHEST || block == Blocks.CHEST) { return true; } - if (BlockStateInterface.isWater(block)) { + if (isWater(block)) { // since this is called literally millions of times per second, the benefit of not allocating millions of useless "pos.up()" // BlockPos s that we'd just garbage collect immediately is actually noticeable. I don't even think its a decrease in readability Block up = BlockStateInterface.get(x, y + 1, z).getBlock(); if (up == Blocks.WATERLILY) { return true; } - if (BlockStateInterface.isFlowing(state) || block == Blocks.FLOWING_WATER) { + if (isFlowing(state) || block == Blocks.FLOWING_WATER) { // the only scenario in which we can walk on flowing water is if it's under still water with jesus off - return BlockStateInterface.isWater(up) && !Baritone.settings().assumeWalkOnWater.get(); + return isWater(up) && !Baritone.settings().assumeWalkOnWater.get(); } // if assumeWalkOnWater is on, we can only walk on water if there isn't water above it // if assumeWalkOnWater is off, we can only walk on water if there is water above it - return BlockStateInterface.isWater(up) ^ Baritone.settings().assumeWalkOnWater.get(); + return isWater(up) ^ Baritone.settings().assumeWalkOnWater.get(); } if (block instanceof BlockGlass || block instanceof BlockStainedGlass) { return true; @@ -444,4 +444,47 @@ public interface MovementHelper extends ActionCosts, Helper { false )).setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); } + + /** + * Returns whether or not the specified block is + * water, regardless of whether or not it is flowing. + * + * @param b The block + * @return Whether or not the block is water + */ + static boolean isWater(Block b) { + return b == Blocks.FLOWING_WATER || b == Blocks.WATER; + } + + /** + * Returns whether or not the block at the specified pos is + * water, regardless of whether or not it is flowing. + * + * @param bp The block pos + * @return Whether or not the block is water + */ + static boolean isWater(BlockPos bp) { + return isWater(BlockStateInterface.getBlock(bp)); + } + + static boolean isLava(Block b) { + return b == Blocks.FLOWING_LAVA || b == Blocks.LAVA; + } + + /** + * Returns whether or not the specified pos has a liquid + * + * @param p The pos + * @return Whether or not the block is a liquid + */ + static boolean isLiquid(BlockPos p) { + return BlockStateInterface.getBlock(p) instanceof BlockLiquid; + } + + static boolean isFlowing(IBlockState state) { + // Will be IFluidState in 1.13 + return state.getBlock() instanceof BlockLiquid + && state.getPropertyKeys().contains(BlockLiquid.LEVEL) + && state.getValue(BlockLiquid.LEVEL) != 0; + } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index e0d41047..cd0744e4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -75,7 +75,7 @@ public class MovementAscend extends Movement { if (!context.canPlaceThrowawayAt(destX, y, destZ)) { return COST_INF; } - if (toPlace.getBlock() != Blocks.AIR && !BlockStateInterface.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y, destZ, toPlace)) { + if (toPlace.getBlock() != Blocks.AIR && !MovementHelper.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y, destZ, toPlace)) { return COST_INF; } // TODO: add ability to place against .down() as well as the cardinal directions diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 5fb78d74..a8874989 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -130,7 +130,7 @@ public class MovementDescend extends Movement { } IBlockState ontoBlock = BlockStateInterface.get(destX, newY, destZ); double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[fallHeight] + frontBreak; - if (ontoBlock.getBlock() == Blocks.WATER && !BlockStateInterface.isFlowing(ontoBlock) && BlockStateInterface.getBlock(destX, newY + 1, destZ) != Blocks.WATERLILY) { // TODO flowing check required here? + if (ontoBlock.getBlock() == Blocks.WATER && !MovementHelper.isFlowing(ontoBlock) && BlockStateInterface.getBlock(destX, newY + 1, destZ) != Blocks.WATERLILY) { // TODO flowing check required here? // lilypads are canWalkThrough, but we can't end a fall that should be broken by water if it's covered by a lilypad // however, don't return impossible in the lilypad scenario, because we could still jump right on it (water that's below a lilypad is canWalkOn so it works) if (Baritone.settings().assumeWalkOnWater.get()) { @@ -183,7 +183,7 @@ public class MovementDescend extends Movement { } BlockPos playerFeet = playerFeet(); - if (playerFeet.equals(dest) && (BlockStateInterface.isLiquid(dest) || player().posY - playerFeet.getY() < 0.094)) { // lilypads + if (playerFeet.equals(dest) && (MovementHelper.isLiquid(dest) || player().posY - playerFeet.getY() < 0.094)) { // lilypads // Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately return state.setStatus(MovementStatus.SUCCESS); /* else { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 19f72fca..9848d671 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -78,11 +78,11 @@ public class MovementDiagonal extends Movement { multiplier += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2; } Block cuttingOver1 = BlockStateInterface.get(x, y - 1, destZ).getBlock(); - if (cuttingOver1 == Blocks.MAGMA || BlockStateInterface.isLava(cuttingOver1)) { + if (cuttingOver1 == Blocks.MAGMA || MovementHelper.isLava(cuttingOver1)) { return COST_INF; } Block cuttingOver2 = BlockStateInterface.get(destX, y - 1, z).getBlock(); - if (cuttingOver2 == Blocks.MAGMA || BlockStateInterface.isLava(cuttingOver2)) { + if (cuttingOver2 == Blocks.MAGMA || MovementHelper.isLava(cuttingOver2)) { return COST_INF; } IBlockState pb0 = BlockStateInterface.get(x, y, destZ); @@ -115,7 +115,7 @@ public class MovementDiagonal extends Movement { return COST_INF; } boolean water = false; - if (BlockStateInterface.isWater(BlockStateInterface.getBlock(x, y, z)) || BlockStateInterface.isWater(destInto.getBlock())) { + if (MovementHelper.isWater(BlockStateInterface.getBlock(x, y, z)) || MovementHelper.isWater(destInto.getBlock())) { // 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 @@ -145,7 +145,7 @@ public class MovementDiagonal extends Movement { state.setStatus(MovementStatus.SUCCESS); return state; } - if (!BlockStateInterface.isLiquid(playerFeet())) { + if (!MovementHelper.isLiquid(playerFeet())) { state.setInput(InputOverrideHandler.Input.SPRINT, true); } MovementHelper.moveTowards(state, dest); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index f7d63f17..8f9feb41 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -25,7 +25,6 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.pathing.movement.MovementState.MovementTarget; -import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.entity.player.InventoryPlayer; @@ -63,7 +62,7 @@ public class MovementFall extends Movement { BlockPos playerFeet = playerFeet(); Rotation targetRotation = null; - if (!BlockStateInterface.isWater(dest) && src.getY() - dest.getY() > Baritone.settings().maxFallHeightNoWater.get() && !playerFeet.equals(dest)) { + if (!MovementHelper.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()) { return state.setStatus(MovementStatus.UNREACHABLE); } @@ -84,8 +83,8 @@ public class MovementFall extends Movement { } else { state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.getBlockPosCenter(dest)), false)); } - if (playerFeet.equals(dest) && (player().posY - playerFeet.getY() < 0.094 || BlockStateInterface.isWater(dest))) { // 0.094 because lilypads - if (BlockStateInterface.isWater(dest)) { + if (playerFeet.equals(dest) && (player().posY - playerFeet.getY() < 0.094 || MovementHelper.isWater(dest))) { // 0.094 because lilypads + if (MovementHelper.isWater(dest)) { if (InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) { player().inventory.currentItem = player().inventory.getSlotFor(STACK_BUCKET_EMPTY); if (player().motionY >= 0) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 825c99f4..dbcf3a59 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -124,7 +124,7 @@ public class MovementParkour extends Movement { if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { return; } - if (toPlace.getBlock() != Blocks.AIR && !BlockStateInterface.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y - 1, destZ, toPlace)) { + if (toPlace.getBlock() != Blocks.AIR && !MovementHelper.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y - 1, destZ, toPlace)) { return; } for (int i = 0; i < 5; i++) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index c11df54a..d85a6b55 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -67,9 +67,9 @@ public class MovementPillar extends Movement { return COST_INF; } Block srcUp = null; - if (BlockStateInterface.isWater(toBreakBlock) && BlockStateInterface.isWater(fromDown)) { + if (MovementHelper.isWater(toBreakBlock) && MovementHelper.isWater(fromDown)) { srcUp = BlockStateInterface.get(x, y + 1, z).getBlock(); - if (BlockStateInterface.isWater(srcUp)) { + if (MovementHelper.isWater(srcUp)) { return LADDER_UP_ONE_COST; } } @@ -144,7 +144,7 @@ public class MovementPillar extends Movement { } IBlockState fromDown = BlockStateInterface.get(src); - if (BlockStateInterface.isWater(fromDown.getBlock()) && BlockStateInterface.isWater(dest)) { + if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(dest)) { // stay centered while swimming up a water column state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.getBlockPosCenter(dest)), false)); Vec3d destCenter = VecUtils.getBlockPosCenter(dest); @@ -240,7 +240,7 @@ public class MovementPillar extends Movement { state.setInput(InputOverrideHandler.Input.SNEAK, true); } } - if (BlockStateInterface.isWater(dest.up())) { + if (MovementHelper.isWater(dest.up())) { return true; } return super.prepared(state); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 7f9c3902..1f56ffe4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -66,7 +66,7 @@ public class MovementTraverse extends Movement { if (MovementHelper.canWalkOn(destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge double WC = WALK_ONE_BLOCK_COST; boolean water = false; - if (BlockStateInterface.isWater(pb0.getBlock()) || BlockStateInterface.isWater(pb1.getBlock())) { + if (MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock())) { WC = context.waterWalkSpeed(); water = true; } else { @@ -101,8 +101,8 @@ public class MovementTraverse extends Movement { return COST_INF; } if (destOn.getBlock().equals(Blocks.AIR) || MovementHelper.isReplacable(destX, y - 1, destZ, destOn)) { - boolean throughWater = BlockStateInterface.isWater(pb0.getBlock()) || BlockStateInterface.isWater(pb1.getBlock()); - if (BlockStateInterface.isWater(destOn.getBlock()) && throughWater) { + boolean throughWater = MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock()); + if (MovementHelper.isWater(destOn.getBlock()) && throughWater) { return COST_INF; } if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { @@ -223,7 +223,7 @@ public class MovementTraverse extends Movement { if (playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } - if (wasTheBridgeBlockAlwaysThere && !BlockStateInterface.isLiquid(playerFeet())) { + if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(playerFeet())) { state.setInput(InputOverrideHandler.Input.SPRINT, true); } Block destDown = BlockStateInterface.get(dest.down()).getBlock(); diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 2c0384b2..7133fa12 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -22,7 +22,6 @@ import baritone.cache.CachedRegion; import baritone.cache.WorldData; import baritone.cache.WorldProvider; import net.minecraft.block.Block; -import net.minecraft.block.BlockLiquid; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; @@ -128,47 +127,4 @@ public class BlockStateInterface implements Helper { public static Block getBlock(int x, int y, int z) { return get(x, y, z).getBlock(); } - - /** - * Returns whether or not the specified block is - * water, regardless of whether or not it is flowing. - * - * @param b The block - * @return Whether or not the block is water - */ - public static boolean isWater(Block b) { - return b == Blocks.FLOWING_WATER || b == Blocks.WATER; - } - - /** - * Returns whether or not the block at the specified pos is - * water, regardless of whether or not it is flowing. - * - * @param bp The block pos - * @return Whether or not the block is water - */ - public static boolean isWater(BlockPos bp) { - return isWater(BlockStateInterface.getBlock(bp)); - } - - public static boolean isLava(Block b) { - return b == Blocks.FLOWING_LAVA || b == Blocks.LAVA; - } - - /** - * Returns whether or not the specified pos has a liquid - * - * @param p The pos - * @return Whether or not the block is a liquid - */ - public static boolean isLiquid(BlockPos p) { - return BlockStateInterface.getBlock(p) instanceof BlockLiquid; - } - - public static boolean isFlowing(IBlockState state) { - // Will be IFluidState in 1.13 - return state.getBlock() instanceof BlockLiquid - && state.getPropertyKeys().contains(BlockLiquid.LEVEL) - && state.getValue(BlockLiquid.LEVEL) != 0; - } } From 42eb86b62462d30eba24382b016a600b893259e5 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 1 Nov 2018 15:41:53 -0700 Subject: [PATCH 225/305] useless check? --- src/main/java/baritone/pathing/movement/MovementHelper.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index f52d8882..0ea254b1 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -254,9 +254,6 @@ public interface MovementHelper extends ActionCosts, Helper { return false; } if (state.isBlockNormalCube()) { - if (isLava(block) || isWater(block)) { - throw new IllegalStateException(); - } return true; } if (block == Blocks.LADDER || (block == Blocks.VINE && Baritone.settings().allowVines.get())) { // TODO reconsider this From 990107a1fa00fbdeb286d77ef3ec5cf5b6662bea Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 1 Nov 2018 20:27:34 -0700 Subject: [PATCH 226/305] simplify --- src/main/java/baritone/behavior/PathingBehavior.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index d8bf9a1d..7a3a16b7 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -406,13 +406,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, logDebug("no goal"); return Optional.empty(); } - if (Baritone.settings().simplifyUnloadedYCoord.get()) { - BlockPos pos = null; - if (goal instanceof IGoalRenderPos) { - pos = ((IGoalRenderPos) goal).getGoalPos(); - } - - if (pos != null && world().getChunk(pos) instanceof EmptyChunk) { + if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) { + BlockPos pos = ((IGoalRenderPos) goal).getGoalPos(); + if (world().getChunk(pos) instanceof EmptyChunk) { logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance"); goal = new GoalXZ(pos.getX(), pos.getZ()); } From da5969c2fd9c86c5ccc64beaef034a13a105e2c2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 1 Nov 2018 20:58:36 -0700 Subject: [PATCH 227/305] shouldnt have taken this long to figure that out --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 4fc09491..a620a86b 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -59,7 +59,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { "cancel - Cancels current path\n" + "forcecancel - sudo cancel (only use if very glitched, try toggling 'pause' first)\n" + "gc - Calls System.gc();\n" + - "invert - Runs away from goal (broken, dont use)\n" + + "invert - Runs away from the goal instead of towards it\n" + "follow - Follows a player 'follow username'\n" + "reloadall - (debug) Reloads chunk cache\n" + "saveall - (debug) Saves chunk cache\n" + @@ -265,7 +265,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } pathingBehavior.setGoal(new GoalRunAway(1, runAwayFrom) { @Override - public boolean isInGoal(BlockPos pos) { + public boolean isInGoal(int x, int y, int z) { return false; } }); From c37a5ba956c8b4fcbe42f58b6ca8b1109af9fc09 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 2 Nov 2018 16:23:57 -0700 Subject: [PATCH 228/305] revamp readme --- README.md | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index f980eaa1..dd7a87cf 100644 --- a/README.md +++ b/README.md @@ -22,29 +22,30 @@ There's also some useful information down below # Setup -## IntelliJ's Gradle UI -- 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 +$ gradlew runClient ``` -Setting up for IntelliJ: +Building Baritone: ``` -$ gradlew setupDecompWorkspace -$ gradlew --refresh-dependencies -$ gradlew genIntellijRuns +$ gradlew build ``` +For example, to replace out Impact 4.4's Baritone build with a customized one, build Baritone as above then copy `dist/baritone-api-$VERSION.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). + +## IntelliJ's Gradle UI +- Open the project in IntelliJ as a Gradle project +- Run the Gradle task `setupDecompWorkspace` +- Run the Gradle task `genIntellijRuns` +- Refresh the Gradle project (or, to be safe, just restart IntelliJ) +- Select the "Minecraft Client" launch config +- In `Edit Configurations...` you may need to select `baritone_launch` for `Use classpath of module:`. + # Chat control [Defined Here](src/main/java/baritone/utils/ExampleBaritoneControl.java) From e017238aca9bbebbf2e5cd8029023ddd6a618400 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 3 Nov 2018 19:41:40 -0700 Subject: [PATCH 229/305] unneeded --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index a620a86b..77dbcef5 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -46,8 +46,6 @@ import java.util.stream.Stream; public class ExampleBaritoneControl extends Behavior implements Helper { - public static ExampleBaritoneControl INSTANCE; // compatibility with impact 4.4 - private static final String HELP_MSG = "baritone - Output settings into chat\n" + "settings - Same as baritone\n" + @@ -80,7 +78,6 @@ public class ExampleBaritoneControl extends Behavior implements Helper { public ExampleBaritoneControl(Baritone baritone) { super(baritone); - INSTANCE = this; } @Override From c614d7ec6a81ff2d23708dfd30e4a497c2304483 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 3 Nov 2018 20:25:09 -0700 Subject: [PATCH 230/305] fix stupid minebehavior bug --- src/main/java/baritone/behavior/MineBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/behavior/MineBehavior.java index d76f0dc1..4d37f5ff 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/behavior/MineBehavior.java @@ -94,7 +94,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe List locs2 = prune(new ArrayList<>(locs), mining, 64); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final baritone.getPathingBehavior().setGoalAndPath(new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new))); - knownOreLocations = locs; + knownOreLocations = locs2; return; } // we don't know any ore locations at the moment From 660efe5e16c769ac73cc1a20c5d8941da6de9b2e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 3 Nov 2018 22:11:52 -0700 Subject: [PATCH 231/305] pathing processes wip --- src/api/java/baritone/api/BaritoneAPI.java | 18 ++- src/api/java/baritone/api/IBaritone.java | 81 ++++++++++++ .../java/baritone/api/IBaritoneProvider.java | 66 +-------- .../java/baritone/api/behavior/IBehavior.java | 3 +- .../api/behavior/IPathingBehavior.java | 21 +-- .../api/pathing/goals/GoalRunAway.java | 23 +++- .../api/process/IBaritoneProcess.java | 47 +++++++ .../api/process/ICustomGoalProcess.java | 31 +++++ .../IFollowProcess.java} | 9 +- .../api/process/IGetToBlockProcess.java | 27 ++++ .../IMineProcess.java} | 20 +-- .../baritone/api/process/PathingCommand.java | 30 +++++ .../api/process/PathingCommandType.java | 27 ++++ .../api/utils/interfaces/Toggleable.java | 54 -------- .../launch/mixins/MixinEntityPlayerSP.java | 2 +- .../launch/mixins/MixinMinecraft.java | 2 +- src/main/java/baritone/Baritone.java | 48 +++++-- src/main/java/baritone/BaritoneProvider.java | 50 +------ src/main/java/baritone/behavior/Behavior.java | 41 ------ .../baritone/behavior/PathingBehavior.java | 30 +---- .../java/baritone/event/GameEventHandler.java | 82 ++---------- .../baritone/process/CustomGoalProcess.java | 65 +++++++++ .../FollowProcess.java} | 42 +++--- .../baritone/process/GetToBlockProcess.java | 82 ++++++++++++ .../MineProcess.java} | 98 +++++++------- .../baritone/utils/BaritoneProcessHelper.java | 53 ++++++++ .../utils/ExampleBaritoneControl.java | 22 ++- .../baritone/utils/PathingControlManager.java | 125 ++++++++++++++++++ 28 files changed, 760 insertions(+), 439 deletions(-) create mode 100644 src/api/java/baritone/api/IBaritone.java create mode 100644 src/api/java/baritone/api/process/IBaritoneProcess.java create mode 100644 src/api/java/baritone/api/process/ICustomGoalProcess.java rename src/api/java/baritone/api/{behavior/IFollowBehavior.java => process/IFollowProcess.java} (85%) create mode 100644 src/api/java/baritone/api/process/IGetToBlockProcess.java rename src/api/java/baritone/api/{behavior/IMineBehavior.java => process/IMineProcess.java} (81%) create mode 100644 src/api/java/baritone/api/process/PathingCommand.java create mode 100644 src/api/java/baritone/api/process/PathingCommandType.java delete mode 100644 src/api/java/baritone/api/utils/interfaces/Toggleable.java create mode 100644 src/main/java/baritone/process/CustomGoalProcess.java rename src/main/java/baritone/{behavior/FollowBehavior.java => process/FollowProcess.java} (66%) create mode 100644 src/main/java/baritone/process/GetToBlockProcess.java rename src/main/java/baritone/{behavior/MineBehavior.java => process/MineProcess.java} (78%) create mode 100644 src/main/java/baritone/utils/BaritoneProcessHelper.java create mode 100644 src/main/java/baritone/utils/PathingControlManager.java diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index 0ffd1e98..bf878d33 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -17,10 +17,14 @@ package baritone.api; -import baritone.api.behavior.*; +import baritone.api.behavior.ILookBehavior; +import baritone.api.behavior.IMemoryBehavior; +import baritone.api.behavior.IPathingBehavior; import baritone.api.cache.IWorldProvider; import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IGameEventListener; +import baritone.api.process.IFollowProcess; +import baritone.api.process.IMineProcess; import baritone.api.utils.SettingsUtil; import java.util.Iterator; @@ -36,20 +40,20 @@ import java.util.ServiceLoader; */ public final class BaritoneAPI { - private static final IBaritoneProvider baritone; + private static final IBaritone baritone; private static final Settings settings; static { ServiceLoader baritoneLoader = ServiceLoader.load(IBaritoneProvider.class); Iterator instances = baritoneLoader.iterator(); - baritone = instances.next(); + baritone = instances.next().getBaritoneForPlayer(null); // PWNAGE settings = new Settings(); SettingsUtil.readAndApply(settings); } - public static IFollowBehavior getFollowBehavior() { - return baritone.getFollowBehavior(); + public static IFollowProcess getFollowProcess() { + return baritone.getFollowProcess(); } public static ILookBehavior getLookBehavior() { @@ -60,8 +64,8 @@ public final class BaritoneAPI { return baritone.getMemoryBehavior(); } - public static IMineBehavior getMineBehavior() { - return baritone.getMineBehavior(); + public static IMineProcess getMineProcess() { + return baritone.getMineProcess(); } public static IPathingBehavior getPathingBehavior() { diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java new file mode 100644 index 00000000..2d1982cd --- /dev/null +++ b/src/api/java/baritone/api/IBaritone.java @@ -0,0 +1,81 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api; + +import baritone.api.behavior.*; +import baritone.api.cache.IWorldProvider; +import baritone.api.cache.IWorldScanner; +import baritone.api.event.listener.IGameEventListener; +import baritone.api.process.IFollowProcess; +import baritone.api.process.IMineProcess; + +/** + * @author Brady + * @since 9/29/2018 + */ +public interface IBaritone { + + /** + * @return The {@link IFollowProcess} instance + * @see IFollowProcess + */ + IFollowProcess getFollowProcess(); + + /** + * @return The {@link ILookBehavior} instance + * @see ILookBehavior + */ + ILookBehavior getLookBehavior(); + + /** + * @return The {@link IMemoryBehavior} instance + * @see IMemoryBehavior + */ + IMemoryBehavior getMemoryBehavior(); + + /** + * @return The {@link IMineProcess} instance + * @see IMineProcess + */ + IMineProcess getMineProcess(); + + /** + * @return The {@link IPathingBehavior} instance + * @see IPathingBehavior + */ + IPathingBehavior getPathingBehavior(); + + /** + * @return The {@link IWorldProvider} instance + * @see IWorldProvider + */ + IWorldProvider getWorldProvider(); + + /** + * @return The {@link IWorldScanner} instance + * @see IWorldScanner + */ + IWorldScanner getWorldScanner(); + + /** + * Registers a {@link IGameEventListener} with Baritone's "event bus". + * + * @param listener The listener + */ + void registerEventListener(IGameEventListener listener); +} diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index 88c4adff..9bd96e7e 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -17,70 +17,8 @@ package baritone.api; -import baritone.api.behavior.*; -import baritone.api.cache.IWorldProvider; -import baritone.api.cache.IWorldScanner; -import baritone.api.event.listener.IGameEventListener; +import net.minecraft.client.entity.EntityPlayerSP; -/** - * @author Brady - * @since 9/29/2018 - */ public interface IBaritoneProvider { - - /** - * @see IFollowBehavior - * - * @return The {@link IFollowBehavior} instance - */ - IFollowBehavior getFollowBehavior(); - - /** - * @see ILookBehavior - * - * @return The {@link ILookBehavior} instance - */ - ILookBehavior getLookBehavior(); - - /** - * @see IMemoryBehavior - * - * @return The {@link IMemoryBehavior} instance - */ - IMemoryBehavior getMemoryBehavior(); - - /** - * @see IMineBehavior - * - * @return The {@link IMineBehavior} instance - */ - IMineBehavior getMineBehavior(); - - /** - * @see IPathingBehavior - * - * @return The {@link IPathingBehavior} instance - */ - IPathingBehavior getPathingBehavior(); - - /** - * @see IWorldProvider - * - * @return The {@link IWorldProvider} instance - */ - IWorldProvider getWorldProvider(); - - /** - * @see IWorldScanner - * - * @return The {@link IWorldScanner} instance - */ - IWorldScanner getWorldScanner(); - - /** - * Registers a {@link IGameEventListener} with Baritone's "event bus". - * - * @param listener The listener - */ - void registerEventListener(IGameEventListener listener); + IBaritone getBaritoneForPlayer(EntityPlayerSP player); // tenor be like } diff --git a/src/api/java/baritone/api/behavior/IBehavior.java b/src/api/java/baritone/api/behavior/IBehavior.java index aee144e2..248148e7 100644 --- a/src/api/java/baritone/api/behavior/IBehavior.java +++ b/src/api/java/baritone/api/behavior/IBehavior.java @@ -18,10 +18,9 @@ package baritone.api.behavior; import baritone.api.event.listener.AbstractGameEventListener; -import baritone.api.utils.interfaces.Toggleable; /** * @author Brady * @since 9/23/2018 */ -public interface IBehavior extends AbstractGameEventListener, Toggleable {} +public interface IBehavior extends AbstractGameEventListener {} diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index 7d88ae59..ced3d861 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -39,35 +39,22 @@ public interface IPathingBehavior extends IBehavior { */ Optional ticksRemainingInSegment(); - /** - * Sets the pathing goal. - * - * @param goal The pathing goal - */ - void setGoal(Goal goal); - /** * @return The current pathing goal */ Goal getGoal(); - /** - * Begins pathing. Calculation will start in a new thread, and once completed, - * movement will commence. Returns whether or not the operation was successful. - * - * @return Whether or not the operation was successful - */ - boolean path(); - /** * @return Whether or not a path is currently being executed. */ boolean isPathing(); /** - * Cancels the pathing behavior or the current path calculation. + * Cancels the pathing behavior or the current path calculation. Also cancels all processes that could be controlling path. + *

+ * Basically, "MAKE IT STOP". */ - void cancel(); + void cancelEverything(); /** * Returns the current path, from the current path executor, if there is one. diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index cb7a000e..d01f6eee 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -20,6 +20,7 @@ package baritone.api.pathing.goals; import net.minecraft.util.math.BlockPos; import java.util.Arrays; +import java.util.Optional; /** * Useful for automated combat (retreating specifically) @@ -32,16 +33,26 @@ public class GoalRunAway implements Goal { private final double distanceSq; + private final Optional maintainY; + public GoalRunAway(double distance, BlockPos... from) { + this(distance, Optional.empty(), from); + } + + public GoalRunAway(double distance, Optional maintainY, BlockPos... from) { if (from.length == 0) { throw new IllegalArgumentException(); } this.from = from; this.distanceSq = distance * distance; + this.maintainY = maintainY; } @Override public boolean isInGoal(int x, int y, int z) { + if (maintainY.isPresent() && maintainY.get() != y) { + return false; + } for (BlockPos p : from) { int diffX = x - p.getX(); int diffZ = z - p.getZ(); @@ -62,11 +73,19 @@ public class GoalRunAway implements Goal { min = h; } } - return -min; + min = -min; + if (maintainY.isPresent()) { + min += GoalYLevel.calculate(maintainY.get(), y); + } + return min; } @Override public String toString() { - return "GoalRunAwayFrom" + Arrays.asList(from); + if (maintainY.isPresent()) { + return "GoalRunAwayFromMaintainY y=" + maintainY.get() + ", " + Arrays.asList(from); + } else { + return "GoalRunAwayFrom" + Arrays.asList(from); + } } } diff --git a/src/api/java/baritone/api/process/IBaritoneProcess.java b/src/api/java/baritone/api/process/IBaritoneProcess.java new file mode 100644 index 00000000..6405be94 --- /dev/null +++ b/src/api/java/baritone/api/process/IBaritoneProcess.java @@ -0,0 +1,47 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.process; + +import baritone.api.IBaritone; + +/** + * A process that can control the PathingBehavior. + *

+ * Differences between a baritone process and a behavior: + * Only one baritone process can be active at a time + * PathingBehavior can only be controlled by a process + *

+ * That's it actually + * + * @author leijurv + */ +public interface IBaritoneProcess { + // javadocs small brain, // comment large brain + + boolean isActive(); // would you like to be in control? + + PathingCommand onTick(); // you're in control, what should baritone do? + + boolean isTemporary(); // CombatPauserProcess should return isTemporary true always, and isActive true only when something is in range + + void onLostControl(); // called if isActive returned true, but another non-temporary process has control. effectively the same as cancel. + + double priority(); // tenor be like + + IBaritone associatedWith(); // which bot is this associated with (5000000iq forward thinking) +} diff --git a/src/api/java/baritone/api/process/ICustomGoalProcess.java b/src/api/java/baritone/api/process/ICustomGoalProcess.java new file mode 100644 index 00000000..c3492df9 --- /dev/null +++ b/src/api/java/baritone/api/process/ICustomGoalProcess.java @@ -0,0 +1,31 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.process; + +import baritone.api.pathing.goals.Goal; + +public interface ICustomGoalProcess extends IBaritoneProcess { + void setGoal(Goal goal); + + void path(); + + default void setGoalAndPath(Goal goal) { + setGoal(goal); + path(); + } +} diff --git a/src/api/java/baritone/api/behavior/IFollowBehavior.java b/src/api/java/baritone/api/process/IFollowProcess.java similarity index 85% rename from src/api/java/baritone/api/behavior/IFollowBehavior.java rename to src/api/java/baritone/api/process/IFollowProcess.java index c960fab3..262ce43f 100644 --- a/src/api/java/baritone/api/behavior/IFollowBehavior.java +++ b/src/api/java/baritone/api/process/IFollowProcess.java @@ -15,15 +15,16 @@ * along with Baritone. If not, see . */ -package baritone.api.behavior; +package baritone.api.process; +import baritone.api.process.IBaritoneProcess; import net.minecraft.entity.Entity; /** * @author Brady * @since 9/23/2018 */ -public interface IFollowBehavior extends IBehavior { +public interface IFollowProcess extends IBaritoneProcess { /** * Set the follow target to the specified entity; @@ -40,5 +41,7 @@ public interface IFollowBehavior extends IBehavior { /** * Cancels the follow behavior, this will clear the current follow target. */ - void cancel(); + default void cancel() { + onLostControl(); + } } diff --git a/src/api/java/baritone/api/process/IGetToBlockProcess.java b/src/api/java/baritone/api/process/IGetToBlockProcess.java new file mode 100644 index 00000000..feaeb747 --- /dev/null +++ b/src/api/java/baritone/api/process/IGetToBlockProcess.java @@ -0,0 +1,27 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.process; + +import net.minecraft.block.Block; + +/** + * but it rescans the world every once in a while so it doesn't get fooled by its cache + */ +public interface IGetToBlockProcess extends IBaritoneProcess { + void getToBlock(Block block); +} diff --git a/src/api/java/baritone/api/behavior/IMineBehavior.java b/src/api/java/baritone/api/process/IMineProcess.java similarity index 81% rename from src/api/java/baritone/api/behavior/IMineBehavior.java rename to src/api/java/baritone/api/process/IMineProcess.java index 78ab6d6a..7ebabc9c 100644 --- a/src/api/java/baritone/api/behavior/IMineBehavior.java +++ b/src/api/java/baritone/api/process/IMineProcess.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.behavior; +package baritone.api.process; import net.minecraft.block.Block; @@ -23,7 +23,7 @@ import net.minecraft.block.Block; * @author Brady * @since 9/23/2018 */ -public interface IMineBehavior extends IBehavior { +public interface IMineProcess extends IBaritoneProcess { /** * Begin to search for and mine the specified blocks until @@ -31,9 +31,9 @@ public interface IMineBehavior extends IBehavior { * are mined. This is based on the first target block to mine. * * @param quantity The number of items to get from blocks mined - * @param blocks The blocks to mine + * @param blocks The blocks to mine */ - void mine(int quantity, String... blocks); + void mineByName(int quantity, String... blocks); /** * Begin to search for and mine the specified blocks until @@ -41,7 +41,7 @@ public interface IMineBehavior extends IBehavior { * are mined. This is based on the first target block to mine. * * @param quantity The number of items to get from blocks mined - * @param blocks The blocks to mine + * @param blocks The blocks to mine */ void mine(int quantity, Block... blocks); @@ -50,8 +50,8 @@ public interface IMineBehavior extends IBehavior { * * @param blocks The blocks to mine */ - default void mine(String... blocks) { - this.mine(0, blocks); + default void mineByName(String... blocks) { + mineByName(0, blocks); } /** @@ -60,11 +60,13 @@ public interface IMineBehavior extends IBehavior { * @param blocks The blocks to mine */ default void mine(Block... blocks) { - this.mine(0, blocks); + mine(0, blocks); } /** * Cancels the current mining task */ - void cancel(); + default void cancel() { + onLostControl(); + } } diff --git a/src/api/java/baritone/api/process/PathingCommand.java b/src/api/java/baritone/api/process/PathingCommand.java new file mode 100644 index 00000000..f5b39501 --- /dev/null +++ b/src/api/java/baritone/api/process/PathingCommand.java @@ -0,0 +1,30 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.process; + +import baritone.api.pathing.goals.Goal; + +public class PathingCommand { + public final Goal goal; + public final PathingCommandType commandType; + + public PathingCommand(Goal goal, PathingCommandType commandType) { + this.goal = goal; + this.commandType = commandType; + } +} diff --git a/src/api/java/baritone/api/process/PathingCommandType.java b/src/api/java/baritone/api/process/PathingCommandType.java new file mode 100644 index 00000000..24eaf3a8 --- /dev/null +++ b/src/api/java/baritone/api/process/PathingCommandType.java @@ -0,0 +1,27 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.process; + +public enum PathingCommandType { + SET_GOAL_AND_PATH, // if you do this one with a null goal it should continue + REQUEST_PAUSE, + + // if you do this one with a null goal it should cancel + REVALIDATE_GOAL_AND_PATH, // idkkkkkkk + FORCE_REVALIDATE_GOAL_AND_PATH // idkkkkkkkkkkkkkkkkkkkkkkkk +} diff --git a/src/api/java/baritone/api/utils/interfaces/Toggleable.java b/src/api/java/baritone/api/utils/interfaces/Toggleable.java deleted file mode 100644 index 359d6ee1..00000000 --- a/src/api/java/baritone/api/utils/interfaces/Toggleable.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.api.utils.interfaces; - -/** - * @author Brady - * @since 8/20/2018 - */ -public interface Toggleable { - - /** - * Toggles the enabled state of this {@link Toggleable}. - * - * @return The new state. - */ - boolean toggle(); - - /** - * Sets the enabled state of this {@link Toggleable}. - * - * @return The new state. - */ - boolean setEnabled(boolean enabled); - - /** - * @return Whether or not this {@link Toggleable} object is enabled - */ - boolean isEnabled(); - - /** - * Called when the state changes from disabled to enabled - */ - default void onEnable() {} - - /** - * Called when the state changes from enabled to disabled - */ - default void onDisable() {} -} diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index dd121ead..a180df5c 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -85,6 +85,6 @@ public class MixinEntityPlayerSP { ) private boolean isAllowFlying(PlayerCapabilities capabilities) { PathingBehavior pathingBehavior = Baritone.INSTANCE.getPathingBehavior(); - return (!pathingBehavior.isEnabled() || !pathingBehavior.isPathing()) && capabilities.allowFlying; + return !pathingBehavior.isPathing() && capabilities.allowFlying; } } diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 30d4109b..b559ae86 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -142,7 +142,7 @@ public class MixinMinecraft { ) ) private boolean isAllowUserInput(GuiScreen screen) { - return (Baritone.INSTANCE.getPathingBehavior().getCurrent() != null && Baritone.INSTANCE.getPathingBehavior().isEnabled() && player != null) || screen.allowUserInput; + return (Baritone.INSTANCE.getPathingBehavior().getCurrent() != null && player != null) || screen.allowUserInput; } @Inject( diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index a0d5ba84..055929f0 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -18,16 +18,25 @@ package baritone; import baritone.api.BaritoneAPI; -import baritone.api.IBaritoneProvider; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.event.listener.IGameEventListener; -import baritone.behavior.*; +import baritone.api.process.IBaritoneProcess; +import baritone.behavior.Behavior; +import baritone.behavior.LookBehavior; +import baritone.behavior.MemoryBehavior; +import baritone.behavior.PathingBehavior; import baritone.cache.WorldProvider; import baritone.cache.WorldScanner; import baritone.event.GameEventHandler; +import baritone.process.CustomGoalProcess; +import baritone.process.FollowProcess; +import baritone.process.GetToBlockProcess; +import baritone.process.MineProcess; import baritone.utils.BaritoneAutoTest; import baritone.utils.ExampleBaritoneControl; import baritone.utils.InputOverrideHandler; +import baritone.utils.PathingControlManager; import net.minecraft.client.Minecraft; import java.io.File; @@ -44,7 +53,7 @@ import java.util.concurrent.TimeUnit; * @author Brady * @since 7/31/2018 10:50 PM */ -public enum Baritone implements IBaritoneProvider { +public enum Baritone implements IBaritone { /** * Singleton instance of this class @@ -66,8 +75,13 @@ public enum Baritone implements IBaritoneProvider { private PathingBehavior pathingBehavior; private LookBehavior lookBehavior; private MemoryBehavior memoryBehavior; - private FollowBehavior followBehavior; - private MineBehavior mineBehavior; + + private FollowProcess followProcess; + private MineProcess mineProcess; + private GetToBlockProcess getToBlockProcess; + private CustomGoalProcess customGoalProcess; + + private PathingControlManager pathingControlManager; /** * Whether or not Baritone is active @@ -89,15 +103,19 @@ public enum Baritone implements IBaritoneProvider { // We might want to change this... this.settings = BaritoneAPI.getSettings(); + this.pathingControlManager = new PathingControlManager(this); + this.behaviors = new ArrayList<>(); { // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist pathingBehavior = new PathingBehavior(this); lookBehavior = new LookBehavior(this); memoryBehavior = new MemoryBehavior(this); - followBehavior = new FollowBehavior(this); - mineBehavior = new MineBehavior(this); + followProcess = new FollowProcess(this); + mineProcess = new MineProcess(this); new ExampleBaritoneControl(this); + new CustomGoalProcess(this); // very high iq + new GetToBlockProcess(this); } if (BaritoneAutoTest.ENABLE_AUTO_TEST) { registerEventListener(BaritoneAutoTest.INSTANCE); @@ -113,6 +131,10 @@ public enum Baritone implements IBaritoneProvider { this.initialized = true; } + public PathingControlManager getPathingControlManager() { + return pathingControlManager; + } + public boolean isInitialized() { return this.initialized; } @@ -138,9 +160,13 @@ public enum Baritone implements IBaritoneProvider { this.registerEventListener(behavior); } + public void registerProcess(IBaritoneProcess process) { + + } + @Override - public FollowBehavior getFollowBehavior() { - return followBehavior; + public FollowProcess getFollowProcess() { + return followProcess; } @Override @@ -154,8 +180,8 @@ public enum Baritone implements IBaritoneProvider { } @Override - public MineBehavior getMineBehavior() { - return mineBehavior; + public MineProcess getMineProcess() { + return mineProcess; } @Override diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index 2e9b3b30..a80dfe5e 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -17,59 +17,17 @@ package baritone; +import baritone.api.IBaritone; import baritone.api.IBaritoneProvider; -import baritone.api.behavior.*; -import baritone.api.cache.IWorldProvider; -import baritone.api.cache.IWorldScanner; -import baritone.api.event.listener.IGameEventListener; -import baritone.cache.WorldProvider; -import baritone.cache.WorldScanner; +import net.minecraft.client.entity.EntityPlayerSP; /** - * todo fix this cancer - * * @author Brady * @since 9/29/2018 */ public final class BaritoneProvider implements IBaritoneProvider { - @Override - public IFollowBehavior getFollowBehavior() { - return Baritone.INSTANCE.getFollowBehavior(); - } - - @Override - public ILookBehavior getLookBehavior() { - return Baritone.INSTANCE.getLookBehavior(); - } - - @Override - public IMemoryBehavior getMemoryBehavior() { - return Baritone.INSTANCE.getMemoryBehavior(); - } - - @Override - public IMineBehavior getMineBehavior() { - return Baritone.INSTANCE.getMineBehavior(); - } - - @Override - public IPathingBehavior getPathingBehavior() { - return Baritone.INSTANCE.getPathingBehavior(); - } - - @Override - public IWorldProvider getWorldProvider() { - return WorldProvider.INSTANCE; - } - - @Override - public IWorldScanner getWorldScanner() { - return WorldScanner.INSTANCE; - } - - @Override - public void registerEventListener(IGameEventListener listener) { - Baritone.INSTANCE.registerEventListener(listener); + public IBaritone getBaritoneForPlayer(EntityPlayerSP player) { + return Baritone.INSTANCE; // pwnage } } diff --git a/src/main/java/baritone/behavior/Behavior.java b/src/main/java/baritone/behavior/Behavior.java index 713e98f0..154897d1 100644 --- a/src/main/java/baritone/behavior/Behavior.java +++ b/src/main/java/baritone/behavior/Behavior.java @@ -30,49 +30,8 @@ public class Behavior implements IBehavior { public final Baritone baritone; - /** - * Whether or not this behavior is enabled - */ - private boolean enabled = true; - protected Behavior(Baritone baritone) { this.baritone = baritone; baritone.registerBehavior(this); } - - /** - * Toggles the enabled state of this {@link Behavior}. - * - * @return The new state. - */ - @Override - public final boolean toggle() { - return this.setEnabled(!this.isEnabled()); - } - - /** - * Sets the enabled state of this {@link Behavior}. - * - * @return The new state. - */ - @Override - public final boolean setEnabled(boolean enabled) { - if (enabled == this.enabled) { - return this.enabled; - } - if (this.enabled = enabled) { - this.onEnable(); - } else { - this.onDisable(); - } - return this.enabled; - } - - /** - * @return Whether or not this {@link Behavior} is active. - */ - @Override - public final boolean isEnabled() { - return this.enabled; - } } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 7a3a16b7..1cfd98bd 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -191,7 +191,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return Optional.of(current.getPath().ticksRemainingFrom(current.getPosition())); } - @Override public void setGoal(Goal goal) { this.goal = goal; } @@ -227,6 +226,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } @Override + public void cancelEverything() { + + } + + // just cancel the current path public void cancel() { queuePathEvent(PathEvent.CANCELED); current = null; @@ -245,7 +249,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * * @return true if this call started path calculation, false if it was already calculating or executing a path */ - @Override public boolean path() { if (goal == null) { return false; @@ -435,31 +438,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } } - public void revalidateGoal() { - if (!Baritone.settings().cancelOnGoalInvalidation.get()) { - return; - } - synchronized (pathPlanLock) { - if (current == null || goal == null) { - return; - } - Goal intended = current.getPath().getGoal(); - BlockPos end = current.getPath().getDest(); - if (intended.isInGoal(end) && !goal.isInGoal(end)) { - // this path used to end in the goal - // but the goal has changed, so there's no reason to continue... - cancel(); - } - } - } - @Override public void onRenderPass(RenderEvent event) { PathRenderer.render(event, this); } - - @Override - public void onDisable() { - Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys(); - } } diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 61756e33..e7cd5847 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -21,7 +21,6 @@ import baritone.Baritone; import baritone.api.event.events.*; import baritone.api.event.events.type.EventState; import baritone.api.event.listener.IGameEventListener; -import baritone.api.utils.interfaces.Toggleable; import baritone.cache.WorldProvider; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; @@ -42,20 +41,12 @@ public final class GameEventHandler implements IGameEventListener, Helper { @Override public final void onTick(TickEvent event) { - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onTick(event); - } - }); + listeners.forEach(l -> l.onTick(event)); } @Override public final void onPlayerUpdate(PlayerUpdateEvent event) { - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onPlayerUpdate(event); - } - }); + listeners.forEach(l -> l.onPlayerUpdate(event)); } @Override @@ -75,20 +66,12 @@ public final class GameEventHandler implements IGameEventListener, Helper { } } - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onProcessKeyBinds(); - } - }); + listeners.forEach(l -> l.onProcessKeyBinds()); } @Override public final void onSendChatMessage(ChatEvent event) { - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onSendChatMessage(event); - } - }); + listeners.forEach(l -> l.onSendChatMessage(event)); } @Override @@ -114,20 +97,12 @@ public final class GameEventHandler implements IGameEventListener, Helper { } - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onChunkEvent(event); - } - }); + listeners.forEach(l -> l.onChunkEvent(event)); } @Override public final void onRenderPass(RenderEvent event) { - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onRenderPass(event); - } - }); + listeners.forEach(l -> l.onRenderPass(event)); } @Override @@ -143,72 +118,41 @@ public final class GameEventHandler implements IGameEventListener, Helper { } } - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onWorldEvent(event); - } - }); + listeners.forEach(l -> l.onWorldEvent(event)); } @Override public final void onSendPacket(PacketEvent event) { - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onSendPacket(event); - } - }); + listeners.forEach(l -> l.onSendPacket(event)); } @Override public final void onReceivePacket(PacketEvent event) { - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onReceivePacket(event); - } - }); + listeners.forEach(l -> l.onReceivePacket(event)); } @Override public void onPlayerRotationMove(RotationMoveEvent event) { - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onPlayerRotationMove(event); - } - }); + listeners.forEach(l -> l.onPlayerRotationMove(event)); } @Override public void onBlockInteract(BlockInteractEvent event) { - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onBlockInteract(event); - } - }); + listeners.forEach(l -> l.onBlockInteract(event)); } @Override public void onPlayerDeath() { - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onPlayerDeath(); - } - }); + listeners.forEach(l -> l.onPlayerDeath()); } @Override public void onPathEvent(PathEvent event) { - listeners.forEach(l -> { - if (canDispatch(l)) { - l.onPathEvent(event); - } - }); + listeners.forEach(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(); - } } diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java new file mode 100644 index 00000000..08b142ff --- /dev/null +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -0,0 +1,65 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.process; + +import baritone.Baritone; +import baritone.api.pathing.goals.Goal; +import baritone.api.process.ICustomGoalProcess; +import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.utils.BaritoneProcessHelper; + +/** + * As set by ExampleBaritoneControl or something idk + * + * @author leijurv + */ +public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomGoalProcess { + private Goal goal; + private boolean active; + + public CustomGoalProcess(Baritone baritone) { + super(baritone); + } + + @Override + public void setGoal(Goal goal) { + this.goal = goal; + } + + @Override + public void path() { + active = true; + } + + @Override + public boolean isActive() { + return active; + } + + @Override + public PathingCommand onTick() { + active = false; // only do this once + return new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); + } + + @Override + public void onLostControl() { + active = false; + } +} diff --git a/src/main/java/baritone/behavior/FollowBehavior.java b/src/main/java/baritone/process/FollowProcess.java similarity index 66% rename from src/main/java/baritone/behavior/FollowBehavior.java rename to src/main/java/baritone/process/FollowProcess.java index 00fbe1c5..dcfa21a0 100644 --- a/src/main/java/baritone/behavior/FollowBehavior.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -15,14 +15,15 @@ * along with Baritone. If not, see . */ -package baritone.behavior; +package baritone.process; import baritone.Baritone; -import baritone.api.behavior.IFollowBehavior; -import baritone.api.event.events.TickEvent; +import baritone.api.process.IFollowProcess; import baritone.api.pathing.goals.GoalNear; import baritone.api.pathing.goals.GoalXZ; -import baritone.utils.Helper; +import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.utils.BaritoneProcessHelper; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; @@ -31,23 +32,16 @@ import net.minecraft.util.math.BlockPos; * * @author leijurv */ -public final class FollowBehavior extends Behavior implements IFollowBehavior, Helper { +public final class FollowProcess extends BaritoneProcessHelper implements IFollowProcess { private Entity following; - public FollowBehavior(Baritone baritone) { + public FollowProcess(Baritone baritone) { super(baritone); } @Override - public void onTick(TickEvent event) { - if (event.getType() == TickEvent.Type.OUT) { - following = null; - return; - } - if (following == null) { - return; - } + public PathingCommand onTick() { // lol this is trashy but it works BlockPos pos; if (Baritone.settings().followOffsetDistance.get() == 0) { @@ -56,9 +50,17 @@ public final class FollowBehavior extends Behavior implements IFollowBehavior, H GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.get(), Baritone.settings().followOffsetDistance.get()); pos = new BlockPos(g.getX(), following.posY, g.getZ()); } - baritone.getPathingBehavior().setGoal(new GoalNear(pos, Baritone.settings().followRadius.get())); - ((PathingBehavior) baritone.getPathingBehavior()).revalidateGoal(); - baritone.getPathingBehavior().path(); + return new PathingCommand(new GoalNear(pos, Baritone.settings().followRadius.get()), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); + } + + @Override + public boolean isActive() { + return following != null; + } + + @Override + public void onLostControl() { + following = null; } @Override @@ -70,10 +72,4 @@ public final class FollowBehavior extends Behavior implements IFollowBehavior, H public Entity following() { return this.following; } - - @Override - public void cancel() { - baritone.getPathingBehavior().cancel(); - follow(null); - } } diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java new file mode 100644 index 00000000..62dac26e --- /dev/null +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -0,0 +1,82 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.process; + +import baritone.Baritone; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalComposite; +import baritone.api.pathing.goals.GoalGetToBlock; +import baritone.api.process.IGetToBlockProcess; +import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.utils.BaritoneProcessHelper; +import net.minecraft.block.Block; +import net.minecraft.util.math.BlockPos; + +import java.util.Collections; +import java.util.List; + +public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess { + Block gettingTo; + List knownLocations; + + int tickCount = 0; + + public GetToBlockProcess(Baritone baritone) { + super(baritone); + } + + @Override + public void getToBlock(Block block) { + gettingTo = block; + rescan(); + } + + @Override + public boolean isActive() { + return gettingTo != null; + } + + @Override + public PathingCommand onTick() { + if (knownLocations == null) { + rescan(); + } + if (knownLocations.isEmpty()) { + logDirect("No known locations of " + gettingTo); + onLostControl(); + return null; + } + int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); + if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain + Baritone.INSTANCE.getExecutor().execute(this::rescan); + } + Goal goal = new GoalComposite(knownLocations.stream().map(GoalGetToBlock::new).toArray(Goal[]::new)); + return new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); + } + + @Override + public void onLostControl() { + gettingTo = null; + knownLocations = null; + } + + private void rescan() { + knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64); + } +} \ No newline at end of file diff --git a/src/main/java/baritone/behavior/MineBehavior.java b/src/main/java/baritone/process/MineProcess.java similarity index 78% rename from src/main/java/baritone/behavior/MineBehavior.java rename to src/main/java/baritone/process/MineProcess.java index 4d37f5ff..a88fd537 100644 --- a/src/main/java/baritone/behavior/MineBehavior.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -15,18 +15,20 @@ * along with Baritone. If not, see . */ -package baritone.behavior; +package baritone.process; import baritone.Baritone; -import baritone.api.behavior.IMineBehavior; -import baritone.api.event.events.TickEvent; import baritone.api.pathing.goals.*; +import baritone.api.process.IMineProcess; +import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; import baritone.api.utils.RotationUtils; import baritone.cache.CachedChunk; import baritone.cache.ChunkPacker; import baritone.cache.WorldProvider; import baritone.cache.WorldScanner; import baritone.pathing.movement.MovementHelper; +import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import net.minecraft.block.Block; @@ -44,26 +46,27 @@ import java.util.stream.Collectors; * * @author leijurv */ -public final class MineBehavior extends Behavior implements IMineBehavior, Helper { +public final class MineProcess extends BaritoneProcessHelper implements IMineProcess { + + private static final int ORE_LOCATIONS_COUNT = 64; private List mining; private List knownOreLocations; private BlockPos branchPoint; private int desiredQuantity; + private int tickCount; - public MineBehavior(Baritone baritone) { + public MineProcess(Baritone baritone) { super(baritone); } @Override - public void onTick(TickEvent event) { - if (event.getType() == TickEvent.Type.OUT) { - cancel(); - return; - } - if (mining == null) { - return; - } + public boolean isActive() { + return mining != null; + } + + @Override + public PathingCommand onTick() { if (desiredQuantity > 0) { Item item = mining.get(0).getItemDropped(mining.get(0).getDefaultState(), new Random(), 0); int curr = player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum(); @@ -71,45 +74,52 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe if (curr >= desiredQuantity) { logDirect("Have " + curr + " " + item.getItemStackDisplayName(new ItemStack(item, 1))); cancel(); - return; + return null; } } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); - if (mineGoalUpdateInterval != 0 && event.getCount() % mineGoalUpdateInterval == 0) { + if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain Baritone.INSTANCE.getExecutor().execute(this::rescan); } if (Baritone.settings().legitMine.get()) { addNearby(); } - updateGoal(); - baritone.getPathingBehavior().revalidateGoal(); + Goal goal = updateGoal(); + if (goal == null) { + // none in range + // maybe say something in chat? (ahem impact) + cancel(); + return null; + } + return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH); } - private void updateGoal() { - if (mining == null) { - return; - } + @Override + public void onLostControl() { + mine(0, (Block[]) null); + } + + private Goal updateGoal() { List locs = knownOreLocations; if (!locs.isEmpty()) { - List locs2 = prune(new ArrayList<>(locs), mining, 64); + List locs2 = prune(new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final - baritone.getPathingBehavior().setGoalAndPath(new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new))); + Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new)); knownOreLocations = locs2; - return; + return goal; } // we don't know any ore locations at the moment if (!Baritone.settings().legitMine.get()) { - return; + return null; } // only in non-Xray mode (aka legit mode) do we do this if (branchPoint == null) { int y = Baritone.settings().legitMineYLevel.get(); - if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) { + if (!associatedWith().getPathingBehavior().isPathing() && playerFeet().y == y) { // cool, path is over and we are at desired y branchPoint = playerFeet(); } else { - baritone.getPathingBehavior().setGoalAndPath(new GoalYLevel(y)); - return; + return new GoalYLevel(y); } } @@ -117,7 +127,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe // TODO mine 1x1 shafts to either side branchPoint = branchPoint.north(10); } - baritone.getPathingBehavior().setGoalAndPath(new GoalBlock(branchPoint)); + return new GoalBlock(branchPoint); } private void rescan() { @@ -127,10 +137,10 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe if (Baritone.settings().legitMine.get()) { return; } - List locs = searchWorld(mining, 64); + List locs = searchWorld(mining, ORE_LOCATIONS_COUNT); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); - mine(0, (String[]) null); + cancel(); return; } knownOreLocations = locs; @@ -158,7 +168,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe } } - public List searchWorld(List mining, int max) { + public static List searchWorld(List mining, int max) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); //long b = System.currentTimeMillis(); @@ -194,18 +204,18 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe } } } - knownOreLocations = prune(knownOreLocations, mining, 64); + knownOreLocations = prune(knownOreLocations, mining, ORE_LOCATIONS_COUNT); } - public List prune(List locs2, List mining, int max) { + public static List prune(List locs2, List mining, int max) { List locs = locs2 .stream() // remove any that are within loaded chunks that aren't actually what we want - .filter(pos -> world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock())) + .filter(pos -> Helper.HELPER.world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock())) // remove any that are implausible to mine (encased in bedrock, or touching lava) - .filter(MineBehavior::plausibleToBreak) + .filter(MineProcess::plausibleToBreak) .sorted(Comparator.comparingDouble(Helper.HELPER.playerFeet()::distanceSq)) .collect(Collectors.toList()); @@ -225,13 +235,8 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe } @Override - public void mine(int quantity, String... blocks) { - this.mining = blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlock).collect(Collectors.toList()); - this.desiredQuantity = quantity; - this.knownOreLocations = new ArrayList<>(); - this.branchPoint = null; - rescan(); - updateGoal(); + public void mineByName(int quantity, String... blocks) { + mine(quantity, blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlock).toArray(Block[]::new)); } @Override @@ -241,12 +246,5 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe this.knownOreLocations = new ArrayList<>(); this.branchPoint = null; rescan(); - updateGoal(); - } - - @Override - public void cancel() { - mine(0, (String[]) null); - baritone.getPathingBehavior().cancel(); } } diff --git a/src/main/java/baritone/utils/BaritoneProcessHelper.java b/src/main/java/baritone/utils/BaritoneProcessHelper.java new file mode 100644 index 00000000..4ca0fe94 --- /dev/null +++ b/src/main/java/baritone/utils/BaritoneProcessHelper.java @@ -0,0 +1,53 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import baritone.Baritone; +import baritone.api.process.IBaritoneProcess; + +public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper { + public static final double DEFAULT_PRIORITY = 0; + + private final Baritone baritone; + private final double priority; + + public BaritoneProcessHelper(Baritone baritone) { + this(baritone, DEFAULT_PRIORITY); + } + + public BaritoneProcessHelper(Baritone baritone, double priority) { + this.baritone = baritone; + this.priority = priority; + baritone.getPathingControlManager().registerProcess(this); + } + + @Override + public Baritone associatedWith() { + return baritone; + } + + @Override + public boolean isTemporary() { + return false; + } + + @Override + public double priority() { + return priority; + } +} diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 77dbcef5..f461b9a7 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -73,7 +73,6 @@ public class ExampleBaritoneControl extends Behavior implements Helper { "sethome - Sets \"home\"\n" + "home - Paths towards \"home\" \n" + "costs - (debug) all movement costs from current location\n" + - "pause - Toggle pause\n" + "damn - Daniel "; public ExampleBaritoneControl(Baritone baritone) { @@ -228,15 +227,15 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("cancel") || msg.equals("stop")) { - baritone.getMineBehavior().cancel(); - baritone.getFollowBehavior().cancel(); + baritone.getMineProcess().cancel(); + baritone.getFollowProcess().cancel(); pathingBehavior.cancel(); logDirect("ok canceled"); return true; } if (msg.equals("forcecancel")) { - baritone.getMineBehavior().cancel(); - baritone.getFollowBehavior().cancel(); + baritone.getMineProcess().cancel(); + baritone.getFollowProcess().cancel(); pathingBehavior.cancel(); AbstractNodeCostSearch.forceCancel(); pathingBehavior.forceCancel(); @@ -288,7 +287,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Not found"); return true; } - baritone.getFollowBehavior().follow(toFollow.get()); + baritone.getFollowProcess().follow(toFollow.get()); logDirect("Following " + toFollow.get()); return true; } @@ -320,7 +319,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { int quantity = Integer.parseInt(blockTypes[1]); Block block = ChunkPacker.stringToBlock(blockTypes[0]); Objects.requireNonNull(block); - baritone.getMineBehavior().mine(quantity, block); + baritone.getMineProcess().mine(quantity, block); logDirect("Will mine " + quantity + " " + blockTypes[0]); return true; } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {} @@ -331,7 +330,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } - baritone.getMineBehavior().mine(0, blockTypes); + baritone.getMineProcess().mineByName(0, blockTypes); logDirect("Started mining blocks of type " + Arrays.toString(blockTypes)); return true; } @@ -407,7 +406,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } else { - List locs = baritone.getMineBehavior().searchWorld(Collections.singletonList(block), 64); + List locs = baritone.getMineProcess().searchWorld(Collections.singletonList(block), 64); if (locs.isEmpty()) { logDirect("No locations for " + mining + " known, cancelling"); return true; @@ -479,11 +478,6 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } return true; } - if (msg.equals("pause")) { - boolean enabled = pathingBehavior.toggle(); - logDirect("Pathing Behavior has " + (enabled ? "resumed" : "paused") + "."); - return true; - } if (msg.equals("damn")) { logDirect("daniel"); } diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java new file mode 100644 index 00000000..37c17614 --- /dev/null +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -0,0 +1,125 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import baritone.Baritone; +import baritone.api.pathing.goals.Goal; +import baritone.api.process.IBaritoneProcess; +import baritone.api.process.PathingCommand; +import baritone.pathing.path.PathExecutor; +import net.minecraft.util.math.BlockPos; + +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.stream.Collectors; + +public class PathingControlManager { + private final Baritone baritone; + private final HashSet processes; // unGh + + public PathingControlManager(Baritone baritone) { + this.baritone = baritone; + this.processes = new HashSet<>(); + } + + public void registerProcess(IBaritoneProcess process) { + processes.add(process); + } + + public void doTheThingWithTheStuff() { + PathingCommand cmd = doTheStuff(); + if (cmd == null) { + baritone.getPathingBehavior().cancel(); + return; + } + + switch (cmd.commandType) { + case REQUEST_PAUSE: + // idk + // ask pathingbehavior if its safe + case FORCE_REVALIDATE_GOAL_AND_PATH: + if (cmd.goal == null) { + baritone.getPathingBehavior().cancel(); // todo only if its safe + return; + } + // pwnage + baritone.getPathingBehavior().setGoal(cmd.goal); + if (revalidateGoal(cmd.goal)) { + baritone.getPathingBehavior().cancel(); // todo only if its safe + } + case REVALIDATE_GOAL_AND_PATH: + if (cmd.goal == null) { + baritone.getPathingBehavior().cancel(); // todo only if its safe + return; + } + baritone.getPathingBehavior().setGoal(cmd.goal); + if (Baritone.settings().cancelOnGoalInvalidation.get() && revalidateGoal(cmd.goal)) { + baritone.getPathingBehavior().cancel(); // todo only if its safe + } + case SET_GOAL_AND_PATH: + // now this i can do + if (cmd.goal != null) { + baritone.getPathingBehavior().setGoalAndPath(cmd.goal); + } + // breaks are for wusses!!!! + } + } + + public boolean revalidateGoal(Goal newGoal) { + PathExecutor current = baritone.getPathingBehavior().getCurrent(); + if (current != null) { + Goal intended = current.getPath().getGoal(); + BlockPos end = current.getPath().getDest(); + if (intended.isInGoal(end) && !newGoal.isInGoal(end)) { + // this path used to end in the goal + // but the goal has changed, so there's no reason to continue... + return true; + } + } + return false; + } + + + public PathingCommand doTheStuff() { + List inContention = processes.stream().filter(IBaritoneProcess::isActive).sorted(Comparator.comparingDouble(IBaritoneProcess::priority)).collect(Collectors.toList()); + boolean found = false; + boolean cancelOthers = false; + PathingCommand exec = null; + for (int i = inContention.size() - 1; i >= 0; i--) { // truly a gamer moment + IBaritoneProcess proc = inContention.get(i); + if (found) { + if (cancelOthers) { + proc.onLostControl(); + } + } else { + exec = proc.onTick(); + if (exec == null) { + if (proc.isActive()) { + throw new IllegalStateException(proc + ""); + } + proc.onLostControl(); + continue; + } + found = true; + cancelOthers = !proc.isTemporary(); + } + } + return exec; + } +} From 338fdb509a4e69d1dd284d1e809f1ff4e23204d7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 4 Nov 2018 10:29:22 -0800 Subject: [PATCH 232/305] it works --- .../api/process/IBaritoneProcess.java | 2 + .../api/process/PathingCommandType.java | 12 ++-- src/main/java/baritone/Baritone.java | 11 ++-- .../baritone/behavior/PathingBehavior.java | 50 ++++++++++++---- .../baritone/process/CustomGoalProcess.java | 54 ++++++++++++++--- .../java/baritone/process/FollowProcess.java | 9 ++- .../baritone/process/GetToBlockProcess.java | 10 +++- .../java/baritone/process/MineProcess.java | 11 +++- .../java/baritone/utils/BaritoneAutoTest.java | 3 +- .../baritone/utils/BaritoneProcessHelper.java | 2 +- .../utils/ExampleBaritoneControl.java | 59 ++++++++----------- .../baritone/utils/PathingControlManager.java | 52 +++++++++------- 12 files changed, 182 insertions(+), 93 deletions(-) diff --git a/src/api/java/baritone/api/process/IBaritoneProcess.java b/src/api/java/baritone/api/process/IBaritoneProcess.java index 6405be94..9eef16fc 100644 --- a/src/api/java/baritone/api/process/IBaritoneProcess.java +++ b/src/api/java/baritone/api/process/IBaritoneProcess.java @@ -44,4 +44,6 @@ public interface IBaritoneProcess { double priority(); // tenor be like IBaritone associatedWith(); // which bot is this associated with (5000000iq forward thinking) + + String displayName(); } diff --git a/src/api/java/baritone/api/process/PathingCommandType.java b/src/api/java/baritone/api/process/PathingCommandType.java index 24eaf3a8..d4f7af44 100644 --- a/src/api/java/baritone/api/process/PathingCommandType.java +++ b/src/api/java/baritone/api/process/PathingCommandType.java @@ -18,10 +18,12 @@ package baritone.api.process; public enum PathingCommandType { - SET_GOAL_AND_PATH, // if you do this one with a null goal it should continue - REQUEST_PAUSE, + SET_GOAL_AND_PATH, // self explanatory, if you do this one with a null goal it should continue - // if you do this one with a null goal it should cancel - REVALIDATE_GOAL_AND_PATH, // idkkkkkkk - FORCE_REVALIDATE_GOAL_AND_PATH // idkkkkkkkkkkkkkkkkkkkkkkkk + REQUEST_PAUSE, // this one just pauses. it doesn't change the goal. + + CANCEL_AND_SET_GOAL, // cancel the current path, and set the goal (regardless of if it's null) + + REVALIDATE_GOAL_AND_PATH, // set the goal, revalidate if cancelOnGoalInvalidation is true, then path. if the goal is null, it will cancel (but only if that setting is true) + FORCE_REVALIDATE_GOAL_AND_PATH // set the goal, revalidate current goal (cancel if no longer valid), cancel if the provided goal is null } diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 055929f0..b655dddc 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -21,7 +21,6 @@ import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.event.listener.IGameEventListener; -import baritone.api.process.IBaritoneProcess; import baritone.behavior.Behavior; import baritone.behavior.LookBehavior; import baritone.behavior.MemoryBehavior; @@ -114,8 +113,8 @@ public enum Baritone implements IBaritone { followProcess = new FollowProcess(this); mineProcess = new MineProcess(this); new ExampleBaritoneControl(this); - new CustomGoalProcess(this); // very high iq - new GetToBlockProcess(this); + customGoalProcess = new CustomGoalProcess(this); // very high iq + getToBlockProcess = new GetToBlockProcess(this); } if (BaritoneAutoTest.ENABLE_AUTO_TEST) { registerEventListener(BaritoneAutoTest.INSTANCE); @@ -160,8 +159,12 @@ public enum Baritone implements IBaritone { this.registerEventListener(behavior); } - public void registerProcess(IBaritoneProcess process) { + public CustomGoalProcess getCustomGoalProcess() { + return customGoalProcess; + } + public GetToBlockProcess getGetToBlockProcess() { // very very high iq + return getToBlockProcess; } @Override diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 1cfd98bd..15dffae8 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -52,6 +52,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private Goal goal; + private boolean safeToCancel; + private boolean pauseRequestedLastTick; + private volatile boolean isPathCalcInProgress; private final Object pathCalcLock = new Object(); @@ -81,7 +84,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, public void onTick(TickEvent event) { dispatchEvents(); if (event.getType() == TickEvent.Type.OUT) { - cancel(); + secretInternalSegmentCancel(); return; } tickPath(); @@ -89,10 +92,17 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } private void tickPath() { + baritone.getPathingControlManager().doTheThingWithTheStuff(); + if (pauseRequestedLastTick && safeToCancel) { + pauseRequestedLastTick = false; + baritone.getInputOverrideHandler().clearAllKeys(); + BlockBreakHelper.stopBreakingBlock(); + return; + } if (current == null) { return; } - boolean safe = current.onTick(); + safeToCancel = current.onTick(); synchronized (pathPlanLock) { if (current.failed() || current.finished()) { current = null; @@ -134,7 +144,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return; } // at this point, we know current is in progress - if (safe && next != null && next.snipsnapifpossible()) { + if (safeToCancel && next != null && next.snipsnapifpossible()) { // a movement just ended; jump directly onto the next path logDebug("Splicing into planned next path early..."); queuePathEvent(PathEvent.SPLICING_ONTO_NEXT_EARLY); @@ -191,13 +201,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return Optional.of(current.getPath().ticksRemainingFrom(current.getPosition())); } - public void setGoal(Goal goal) { + public void secretInternalSetGoal(Goal goal) { this.goal = goal; } - public boolean setGoalAndPath(Goal goal) { - setGoal(goal); - return path(); + public boolean secretInternalSetGoalAndPath(Goal goal) { + secretInternalSetGoal(goal); + return secretInternalPath(); } @Override @@ -225,22 +235,40 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return this.current != null; } + public boolean isSafeToCancel() { + return current == null || safeToCancel; + } + + public void requestPause() { + pauseRequestedLastTick = true; + } + + public boolean cancelSegmentIfSafe() { + if (isSafeToCancel()) { + secretInternalSegmentCancel(); + return true; + } + return false; + } + @Override public void cancelEverything() { - + secretInternalSegmentCancel(); + baritone.getPathingControlManager().cancelEverything(); } // just cancel the current path - public void cancel() { + public void secretInternalSegmentCancel() { queuePathEvent(PathEvent.CANCELED); current = null; next = null; - Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys(); + baritone.getInputOverrideHandler().clearAllKeys(); AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(AbstractNodeCostSearch::cancel); BlockBreakHelper.stopBreakingBlock(); } public void forceCancel() { // NOT exposed on public api + cancelEverything(); isPathCalcInProgress = false; } @@ -249,7 +277,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * * @return true if this call started path calculation, false if it was already calculating or executing a path */ - public boolean path() { + public boolean secretInternalPath() { if (goal == null) { return false; } diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index 08b142ff..e402edf8 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -22,8 +22,11 @@ import baritone.api.pathing.goals.Goal; import baritone.api.process.ICustomGoalProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; +import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.utils.BaritoneProcessHelper; +import java.util.Objects; + /** * As set by ExampleBaritoneControl or something idk * @@ -31,35 +34,72 @@ import baritone.utils.BaritoneProcessHelper; */ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomGoalProcess { private Goal goal; - private boolean active; + private State state; + private int ticksExecuting; public CustomGoalProcess(Baritone baritone) { - super(baritone); + super(baritone, 3); } @Override public void setGoal(Goal goal) { this.goal = goal; + state = State.GOAL_SET; } @Override public void path() { - active = true; + if (goal == null) { + goal = baritone.getPathingBehavior().getGoal(); + } + state = State.PATH_REQUESTED; + } + + private enum State { + NONE, + GOAL_SET, + PATH_REQUESTED, + EXECUTING, + } @Override public boolean isActive() { - return active; + return state != State.NONE; } @Override public PathingCommand onTick() { - active = false; // only do this once - return new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); + switch (state) { + case GOAL_SET: + if (!baritone.getPathingBehavior().isPathing() && Objects.equals(baritone.getPathingBehavior().getGoal(), goal)) { + state = State.NONE; + } + return new PathingCommand(goal, PathingCommandType.CANCEL_AND_SET_GOAL); + case PATH_REQUESTED: + PathingCommand ret = new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); + state = State.EXECUTING; + ticksExecuting = 0; + return ret; + case EXECUTING: + if (ticksExecuting++ > 2 && !baritone.getPathingBehavior().isPathing() && !AbstractNodeCostSearch.getCurrentlyRunning().isPresent()) { + onLostControl(); + } + return new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); + default: + throw new IllegalStateException(); + } } @Override public void onLostControl() { - active = false; + state = State.NONE; + goal = null; + ticksExecuting = 0; + } + + @Override + public String displayName() { + return "Custom Goal " + goal; } } diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index dcfa21a0..bfccdda7 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -18,9 +18,9 @@ package baritone.process; import baritone.Baritone; -import baritone.api.process.IFollowProcess; import baritone.api.pathing.goals.GoalNear; import baritone.api.pathing.goals.GoalXZ; +import baritone.api.process.IFollowProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; import baritone.utils.BaritoneProcessHelper; @@ -37,7 +37,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo private Entity following; public FollowProcess(Baritone baritone) { - super(baritone); + super(baritone, 1); } @Override @@ -63,6 +63,11 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo following = null; } + @Override + public String displayName() { + return "Follow " + following; + } + @Override public void follow(Entity entity) { this.following = entity; diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 62dac26e..b2fd1363 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -38,7 +38,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl int tickCount = 0; public GetToBlockProcess(Baritone baritone) { - super(baritone); + super(baritone, 2); } @Override @@ -67,6 +67,9 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl Baritone.INSTANCE.getExecutor().execute(this::rescan); } Goal goal = new GoalComposite(knownLocations.stream().map(GoalGetToBlock::new).toArray(Goal[]::new)); + if (goal.isInGoal(playerFeet())) { + onLostControl(); + } return new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); } @@ -76,6 +79,11 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl knownLocations = null; } + @Override + public String displayName() { + return "Get To Block " + gettingTo; + } + private void rescan() { knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64); } diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index a88fd537..823f2091 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -57,7 +57,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro private int tickCount; public MineProcess(Baritone baritone) { - super(baritone); + super(baritone, 0); } @Override @@ -79,7 +79,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain - Baritone.INSTANCE.getExecutor().execute(this::rescan); + baritone.getExecutor().execute(this::rescan); } if (Baritone.settings().legitMine.get()) { addNearby(); @@ -99,6 +99,11 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro mine(0, (Block[]) null); } + @Override + public String displayName() { + return "Mine " + mining; + } + private Goal updateGoal() { List locs = knownOreLocations; if (!locs.isEmpty()) { @@ -115,7 +120,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro // only in non-Xray mode (aka legit mode) do we do this if (branchPoint == null) { int y = Baritone.settings().legitMineYLevel.get(); - if (!associatedWith().getPathingBehavior().isPathing() && playerFeet().y == y) { + if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) { // cool, path is over and we are at desired y branchPoint = playerFeet(); } else { diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index 70e1a70e..4aee4bd4 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -105,8 +105,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { } // Setup Baritone's pathing goal and (if needed) begin pathing - Baritone.INSTANCE.getPathingBehavior().setGoal(GOAL); - Baritone.INSTANCE.getPathingBehavior().path(); + Baritone.INSTANCE.getCustomGoalProcess().setGoalAndPath(GOAL); // If we have reached our goal, print a message and safely close the game if (GOAL.isInGoal(playerFeet())) { diff --git a/src/main/java/baritone/utils/BaritoneProcessHelper.java b/src/main/java/baritone/utils/BaritoneProcessHelper.java index 4ca0fe94..d01e815d 100644 --- a/src/main/java/baritone/utils/BaritoneProcessHelper.java +++ b/src/main/java/baritone/utils/BaritoneProcessHelper.java @@ -23,7 +23,7 @@ import baritone.api.process.IBaritoneProcess; public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper { public static final double DEFAULT_PRIORITY = 0; - private final Baritone baritone; + protected final Baritone baritone; private final double priority; public BaritoneProcessHelper(Baritone baritone) { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index f461b9a7..90648245 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -33,6 +33,7 @@ import baritone.cache.WorldProvider; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; +import baritone.process.CustomGoalProcess; import net.minecraft.block.Block; import net.minecraft.client.multiplayer.ChunkProviderClient; import net.minecraft.entity.Entity; @@ -99,6 +100,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { public boolean runCommand(String msg0) { String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL PathingBehavior pathingBehavior = baritone.getPathingBehavior(); + PathingControlManager pathControl = baritone.getPathingControlManager(); + CustomGoalProcess CGPgrey = baritone.getCustomGoalProcess(); List> toggleable = Baritone.settings().getAllValuesByType(Boolean.class); for (Settings.Setting setting : toggleable) { if (msg.equalsIgnoreCase(setting.getName())) { @@ -186,21 +189,19 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("unable to parse integer " + ex); return true; } - pathingBehavior.setGoal(goal); + CGPgrey.setGoal(goal); logDirect("Goal: " + goal); return true; } if (msg.equals("path")) { - if (!pathingBehavior.path()) { - if (pathingBehavior.getGoal() == null) { - logDirect("No goal."); - } else { - if (pathingBehavior.getGoal().isInGoal(playerFeet())) { - logDirect("Already in goal"); - } else { - logDirect("Currently executing a path. Please cancel it first."); - } - } + if (pathingBehavior.getGoal() == null) { + logDirect("No goal."); + } else if (pathingBehavior.getGoal().isInGoal(playerFeet())) { + logDirect("Already in goal"); + } else if (pathingBehavior.isPathing()) { + logDirect("Currently executing a path. Please cancel it first."); + } else { + CGPgrey.path(); } return true; } @@ -222,21 +223,20 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("axis")) { - pathingBehavior.setGoal(new GoalAxis()); - pathingBehavior.path(); + CGPgrey.setGoalAndPath(new GoalAxis()); return true; } if (msg.equals("cancel") || msg.equals("stop")) { baritone.getMineProcess().cancel(); baritone.getFollowProcess().cancel(); - pathingBehavior.cancel(); + pathingBehavior.cancelEverything(); logDirect("ok canceled"); return true; } if (msg.equals("forcecancel")) { baritone.getMineProcess().cancel(); baritone.getFollowProcess().cancel(); - pathingBehavior.cancel(); + pathingBehavior.cancelEverything(); AbstractNodeCostSearch.forceCancel(); pathingBehavior.forceCancel(); logDirect("ok force canceled"); @@ -259,15 +259,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Inverting goal of player feet"); runAwayFrom = playerFeet(); } - pathingBehavior.setGoal(new GoalRunAway(1, runAwayFrom) { + CGPgrey.setGoalAndPath(new GoalRunAway(1, runAwayFrom) { @Override public boolean isInGoal(int x, int y, int z) { return false; } }); - if (!pathingBehavior.path()) { - logDirect("Currently executing a path. Please cancel it first."); - } return true; } if (msg.startsWith("follow")) { @@ -337,7 +334,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { if (msg.startsWith("thisway")) { try { Goal goal = GoalXZ.fromDirection(playerFeetAsVec(), player().rotationYaw, Double.parseDouble(msg.substring(7).trim())); - pathingBehavior.setGoal(goal); + CGPgrey.setGoal(goal); logDirect("Goal: " + goal); } catch (NumberFormatException ex) { logDirect("Error unable to parse '" + msg.substring(7).trim() + "' to a double."); @@ -406,13 +403,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } else { - List locs = baritone.getMineProcess().searchWorld(Collections.singletonList(block), 64); - if (locs.isEmpty()) { - logDirect("No locations for " + mining + " known, cancelling"); - return true; - } - pathingBehavior.setGoal(new GoalComposite(locs.stream().map(GoalGetToBlock::new).toArray(Goal[]::new))); - pathingBehavior.path(); + baritone.getGetToBlockProcess().getToBlock(block); return true; } } else { @@ -423,10 +414,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } Goal goal = new GoalBlock(waypoint.getLocation()); - pathingBehavior.setGoal(goal); - if (!pathingBehavior.path() && !goal.isInGoal(playerFeet())) { - logDirect("Currently executing a path. Please cancel it first."); - } + CGPgrey.setGoalAndPath(goal); return true; } if (msg.equals("spawn") || msg.equals("bed")) { @@ -436,10 +424,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper { // for some reason the default spawnpoint is underground sometimes Goal goal = new GoalXZ(spawnPoint.getX(), spawnPoint.getZ()); logDirect("spawn not saved, defaulting to world spawn. set goal to " + goal); - pathingBehavior.setGoal(goal); + CGPgrey.setGoalAndPath(goal); } else { - Goal goal = new GoalBlock(waypoint.getLocation()); - pathingBehavior.setGoal(goal); + Goal goal = new GoalGetToBlock(waypoint.getLocation()); + CGPgrey.setGoalAndPath(goal); logDirect("Set goal to most recent bed " + goal); } return true; @@ -455,8 +443,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("home not saved"); } else { Goal goal = new GoalBlock(waypoint.getLocation()); - pathingBehavior.setGoal(goal); - pathingBehavior.path(); + CGPgrey.setGoalAndPath(goal); logDirect("Going to saved home " + goal); } return true; diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 37c17614..55308daf 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -21,6 +21,7 @@ import baritone.Baritone; import baritone.api.pathing.goals.Goal; import baritone.api.process.IBaritoneProcess; import baritone.api.process.PathingCommand; +import baritone.behavior.PathingBehavior; import baritone.pathing.path.PathExecutor; import net.minecraft.util.math.BlockPos; @@ -39,43 +40,51 @@ public class PathingControlManager { } public void registerProcess(IBaritoneProcess process) { + process.onLostControl(); // make sure it's reset processes.add(process); } + public void cancelEverything() { + for (IBaritoneProcess proc : processes) { + proc.onLostControl(); + if (proc.isActive() && !proc.isTemporary()) { // it's okay for a temporary thing (like combat pause) to maintain control even if you say to cancel + // but not for a non temporary thing + throw new IllegalStateException(proc.displayName()); + } + } + } + public void doTheThingWithTheStuff() { PathingCommand cmd = doTheStuff(); if (cmd == null) { - baritone.getPathingBehavior().cancel(); return; } - + PathingBehavior p = baritone.getPathingBehavior(); switch (cmd.commandType) { case REQUEST_PAUSE: - // idk - // ask pathingbehavior if its safe + p.requestPause(); + break; + case CANCEL_AND_SET_GOAL: + p.secretInternalSetGoal(cmd.goal); + p.cancelSegmentIfSafe(); + break; case FORCE_REVALIDATE_GOAL_AND_PATH: - if (cmd.goal == null) { - baritone.getPathingBehavior().cancel(); // todo only if its safe - return; - } - // pwnage - baritone.getPathingBehavior().setGoal(cmd.goal); - if (revalidateGoal(cmd.goal)) { - baritone.getPathingBehavior().cancel(); // todo only if its safe + p.secretInternalSetGoalAndPath(cmd.goal); + if (cmd.goal == null || revalidateGoal(cmd.goal)) { + // pwnage + p.cancelSegmentIfSafe(); } + break; case REVALIDATE_GOAL_AND_PATH: - if (cmd.goal == null) { - baritone.getPathingBehavior().cancel(); // todo only if its safe - return; - } - baritone.getPathingBehavior().setGoal(cmd.goal); - if (Baritone.settings().cancelOnGoalInvalidation.get() && revalidateGoal(cmd.goal)) { - baritone.getPathingBehavior().cancel(); // todo only if its safe + p.secretInternalSetGoalAndPath(cmd.goal); + if (Baritone.settings().cancelOnGoalInvalidation.get() && (cmd.goal == null || revalidateGoal(cmd.goal))) { + p.cancelSegmentIfSafe(); } + break; case SET_GOAL_AND_PATH: // now this i can do if (cmd.goal != null) { - baritone.getPathingBehavior().setGoalAndPath(cmd.goal); + baritone.getPathingBehavior().secretInternalSetGoalAndPath(cmd.goal); } // breaks are for wusses!!!! } @@ -111,11 +120,12 @@ public class PathingControlManager { exec = proc.onTick(); if (exec == null) { if (proc.isActive()) { - throw new IllegalStateException(proc + ""); + throw new IllegalStateException(proc.displayName()); } proc.onLostControl(); continue; } + System.out.println("Executing command " + exec.commandType + " " + exec.goal + " from " + proc.displayName()); found = true; cancelOthers = !proc.isTemporary(); } From cd3aef47a5c362dda1014172e5d3fc1e16e0b0ba Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 4 Nov 2018 10:30:46 -0800 Subject: [PATCH 233/305] that already does that --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 90648245..d7c1cf89 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -227,15 +227,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("cancel") || msg.equals("stop")) { - baritone.getMineProcess().cancel(); - baritone.getFollowProcess().cancel(); pathingBehavior.cancelEverything(); logDirect("ok canceled"); return true; } if (msg.equals("forcecancel")) { - baritone.getMineProcess().cancel(); - baritone.getFollowProcess().cancel(); pathingBehavior.cancelEverything(); AbstractNodeCostSearch.forceCancel(); pathingBehavior.forceCancel(); From c814874cb6290d70f864888e56dd377b6a2a6c09 Mon Sep 17 00:00:00 2001 From: 0x22 <0x22@futureclient.net> Date: Sun, 4 Nov 2018 18:09:40 -0500 Subject: [PATCH 234/305] Updated mappings to stable_39 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index abb75959..e0b556a2 100755 --- a/build.gradle +++ b/build.gradle @@ -58,7 +58,7 @@ sourceSets { minecraft { version = '1.12.2' - mappings = 'snapshot_20180731' + mappings = 'stable_39' tweakClass = 'baritone.launch.BaritoneTweaker' runDir = 'run' From c0b5d60715cfeb033d10d050e334bcee79e2c54f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 4 Nov 2018 22:17:49 -0800 Subject: [PATCH 235/305] fix --- src/main/java/baritone/utils/PathingControlManager.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 55308daf..8165f1a1 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -86,7 +86,9 @@ public class PathingControlManager { if (cmd.goal != null) { baritone.getPathingBehavior().secretInternalSetGoalAndPath(cmd.goal); } - // breaks are for wusses!!!! + break; + default: + throw new IllegalStateException(); } } From 6812d2ba7d744ff00aaceba6ec99a44cbceff7ad Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 4 Nov 2018 22:22:04 -0800 Subject: [PATCH 236/305] simplify readme --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index dd7a87cf..78202aa6 100644 --- a/README.md +++ b/README.md @@ -40,8 +40,7 @@ For example, to replace out Impact 4.4's Baritone build with a customized one, b ## IntelliJ's Gradle UI - Open the project in IntelliJ as a Gradle project -- Run the Gradle task `setupDecompWorkspace` -- Run the Gradle task `genIntellijRuns` +- Run the Gradle tasks `setupDecompWorkspace` then `genIntellijRuns` - Refresh the Gradle project (or, to be safe, just restart IntelliJ) - Select the "Minecraft Client" launch config - In `Edit Configurations...` you may need to select `baritone_launch` for `Use classpath of module:`. From 1c4f029bf4510e43d3c813e2b0c49791e3fe6ec4 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 5 Nov 2018 12:47:17 -0600 Subject: [PATCH 237/305] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 78202aa6..4defe19f 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Building Baritone: $ gradlew build ``` -For example, to replace out Impact 4.4's Baritone build with a customized one, build Baritone as above then copy `dist/baritone-api-$VERSION.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). +For example, to replace out Impact 4.4's Baritone build with a customized one, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/$VERSION$/baritone-api-$VERSION$.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:$VERSION$"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). ## IntelliJ's Gradle UI - Open the project in IntelliJ as a Gradle project From ffb044ffc6248c7022a04955f30faf6502900d28 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 5 Nov 2018 13:47:55 -0600 Subject: [PATCH 238/305] Replace RotationMoveEvent Inject with Redirect --- .../api/event/events/RotationMoveEvent.java | 15 +++--- .../baritone/launch/mixins/MixinEntity.java | 37 ++++++++++---- .../launch/mixins/MixinEntityLivingBase.java | 48 +++++++++++++------ 3 files changed, 67 insertions(+), 33 deletions(-) diff --git a/src/api/java/baritone/api/event/events/RotationMoveEvent.java b/src/api/java/baritone/api/event/events/RotationMoveEvent.java index 7a7514db..7f98947d 100644 --- a/src/api/java/baritone/api/event/events/RotationMoveEvent.java +++ b/src/api/java/baritone/api/event/events/RotationMoveEvent.java @@ -17,7 +17,6 @@ package baritone.api.event.events; -import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.ManagedPlayerEvent; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; @@ -35,21 +34,21 @@ public final class RotationMoveEvent extends ManagedPlayerEvent { private final Type type; /** - * The state of the event + * The yaw rotation */ - private final EventState state; + private float yaw; - public RotationMoveEvent(EntityPlayerSP player, EventState state, Type type) { + public RotationMoveEvent(EntityPlayerSP player, Type type, float yaw) { super(player); - this.state = state; this.type = type; + this.yaw = yaw; } /** - * @return The state of the event + * @return The yaw rotation */ - public final EventState getState() { - return this.state; + public final float getYaw() { + return this.yaw; } /** diff --git a/src/launch/java/baritone/launch/mixins/MixinEntity.java b/src/launch/java/baritone/launch/mixins/MixinEntity.java index fe019bb7..db8b513f 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntity.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntity.java @@ -19,14 +19,17 @@ package baritone.launch.mixins; import baritone.Baritone; import baritone.api.event.events.RotationMoveEvent; -import baritone.api.event.events.type.EventState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import static org.spongepowered.asm.lib.Opcodes.GETFIELD; + /** * @author Brady * @since 8/21/2018 @@ -34,23 +37,37 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(Entity.class) public class MixinEntity { + @Shadow public float rotationYaw; + + /** + * Event called to override the movement direction when walking + */ + private RotationMoveEvent motionUpdateRotationEvent; + @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 (EntityPlayerSP.class.isInstance(_this)) - Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.PRE, RotationMoveEvent.Type.MOTION_UPDATE)); + // noinspection ConstantConditions + if (EntityPlayerSP.class.isInstance(this)) { + this.motionUpdateRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw); + Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(this.motionUpdateRotationEvent); + } } - @Inject( + @Redirect( method = "moveRelative", - at = @At("RETURN") + at = @At( + value = "FIELD", + opcode = GETFIELD, + target = "net/minecraft/entity/Entity.rotationYaw:F" + ) ) - private void postMoveRelative(float strafe, float up, float forward, float friction, CallbackInfo ci) { - Entity _this = (Entity) (Object) this; - if (EntityPlayerSP.class.isInstance(_this)) - Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.POST, RotationMoveEvent.Type.MOTION_UPDATE)); + private float overrideYaw(Entity entity) { + if (entity instanceof EntityPlayerSP) { + return this.motionUpdateRotationEvent.getYaw(); + } + return entity.rotationYaw; } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java index 6313b3a1..42aa9bf0 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -19,41 +19,59 @@ package baritone.launch.mixins; import baritone.Baritone; import baritone.api.event.events.RotationMoveEvent; -import baritone.api.event.events.type.EventState; import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.world.World; 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.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import static org.spongepowered.asm.lib.Opcodes.GETFIELD; + /** * @author Brady * @since 9/10/2018 */ @Mixin(EntityLivingBase.class) -public class MixinEntityLivingBase { +public abstract class MixinEntityLivingBase extends Entity { + + /** + * Event called to override the movement direction when jumping + */ + private RotationMoveEvent jumpRotationEvent; + + public MixinEntityLivingBase(World worldIn, RotationMoveEvent jumpRotationEvent) { + super(worldIn); + this.jumpRotationEvent = jumpRotationEvent; + } @Inject( method = "jump", at = @At("HEAD") ) - private void preJump(CallbackInfo ci) { - EntityLivingBase _this = (EntityLivingBase) (Object) this; - // This uses Class.isInstance instead of instanceof since proguard optimizes out the instanceof (since MixinEntityLivingBase could never be instanceof EntityLivingBase in normal java) - // but proguard isn't smart enough to optimize out this Class.isInstance =) - if (EntityPlayerSP.class.isInstance(_this)) - Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.PRE, RotationMoveEvent.Type.JUMP)); + private void preMoveRelative(CallbackInfo ci) { + // noinspection ConstantConditions + if (EntityPlayerSP.class.isInstance(this)) { + this.jumpRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.JUMP, this.rotationYaw); + Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent); + } } - @Inject( + @Redirect( method = "jump", - at = @At("RETURN") + at = @At( + value = "FIELD", + opcode = GETFIELD, + target = "net/minecraft/entity/EntityLivingBase.rotationYaw:F" + ) ) - private void postJump(CallbackInfo ci) { - EntityLivingBase _this = (EntityLivingBase) (Object) this; - // See above - if (EntityPlayerSP.class.isInstance(_this)) - Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.POST, RotationMoveEvent.Type.JUMP)); + private float overrideYaw(EntityLivingBase entity) { + if (entity instanceof EntityPlayerSP) { + return this.jumpRotationEvent.getYaw(); + } + return entity.rotationYaw; } } From c0e0f8dc2a3537f2cd463ba03cfe9c1d3cfdd5ff Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 5 Nov 2018 13:53:26 -0600 Subject: [PATCH 239/305] Fix last commit lol --- .../api/event/events/RotationMoveEvent.java | 9 ++++++++ .../java/baritone/behavior/LookBehavior.java | 21 ++++++------------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/api/java/baritone/api/event/events/RotationMoveEvent.java b/src/api/java/baritone/api/event/events/RotationMoveEvent.java index 7f98947d..790318e0 100644 --- a/src/api/java/baritone/api/event/events/RotationMoveEvent.java +++ b/src/api/java/baritone/api/event/events/RotationMoveEvent.java @@ -44,6 +44,15 @@ public final class RotationMoveEvent extends ManagedPlayerEvent { this.yaw = yaw; } + /** + * Set the yaw movement rotation + * + * @param yaw Yaw rotation + */ + public final void setYaw(float yaw) { + this.yaw = yaw; + } + /** * @return The yaw rotation */ diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index ac3a4698..bcaf487e 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -97,22 +97,13 @@ public final class LookBehavior extends Behavior implements ILookBehavior, Helpe @Override public void onPlayerRotationMove(RotationMoveEvent event) { if (this.target != null && !this.force) { - switch (event.getState()) { - case PRE: - this.lastYaw = player().rotationYaw; - player().rotationYaw = this.target.getYaw(); - break; - case POST: - player().rotationYaw = this.lastYaw; - // If we have antiCheatCompatibility on, we're going to use the target value later in onPlayerUpdate() - // Also the type has to be MOTION_UPDATE because that is called after JUMP - if (!Baritone.settings().antiCheatCompatibility.get() && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE) { - this.target = null; - } - break; - default: - break; + event.setYaw(this.target.getYaw()); + + // If we have antiCheatCompatibility on, we're going to use the target value later in onPlayerUpdate() + // Also the type has to be MOTION_UPDATE because that is called after JUMP + if (!Baritone.settings().antiCheatCompatibility.get() && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE) { + this.target = null; } } } From f286c400a3d8904657104b098ab3d713c01d66f8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 13:47:00 -0800 Subject: [PATCH 240/305] when parkouring from soul sand, the maximum gap should be 1, fixes #247 --- .../movement/movements/MovementParkour.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index dbcf3a59..68bddae0 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -93,7 +93,17 @@ public class MovementParkour extends Movement { if (!MovementHelper.fullyPassable(x, y + 2, z)) { return; } - for (int i = 2; i <= (context.canSprint() ? 4 : 3); i++) { + int maxJump; + if (standingOn.getBlock() == Blocks.SOUL_SAND) { + maxJump = 2; // 1 block gap + } else { + if (context.canSprint()) { + maxJump = 4; + } else { + maxJump = 3; + } + } + for (int i = 2; i <= maxJump; i++) { // TODO perhaps dest.up(3) doesn't need to be fullyPassable, just canWalkThrough, possibly? for (int y2 = 0; y2 < 4; y2++) { if (!MovementHelper.fullyPassable(x + xDiff * i, y + y2, z + zDiff * i)) { @@ -108,7 +118,7 @@ public class MovementParkour extends Movement { return; } } - if (!context.canSprint()) { + if (maxJump != 4) { return; } if (!Baritone.settings().allowParkourPlace.get()) { From 0373f1875f9d30d5afe7ecf3974bcbf724a35d99 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 5 Nov 2018 16:05:25 -0600 Subject: [PATCH 241/305] Meme --- .../baritone/api/event/events/type/EventState.java | 6 ++---- .../java/baritone/launch/mixins/MixinEntity.java | 6 +++--- .../baritone/launch/mixins/MixinEntityLivingBase.java | 6 +++--- src/main/java/baritone/behavior/LookBehavior.java | 11 ++++++++--- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/api/java/baritone/api/event/events/type/EventState.java b/src/api/java/baritone/api/event/events/type/EventState.java index 10b633bd..072e12c1 100644 --- a/src/api/java/baritone/api/event/events/type/EventState.java +++ b/src/api/java/baritone/api/event/events/type/EventState.java @@ -24,14 +24,12 @@ package baritone.api.event.events.type; public enum EventState { /** - * Indicates that whatever movement the event is being - * dispatched as a result of is about to occur. + * Before the dispatching of what the event is targetting */ PRE, /** - * Indicates that whatever movement the event is being - * dispatched as a result of has already occurred. + * After the dispatching of what the event is targetting */ POST } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntity.java b/src/launch/java/baritone/launch/mixins/MixinEntity.java index db8b513f..6623e1c2 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntity.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntity.java @@ -64,10 +64,10 @@ public class MixinEntity { target = "net/minecraft/entity/Entity.rotationYaw:F" ) ) - private float overrideYaw(Entity entity) { - if (entity instanceof EntityPlayerSP) { + private float overrideYaw(Entity self) { + if (self instanceof EntityPlayerSP) { return this.motionUpdateRotationEvent.getYaw(); } - return entity.rotationYaw; + return self.rotationYaw; } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java index 42aa9bf0..8e2eb515 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -68,10 +68,10 @@ public abstract class MixinEntityLivingBase extends Entity { target = "net/minecraft/entity/EntityLivingBase.rotationYaw:F" ) ) - private float overrideYaw(EntityLivingBase entity) { - if (entity instanceof EntityPlayerSP) { + private float overrideYaw(EntityLivingBase self) { + if (self instanceof EntityPlayerSP) { return this.jumpRotationEvent.getYaw(); } - return entity.rotationYaw; + return self.rotationYaw; } } diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index bcaf487e..ee8548a2 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -26,6 +26,7 @@ import baritone.api.utils.Rotation; import baritone.utils.Helper; public final class LookBehavior extends Behavior implements ILookBehavior, Helper { + /** * Target's values are as follows: *

@@ -63,7 +64,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior, Helpe } // Whether or not we're going to silently set our angles - boolean silent = Baritone.settings().antiCheatCompatibility.get(); + boolean silent = Baritone.settings().antiCheatCompatibility.get() && !this.force; switch (event.getState()) { case PRE: { @@ -76,14 +77,15 @@ public final class LookBehavior extends Behavior implements ILookBehavior, Helpe nudgeToLevel(); } this.target = null; - } else if (silent) { + } + if (silent) { this.lastYaw = player().rotationYaw; player().rotationYaw = this.target.getYaw(); } break; } case POST: { - if (!this.force && silent) { + if (silent) { player().rotationYaw = this.lastYaw; this.target = null; } @@ -108,6 +110,9 @@ public final class LookBehavior extends Behavior implements ILookBehavior, Helpe } } + /** + * Nudges the player's pitch to a regular level. (Between {@code -20} and {@code 10}, increments are by {@code 1}) + */ private void nudgeToLevel() { if (player().rotationPitch < -20) { player().rotationPitch++; From 75a224cef1801f8177e20d5ce170ac80a737b1d7 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 5 Nov 2018 16:06:23 -0600 Subject: [PATCH 242/305] Partially revert README update --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4defe19f..ef568f0c 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Building Baritone: $ gradlew build ``` -For example, to replace out Impact 4.4's Baritone build with a customized one, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/$VERSION$/baritone-api-$VERSION$.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:$VERSION$"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). +For example, to replace out Impact 4.4's Baritone build with a customized one, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). ## IntelliJ's Gradle UI - Open the project in IntelliJ as a Gradle project From 2c39cd06ed744f13d5a66d5adbce01f83df1a7b9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 14:19:50 -0800 Subject: [PATCH 243/305] cleanup --- .../api/process/IBaritoneProcess.java | 55 ++++++++++++++++--- .../api/process/PathingCommandType.java | 32 +++++++++-- .../baritone/behavior/PathingBehavior.java | 6 ++ .../baritone/process/CustomGoalProcess.java | 11 ++-- .../java/baritone/process/FollowProcess.java | 2 +- .../baritone/process/GetToBlockProcess.java | 23 +++++--- .../java/baritone/process/MineProcess.java | 7 ++- .../utils/ExampleBaritoneControl.java | 1 - .../baritone/utils/PathingControlManager.java | 10 +++- 9 files changed, 117 insertions(+), 30 deletions(-) diff --git a/src/api/java/baritone/api/process/IBaritoneProcess.java b/src/api/java/baritone/api/process/IBaritoneProcess.java index 9eef16fc..3f907c3d 100644 --- a/src/api/java/baritone/api/process/IBaritoneProcess.java +++ b/src/api/java/baritone/api/process/IBaritoneProcess.java @@ -31,19 +31,58 @@ import baritone.api.IBaritone; * @author leijurv */ public interface IBaritoneProcess { - // javadocs small brain, // comment large brain + /** + * Would this process like to be in control? + * + * @return + */ + boolean isActive(); - boolean isActive(); // would you like to be in control? + /** + * This process is in control of pathing. What should Baritone do? + * + * @param calcFailed true if this specific process was in control last tick, and there was a CALC_FAILED event last tick + * @param isSafeToCancel true if a REQUEST_PAUSE would happen this tick, and PathingBehavior wouldn't actually tick. + * false if the PathExecutor reported pausing would be unsafe at the end of the last tick + * @return what the PathingBehavior should do + */ + PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel); - PathingCommand onTick(); // you're in control, what should baritone do? + /** + * Is this control temporary? + * If a process is temporary, it doesn't call onLostControl on the processes that aren't execute because of it + * For example, CombatPauserProcess and PauseForAutoEatProcess should return isTemporary true always, + * and should return isActive true only if there's something in range this tick, or if the player would like to start eating this tick. + * PauseForAutoEatProcess should only actually right click once onTick is called with isSafeToCancel true though. + * + * @return + */ + boolean isTemporary(); - boolean isTemporary(); // CombatPauserProcess should return isTemporary true always, and isActive true only when something is in range + /** + * Called if isActive returned true, but another non-temporary process has control. Effectively the same as cancel. + * You want control but you don't get it. + */ + void onLostControl(); - void onLostControl(); // called if isActive returned true, but another non-temporary process has control. effectively the same as cancel. + /** + * How to decide which Process gets control if they all report isActive? It's the one with the highest priority. + * + * @return + */ + double priority(); - double priority(); // tenor be like - - IBaritone associatedWith(); // which bot is this associated with (5000000iq forward thinking) + /** + * which bot is this associated with (5000000iq forward thinking) + * + * @return + */ + IBaritone associatedWith(); + /** + * What this process should be displayed to the user as (maybe in a HUD? hint hint) + * + * @return + */ String displayName(); } diff --git a/src/api/java/baritone/api/process/PathingCommandType.java b/src/api/java/baritone/api/process/PathingCommandType.java index d4f7af44..98517ba5 100644 --- a/src/api/java/baritone/api/process/PathingCommandType.java +++ b/src/api/java/baritone/api/process/PathingCommandType.java @@ -18,12 +18,34 @@ package baritone.api.process; public enum PathingCommandType { - SET_GOAL_AND_PATH, // self explanatory, if you do this one with a null goal it should continue + /** + * Set the goal and path. + *

+ * If you use this alongside a null goal, it will continue along its current path and current goal. + */ + SET_GOAL_AND_PATH, - REQUEST_PAUSE, // this one just pauses. it doesn't change the goal. + /** + * Has no effect on the current goal or path, just requests a pause + */ + REQUEST_PAUSE, - CANCEL_AND_SET_GOAL, // cancel the current path, and set the goal (regardless of if it's null) + /** + * Set the goal (regardless of null), and request a cancel of the current path (when safe) + */ + CANCEL_AND_SET_GOAL, - REVALIDATE_GOAL_AND_PATH, // set the goal, revalidate if cancelOnGoalInvalidation is true, then path. if the goal is null, it will cancel (but only if that setting is true) - FORCE_REVALIDATE_GOAL_AND_PATH // set the goal, revalidate current goal (cancel if no longer valid), cancel if the provided goal is null + /** + * Set the goal and path. + *

+ * If cancelOnGoalInvalidation is true, revalidate the current goal, and cancel if it's no longer valid, or if the new goal is null. + */ + REVALIDATE_GOAL_AND_PATH, + + /** + * Set the goal and path. + *

+ * Revalidate the current goal, and cancel if it's no longer valid, or if the new goal is null. + */ + FORCE_REVALIDATE_GOAL_AND_PATH, } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 15dffae8..03641ac5 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -54,6 +54,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private boolean safeToCancel; private boolean pauseRequestedLastTick; + private boolean calcFailedLastTick; private volatile boolean isPathCalcInProgress; private final Object pathCalcLock = new Object(); @@ -75,6 +76,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private void dispatchEvents() { ArrayList curr = new ArrayList<>(); toDispatch.drainTo(curr); + calcFailedLastTick = curr.contains(PathEvent.CALC_FAILED); for (PathEvent event : curr) { Baritone.INSTANCE.getGameEventHandler().onPathEvent(event); } @@ -257,6 +259,10 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, baritone.getPathingControlManager().cancelEverything(); } + public boolean calcFailedLastTick() { // NOT exposed on public api + return calcFailedLastTick; + } + // just cancel the current path public void secretInternalSegmentCancel() { queuePathEvent(PathEvent.CANCELED); diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index e402edf8..52769f25 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -22,7 +22,6 @@ import baritone.api.pathing.goals.Goal; import baritone.api.process.ICustomGoalProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.utils.BaritoneProcessHelper; import java.util.Objects; @@ -35,7 +34,6 @@ import java.util.Objects; public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomGoalProcess { private Goal goal; private State state; - private int ticksExecuting; public CustomGoalProcess(Baritone baritone) { super(baritone, 3); @@ -69,7 +67,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG } @Override - public PathingCommand onTick() { + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { switch (state) { case GOAL_SET: if (!baritone.getPathingBehavior().isPathing() && Objects.equals(baritone.getPathingBehavior().getGoal(), goal)) { @@ -79,12 +77,14 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG case PATH_REQUESTED: PathingCommand ret = new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); state = State.EXECUTING; - ticksExecuting = 0; return ret; case EXECUTING: - if (ticksExecuting++ > 2 && !baritone.getPathingBehavior().isPathing() && !AbstractNodeCostSearch.getCurrentlyRunning().isPresent()) { + if (calcFailed) { onLostControl(); } + if (goal.isInGoal(playerFeet())) { + onLostControl(); // we're there xd + } return new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); default: throw new IllegalStateException(); @@ -95,7 +95,6 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG public void onLostControl() { state = State.NONE; goal = null; - ticksExecuting = 0; } @Override diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index bfccdda7..f662fa1d 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -41,7 +41,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo } @Override - public PathingCommand onTick() { + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { // lol this is trashy but it works BlockPos pos; if (Baritone.settings().followOffsetDistance.get() == 0) { diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index b2fd1363..8dd07560 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -32,10 +32,10 @@ import java.util.Collections; import java.util.List; public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess { - Block gettingTo; - List knownLocations; + private Block gettingTo; + private List knownLocations; - int tickCount = 0; + private int tickCount = 0; public GetToBlockProcess(Baritone baritone) { super(baritone, 2); @@ -53,14 +53,23 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } @Override - public PathingCommand onTick() { + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (knownLocations == null) { rescan(); } if (knownLocations.isEmpty()) { - logDirect("No known locations of " + gettingTo); - onLostControl(); - return null; + logDirect("No known locations of " + gettingTo + ", canceling GetToBlock"); + if (isSafeToCancel) { + onLostControl(); + } + return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); + } + if (calcFailed) { + logDirect("Unable to find any path to " + gettingTo + ", canceling GetToBlock"); + if (isSafeToCancel) { + onLostControl(); + } + return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 823f2091..2efeca03 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -66,7 +66,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } @Override - public PathingCommand onTick() { + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (desiredQuantity > 0) { Item item = mining.get(0).getItemDropped(mining.get(0).getDefaultState(), new Random(), 0); int curr = player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum(); @@ -77,6 +77,11 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return null; } } + if (calcFailed) { + logDirect("Unable to find any path to " + mining + ", canceling Mine"); + cancel(); + return null; + } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain baritone.getExecutor().execute(this::rescan); diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index d7c1cf89..74c17d60 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -100,7 +100,6 @@ public class ExampleBaritoneControl extends Behavior implements Helper { public boolean runCommand(String msg0) { String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL PathingBehavior pathingBehavior = baritone.getPathingBehavior(); - PathingControlManager pathControl = baritone.getPathingControlManager(); CustomGoalProcess CGPgrey = baritone.getCustomGoalProcess(); List> toggleable = Baritone.settings().getAllValuesByType(Boolean.class); for (Settings.Setting setting : toggleable) { diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 8165f1a1..bfb84d3c 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -33,6 +33,8 @@ import java.util.stream.Collectors; public class PathingControlManager { private final Baritone baritone; private final HashSet processes; // unGh + private IBaritoneProcess inControlLastTick; + private IBaritoneProcess inControlThisTick; public PathingControlManager(Baritone baritone) { this.baritone = baritone; @@ -54,7 +56,12 @@ public class PathingControlManager { } } + public IBaritoneProcess inControlThisTick() { + return inControlThisTick; + } + public void doTheThingWithTheStuff() { + inControlLastTick = inControlThisTick; PathingCommand cmd = doTheStuff(); if (cmd == null) { return; @@ -119,7 +126,7 @@ public class PathingControlManager { proc.onLostControl(); } } else { - exec = proc.onTick(); + exec = proc.onTick(proc == inControlLastTick && baritone.getPathingBehavior().calcFailedLastTick(), baritone.getPathingBehavior().isSafeToCancel()); if (exec == null) { if (proc.isActive()) { throw new IllegalStateException(proc.displayName()); @@ -128,6 +135,7 @@ public class PathingControlManager { continue; } System.out.println("Executing command " + exec.commandType + " " + exec.goal + " from " + proc.displayName()); + inControlThisTick = proc; found = true; cancelOthers = !proc.isTemporary(); } From e11e3dfd864dede96cb9764deb98f6b55ffe4f92 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 14:22:30 -0800 Subject: [PATCH 244/305] explain --- src/api/java/baritone/api/process/IBaritoneProcess.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/process/IBaritoneProcess.java b/src/api/java/baritone/api/process/IBaritoneProcess.java index 3f907c3d..d05bd8ef 100644 --- a/src/api/java/baritone/api/process/IBaritoneProcess.java +++ b/src/api/java/baritone/api/process/IBaritoneProcess.java @@ -43,7 +43,8 @@ public interface IBaritoneProcess { * * @param calcFailed true if this specific process was in control last tick, and there was a CALC_FAILED event last tick * @param isSafeToCancel true if a REQUEST_PAUSE would happen this tick, and PathingBehavior wouldn't actually tick. - * false if the PathExecutor reported pausing would be unsafe at the end of the last tick + * false if the PathExecutor reported pausing would be unsafe at the end of the last tick. + * Effectively "could request cancel or pause and have it happen right away" * @return what the PathingBehavior should do */ PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel); From 30408384c6d3eb131ecc9b2b900a8cfdd05f967d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 14:37:05 -0800 Subject: [PATCH 245/305] fix --- src/api/java/baritone/api/behavior/IPathingBehavior.java | 4 +++- src/main/java/baritone/behavior/PathingBehavior.java | 9 +++++++-- src/main/java/baritone/process/GetToBlockProcess.java | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index ced3d861..622c453a 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -53,8 +53,10 @@ public interface IPathingBehavior extends IBehavior { * Cancels the pathing behavior or the current path calculation. Also cancels all processes that could be controlling path. *

* Basically, "MAKE IT STOP". + * + * @return whether or not the pathing behavior was canceled. All processes are guaranteed to be canceled, but the PathingBehavior might be in the middle of an uncancelable action like a parkour jump */ - void cancelEverything(); + boolean cancelEverything(); /** * Returns the current path, from the current path executor, if there is one. diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 03641ac5..9582f3c5 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -254,9 +254,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } @Override - public void cancelEverything() { - secretInternalSegmentCancel(); + public boolean cancelEverything() { + boolean doIt = isSafeToCancel(); + if (doIt) { + secretInternalSegmentCancel(); + } baritone.getPathingControlManager().cancelEverything(); + return doIt; } public boolean calcFailedLastTick() { // NOT exposed on public api @@ -275,6 +279,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, public void forceCancel() { // NOT exposed on public api cancelEverything(); + secretInternalSegmentCancel(); isPathCalcInProgress = false; } diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 8dd07560..7f5340ed 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -79,7 +79,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl if (goal.isInGoal(playerFeet())) { onLostControl(); } - return new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); + return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH); } @Override From 23286dd8b8d1ceaf6fd26e6247c365456f0a38e8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 14:38:32 -0800 Subject: [PATCH 246/305] disallow null PathingCommandType --- src/api/java/baritone/api/process/PathingCommand.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/api/java/baritone/api/process/PathingCommand.java b/src/api/java/baritone/api/process/PathingCommand.java index f5b39501..082928b3 100644 --- a/src/api/java/baritone/api/process/PathingCommand.java +++ b/src/api/java/baritone/api/process/PathingCommand.java @@ -26,5 +26,8 @@ public class PathingCommand { public PathingCommand(Goal goal, PathingCommandType commandType) { this.goal = goal; this.commandType = commandType; + if (commandType == null) { + throw new IllegalArgumentException(); + } } } From 8aa5a6756aa040aa99c79edefa929333668ce1f6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 14:41:17 -0800 Subject: [PATCH 247/305] add to api --- src/api/java/baritone/api/BaritoneAPI.java | 10 ++++++++++ src/api/java/baritone/api/IBaritone.java | 10 +++++++++- src/main/java/baritone/Baritone.java | 2 ++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index bf878d33..b9dbcd04 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -23,7 +23,9 @@ import baritone.api.behavior.IPathingBehavior; import baritone.api.cache.IWorldProvider; import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IGameEventListener; +import baritone.api.process.ICustomGoalProcess; import baritone.api.process.IFollowProcess; +import baritone.api.process.IGetToBlockProcess; import baritone.api.process.IMineProcess; import baritone.api.utils.SettingsUtil; @@ -84,6 +86,14 @@ public final class BaritoneAPI { return baritone.getWorldScanner(); } + public static ICustomGoalProcess getCustomGoalProcess() { + return baritone.getCustomGoalProcess(); + } + + public static IGetToBlockProcess getGetToBlockProcess() { + return baritone.getGetToBlockProcess(); + } + public static void registerEventListener(IGameEventListener listener) { baritone.registerEventListener(listener); } diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index 2d1982cd..aee9dead 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -17,11 +17,15 @@ package baritone.api; -import baritone.api.behavior.*; +import baritone.api.behavior.ILookBehavior; +import baritone.api.behavior.IMemoryBehavior; +import baritone.api.behavior.IPathingBehavior; import baritone.api.cache.IWorldProvider; import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IGameEventListener; +import baritone.api.process.ICustomGoalProcess; import baritone.api.process.IFollowProcess; +import baritone.api.process.IGetToBlockProcess; import baritone.api.process.IMineProcess; /** @@ -72,6 +76,10 @@ public interface IBaritone { */ IWorldScanner getWorldScanner(); + ICustomGoalProcess getCustomGoalProcess(); + + IGetToBlockProcess getGetToBlockProcess(); + /** * Registers a {@link IGameEventListener} with Baritone's "event bus". * diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index b655dddc..1cd482cf 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -159,10 +159,12 @@ public enum Baritone implements IBaritone { this.registerEventListener(behavior); } + @Override public CustomGoalProcess getCustomGoalProcess() { return customGoalProcess; } + @Override public GetToBlockProcess getGetToBlockProcess() { // very very high iq return getToBlockProcess; } From cb153e039bb5e28bf3c76103111c750788fdb08e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 14:43:57 -0800 Subject: [PATCH 248/305] not used and not publicly exposed --- src/main/java/baritone/Baritone.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 1cd482cf..89806f98 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -82,11 +82,6 @@ public enum Baritone implements IBaritone { private PathingControlManager pathingControlManager; - /** - * Whether or not Baritone is active - */ - private boolean active; - Baritone() { this.gameEventHandler = new GameEventHandler(); } @@ -126,7 +121,6 @@ public enum Baritone implements IBaritone { } catch (IOException ignored) {} } - this.active = true; this.initialized = true; } @@ -209,10 +203,6 @@ public enum Baritone implements IBaritone { this.gameEventHandler.registerEventListener(listener); } - public boolean isActive() { - return this.active; - } - public Settings getSettings() { return this.settings; } From 4d0bfce7122a09d7f0c5e7ea8cfb3369e741a85e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 14:47:40 -0800 Subject: [PATCH 249/305] make InputOverrideHandler a Behavior --- src/main/java/baritone/Baritone.java | 14 +++++++++----- .../java/baritone/utils/InputOverrideHandler.java | 8 +++++++- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 89806f98..50320289 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -65,7 +65,6 @@ public enum Baritone implements IBaritone { private boolean initialized; private GameEventHandler gameEventHandler; - private InputOverrideHandler inputOverrideHandler; private Settings settings; private File dir; private ThreadPoolExecutor threadPool; @@ -74,6 +73,7 @@ public enum Baritone implements IBaritone { private PathingBehavior pathingBehavior; private LookBehavior lookBehavior; private MemoryBehavior memoryBehavior; + private InputOverrideHandler inputOverrideHandler; private FollowProcess followProcess; private MineProcess mineProcess; @@ -91,26 +91,30 @@ public enum Baritone implements IBaritone { return; } this.threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); - this.inputOverrideHandler = new InputOverrideHandler(); + // Acquire the "singleton" instance of the settings directly from the API // We might want to change this... this.settings = BaritoneAPI.getSettings(); - this.pathingControlManager = new PathingControlManager(this); - this.behaviors = new ArrayList<>(); { // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist pathingBehavior = new PathingBehavior(this); lookBehavior = new LookBehavior(this); memoryBehavior = new MemoryBehavior(this); + inputOverrideHandler = new InputOverrideHandler(this); + new ExampleBaritoneControl(this); + } + + this.pathingControlManager = new PathingControlManager(this); + { followProcess = new FollowProcess(this); mineProcess = new MineProcess(this); - new ExampleBaritoneControl(this); customGoalProcess = new CustomGoalProcess(this); // very high iq getToBlockProcess = new GetToBlockProcess(this); } + if (BaritoneAutoTest.ENABLE_AUTO_TEST) { registerEventListener(BaritoneAutoTest.INSTANCE); } diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 9cf7d1da..4d325fc7 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -17,6 +17,8 @@ package baritone.utils; +import baritone.Baritone; +import baritone.behavior.Behavior; import net.minecraft.client.settings.KeyBinding; import java.util.HashMap; @@ -30,7 +32,11 @@ import java.util.Map; * @author Brady * @since 7/31/2018 11:20 PM */ -public final class InputOverrideHandler implements Helper { +public final class InputOverrideHandler extends Behavior implements Helper { + + public InputOverrideHandler(Baritone baritone) { + super(baritone); + } /** * Maps keybinds to whether or not we are forcing their state down. From 2da3222115ece37de5aab28e1c21c9b35e2ae462 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 14:55:13 -0800 Subject: [PATCH 250/305] fix --- src/main/java/baritone/behavior/PathingBehavior.java | 1 + src/main/java/baritone/process/CustomGoalProcess.java | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 9582f3c5..d2a55127 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -87,6 +87,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, dispatchEvents(); if (event.getType() == TickEvent.Type.OUT) { secretInternalSegmentCancel(); + baritone.getPathingControlManager().cancelEverything(); return; } tickPath(); diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index 52769f25..1e1b7473 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -82,7 +82,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG if (calcFailed) { onLostControl(); } - if (goal.isInGoal(playerFeet())) { + if (goal == null || goal.isInGoal(playerFeet())) { onLostControl(); // we're there xd } return new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); From 52246e41c86ecba00b710b86544bd2babad60777 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 15:16:23 -0800 Subject: [PATCH 251/305] appease codacy --- src/main/java/baritone/utils/PathingControlManager.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index bfb84d3c..6d91b734 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -28,6 +28,7 @@ import net.minecraft.util.math.BlockPos; import java.util.Comparator; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; public class PathingControlManager { @@ -126,7 +127,7 @@ public class PathingControlManager { proc.onLostControl(); } } else { - exec = proc.onTick(proc == inControlLastTick && baritone.getPathingBehavior().calcFailedLastTick(), baritone.getPathingBehavior().isSafeToCancel()); + exec = proc.onTick(Objects.equals(proc, inControlLastTick) && baritone.getPathingBehavior().calcFailedLastTick(), baritone.getPathingBehavior().isSafeToCancel()); if (exec == null) { if (proc.isActive()) { throw new IllegalStateException(proc.displayName()); From 5692e79e021eaca2fe0671fa891747c53fc1f7e7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 15:25:19 -0800 Subject: [PATCH 252/305] more docs --- .../java/baritone/api/process/IBaritoneProcess.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/process/IBaritoneProcess.java b/src/api/java/baritone/api/process/IBaritoneProcess.java index d05bd8ef..a214d06d 100644 --- a/src/api/java/baritone/api/process/IBaritoneProcess.java +++ b/src/api/java/baritone/api/process/IBaritoneProcess.java @@ -34,7 +34,7 @@ public interface IBaritoneProcess { /** * Would this process like to be in control? * - * @return + * @return true if yes */ boolean isActive(); @@ -56,7 +56,7 @@ public interface IBaritoneProcess { * and should return isActive true only if there's something in range this tick, or if the player would like to start eating this tick. * PauseForAutoEatProcess should only actually right click once onTick is called with isSafeToCancel true though. * - * @return + * @return true if temporary */ boolean isTemporary(); @@ -69,21 +69,21 @@ public interface IBaritoneProcess { /** * How to decide which Process gets control if they all report isActive? It's the one with the highest priority. * - * @return + * @return a double representing the priority */ double priority(); /** * which bot is this associated with (5000000iq forward thinking) * - * @return + * @return the IBaritone object */ IBaritone associatedWith(); /** * What this process should be displayed to the user as (maybe in a HUD? hint hint) * - * @return + * @return a display name that's suitable for a HUD (hint hint) */ String displayName(); } From 472e89239cd1f0d8e6847368e093ed62a8f2df49 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 5 Nov 2018 18:07:47 -0600 Subject: [PATCH 253/305] IBaritoneProcess javadoc update --- .../api/process/IBaritoneProcess.java | 52 +++++++++++-------- .../api/process/ICustomGoalProcess.java | 1 + .../baritone/api/process/IFollowProcess.java | 1 - .../api/process/IGetToBlockProcess.java | 1 + 4 files changed, 33 insertions(+), 22 deletions(-) diff --git a/src/api/java/baritone/api/process/IBaritoneProcess.java b/src/api/java/baritone/api/process/IBaritoneProcess.java index a214d06d..db7588ab 100644 --- a/src/api/java/baritone/api/process/IBaritoneProcess.java +++ b/src/api/java/baritone/api/process/IBaritoneProcess.java @@ -18,6 +18,8 @@ package baritone.api.process; import baritone.api.IBaritone; +import baritone.api.behavior.IPathingBehavior; +import baritone.api.event.events.PathEvent; /** * A process that can control the PathingBehavior. @@ -31,59 +33,67 @@ import baritone.api.IBaritone; * @author leijurv */ public interface IBaritoneProcess { + /** * Would this process like to be in control? * - * @return true if yes + * @return Whether or not this process would like to be in contorl. */ boolean isActive(); /** - * This process is in control of pathing. What should Baritone do? + * Called when this process is in control of pathing; Returns what Baritone should do. * - * @param calcFailed true if this specific process was in control last tick, and there was a CALC_FAILED event last tick - * @param isSafeToCancel true if a REQUEST_PAUSE would happen this tick, and PathingBehavior wouldn't actually tick. - * false if the PathExecutor reported pausing would be unsafe at the end of the last tick. - * Effectively "could request cancel or pause and have it happen right away" - * @return what the PathingBehavior should do + * @param calcFailed {@code true} if this specific process was in control last tick, + * and there was a {@link PathEvent#CALC_FAILED} event last tick + * @param isSafeToCancel {@code true} if a {@link PathingCommandType#REQUEST_PAUSE} would happen this tick, and + * {@link IPathingBehavior} wouldn't actually tick. {@code false} if the PathExecutor reported + * pausing would be unsafe at the end of the last tick. Effectively "could request cancel or + * pause and have it happen right away" + * @return What the {@link IPathingBehavior} should do */ PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel); /** - * Is this control temporary? - * If a process is temporary, it doesn't call onLostControl on the processes that aren't execute because of it - * For example, CombatPauserProcess and PauseForAutoEatProcess should return isTemporary true always, - * and should return isActive true only if there's something in range this tick, or if the player would like to start eating this tick. - * PauseForAutoEatProcess should only actually right click once onTick is called with isSafeToCancel true though. + * Returns whether or not this process should be treated as "temporary". + *

+ * If a process is temporary, it doesn't call {@link #onLostControl} on the processes that aren't execute because of it. + *

+ * For example, {@code CombatPauserProcess} and {@code PauseForAutoEatProcess} should return {@code true} always, + * and should return {@link #isActive} {@code true} only if there's something in range this tick, or if the player would like + * to start eating this tick. {@code PauseForAutoEatProcess} should only actually right click once onTick is called with + * {@code isSafeToCancel} true though. * - * @return true if temporary + * @return Whethor or not if this control is temporary */ boolean isTemporary(); /** - * Called if isActive returned true, but another non-temporary process has control. Effectively the same as cancel. - * You want control but you don't get it. + * Called if {@link #isActive} returned {@code true}, but another non-temporary + * process has control. Effectively the same as cancel. You want control but you + * don't get it. */ void onLostControl(); /** - * How to decide which Process gets control if they all report isActive? It's the one with the highest priority. + * Used to determine which Process gains control if multiple are reporting {@link #isActive()}. The one + * that returns the highest value will be given control. * - * @return a double representing the priority + * @return A double representing the priority */ double priority(); /** - * which bot is this associated with (5000000iq forward thinking) + * Returns which bot this process is associated with. (5000000iq forward thinking) * - * @return the IBaritone object + * @return The Bot associated with this process */ IBaritone associatedWith(); /** - * What this process should be displayed to the user as (maybe in a HUD? hint hint) + * Returns a user-friendly name for this process. Suitable for a HUD. * - * @return a display name that's suitable for a HUD (hint hint) + * @return A display name that's suitable for a HUD */ String displayName(); } diff --git a/src/api/java/baritone/api/process/ICustomGoalProcess.java b/src/api/java/baritone/api/process/ICustomGoalProcess.java index c3492df9..0484d4c5 100644 --- a/src/api/java/baritone/api/process/ICustomGoalProcess.java +++ b/src/api/java/baritone/api/process/ICustomGoalProcess.java @@ -20,6 +20,7 @@ package baritone.api.process; import baritone.api.pathing.goals.Goal; public interface ICustomGoalProcess extends IBaritoneProcess { + void setGoal(Goal goal); void path(); diff --git a/src/api/java/baritone/api/process/IFollowProcess.java b/src/api/java/baritone/api/process/IFollowProcess.java index 262ce43f..cb9ecde6 100644 --- a/src/api/java/baritone/api/process/IFollowProcess.java +++ b/src/api/java/baritone/api/process/IFollowProcess.java @@ -17,7 +17,6 @@ package baritone.api.process; -import baritone.api.process.IBaritoneProcess; import net.minecraft.entity.Entity; /** diff --git a/src/api/java/baritone/api/process/IGetToBlockProcess.java b/src/api/java/baritone/api/process/IGetToBlockProcess.java index feaeb747..ff3dc9b5 100644 --- a/src/api/java/baritone/api/process/IGetToBlockProcess.java +++ b/src/api/java/baritone/api/process/IGetToBlockProcess.java @@ -23,5 +23,6 @@ import net.minecraft.block.Block; * but it rescans the world every once in a while so it doesn't get fooled by its cache */ public interface IGetToBlockProcess extends IBaritoneProcess { + void getToBlock(Block block); } From fdee1b94534114a4e0a589952a107b2950401244 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 5 Nov 2018 18:11:16 -0600 Subject: [PATCH 254/305] More javadocs --- .../java/baritone/api/process/PathingCommand.java | 2 ++ .../baritone/api/process/PathingCommandType.java | 14 +++++++++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/process/PathingCommand.java b/src/api/java/baritone/api/process/PathingCommand.java index 082928b3..0d0d7db3 100644 --- a/src/api/java/baritone/api/process/PathingCommand.java +++ b/src/api/java/baritone/api/process/PathingCommand.java @@ -20,7 +20,9 @@ package baritone.api.process; import baritone.api.pathing.goals.Goal; public class PathingCommand { + public final Goal goal; + public final PathingCommandType commandType; public PathingCommand(Goal goal, PathingCommandType commandType) { diff --git a/src/api/java/baritone/api/process/PathingCommandType.java b/src/api/java/baritone/api/process/PathingCommandType.java index 98517ba5..f2336d26 100644 --- a/src/api/java/baritone/api/process/PathingCommandType.java +++ b/src/api/java/baritone/api/process/PathingCommandType.java @@ -17,11 +17,14 @@ package baritone.api.process; +import baritone.api.Settings; + public enum PathingCommandType { + /** * Set the goal and path. *

- * If you use this alongside a null goal, it will continue along its current path and current goal. + * If you use this alongside a {@code null} goal, it will continue along its current path and current goal. */ SET_GOAL_AND_PATH, @@ -31,21 +34,22 @@ public enum PathingCommandType { REQUEST_PAUSE, /** - * Set the goal (regardless of null), and request a cancel of the current path (when safe) + * Set the goal (regardless of {@code null}), and request a cancel of the current path (when safe) */ CANCEL_AND_SET_GOAL, /** * Set the goal and path. *

- * If cancelOnGoalInvalidation is true, revalidate the current goal, and cancel if it's no longer valid, or if the new goal is null. + * If {@link Settings#cancelOnGoalInvalidation} is {@code true}, revalidate the + * current goal, and cancel if it's no longer valid, or if the new goal is {@code null}. */ REVALIDATE_GOAL_AND_PATH, /** * Set the goal and path. *

- * Revalidate the current goal, and cancel if it's no longer valid, or if the new goal is null. + * Revalidate the current goal, and cancel if it's no longer valid, or if the new goal is {@code null}. */ - FORCE_REVALIDATE_GOAL_AND_PATH, + FORCE_REVALIDATE_GOAL_AND_PATH } From ebd3ce42d04ee8ca52d6d1af3451ff653d960ca6 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 5 Nov 2018 18:28:29 -0600 Subject: [PATCH 255/305] whoops --- src/api/java/baritone/api/behavior/IPathingBehavior.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index 622c453a..c8728965 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -50,11 +50,12 @@ public interface IPathingBehavior extends IBehavior { boolean isPathing(); /** - * Cancels the pathing behavior or the current path calculation. Also cancels all processes that could be controlling path. + * Cancels the pathing behavior or the current path calculation, and all processes that could be controlling path. *

* Basically, "MAKE IT STOP". * - * @return whether or not the pathing behavior was canceled. All processes are guaranteed to be canceled, but the PathingBehavior might be in the middle of an uncancelable action like a parkour jump + * @return Whether or not the pathing behavior was canceled. All processes are guaranteed to be canceled, but the + * PathingBehavior might be in the middle of an uncancelable action like a parkour jump */ boolean cancelEverything(); From 99da815f49fe1bd4bcbc7314cac3a37e44312371 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 5 Nov 2018 18:40:25 -0600 Subject: [PATCH 256/305] Massive brain --- .../api/process/ICustomGoalProcess.java | 22 ++++++- .../baritone/process/CustomGoalProcess.java | 58 ++++++++++++------- 2 files changed, 56 insertions(+), 24 deletions(-) diff --git a/src/api/java/baritone/api/process/ICustomGoalProcess.java b/src/api/java/baritone/api/process/ICustomGoalProcess.java index 0484d4c5..5084aff2 100644 --- a/src/api/java/baritone/api/process/ICustomGoalProcess.java +++ b/src/api/java/baritone/api/process/ICustomGoalProcess.java @@ -21,12 +21,30 @@ import baritone.api.pathing.goals.Goal; public interface ICustomGoalProcess extends IBaritoneProcess { + /** + * Sets the pathing goal + * + * @param goal The new goal + */ void setGoal(Goal goal); + /** + * Starts path calculation and execution. + */ void path(); + /** + * @return The current goal + */ + Goal getGoal(); + + /** + * Sets the goal and begins the path execution. + * + * @param goal The new goal + */ default void setGoalAndPath(Goal goal) { - setGoal(goal); - path(); + this.setGoal(goal); + this.path(); } } diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index 1e1b7473..8b3d1773 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -32,7 +32,17 @@ import java.util.Objects; * @author leijurv */ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomGoalProcess { + + /** + * The current goal + */ private Goal goal; + + /** + * The current process state. + * + * @see State + */ private State state; public CustomGoalProcess(Baritone baritone) { @@ -42,50 +52,47 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG @Override public void setGoal(Goal goal) { this.goal = goal; - state = State.GOAL_SET; + this.state = State.GOAL_SET; } @Override public void path() { - if (goal == null) { - goal = baritone.getPathingBehavior().getGoal(); + if (this.goal == null) { + this.goal = baritone.getPathingBehavior().getGoal(); } - state = State.PATH_REQUESTED; + this.state = State.PATH_REQUESTED; } - private enum State { - NONE, - GOAL_SET, - PATH_REQUESTED, - EXECUTING, - + @Override + public Goal getGoal() { + return this.goal; } @Override public boolean isActive() { - return state != State.NONE; + return this.state != State.NONE; } @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { - switch (state) { + switch (this.state) { case GOAL_SET: - if (!baritone.getPathingBehavior().isPathing() && Objects.equals(baritone.getPathingBehavior().getGoal(), goal)) { - state = State.NONE; + if (!baritone.getPathingBehavior().isPathing() && Objects.equals(baritone.getPathingBehavior().getGoal(), this.goal)) { + this.state = State.NONE; } - return new PathingCommand(goal, PathingCommandType.CANCEL_AND_SET_GOAL); + return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL); case PATH_REQUESTED: - PathingCommand ret = new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); - state = State.EXECUTING; + PathingCommand ret = new PathingCommand(this.goal, PathingCommandType.SET_GOAL_AND_PATH); + this.state = State.EXECUTING; return ret; case EXECUTING: if (calcFailed) { onLostControl(); } - if (goal == null || goal.isInGoal(playerFeet())) { + if (this.goal == null || this.goal.isInGoal(playerFeet())) { onLostControl(); // we're there xd } - return new PathingCommand(goal, PathingCommandType.SET_GOAL_AND_PATH); + return new PathingCommand(this.goal, PathingCommandType.SET_GOAL_AND_PATH); default: throw new IllegalStateException(); } @@ -93,12 +100,19 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG @Override public void onLostControl() { - state = State.NONE; - goal = null; + this.state = State.NONE; + this.goal = null; } @Override public String displayName() { - return "Custom Goal " + goal; + return "Custom Goal " + this.goal; + } + + protected enum State { + NONE, + GOAL_SET, + PATH_REQUESTED, + EXECUTING } } From 2aee91be102db254026d090413480947160a37d8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 16:46:24 -0800 Subject: [PATCH 257/305] fix it up a bit --- .../baritone/process/CustomGoalProcess.java | 3 --- .../utils/ExampleBaritoneControl.java | 20 +++++++++---------- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index 8b3d1773..98c700e3 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -57,9 +57,6 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG @Override public void path() { - if (this.goal == null) { - this.goal = baritone.getPathingBehavior().getGoal(); - } this.state = State.PATH_REQUESTED; } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 74c17d60..e908d1c4 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -100,7 +100,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { public boolean runCommand(String msg0) { String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL PathingBehavior pathingBehavior = baritone.getPathingBehavior(); - CustomGoalProcess CGPgrey = baritone.getCustomGoalProcess(); + CustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); List> toggleable = Baritone.settings().getAllValuesByType(Boolean.class); for (Settings.Setting setting : toggleable) { if (msg.equalsIgnoreCase(setting.getName())) { @@ -188,7 +188,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("unable to parse integer " + ex); return true; } - CGPgrey.setGoal(goal); + customGoalProcess.setGoal(goal); logDirect("Goal: " + goal); return true; } @@ -200,7 +200,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } else if (pathingBehavior.isPathing()) { logDirect("Currently executing a path. Please cancel it first."); } else { - CGPgrey.path(); + customGoalProcess.setGoalAndPath(pathingBehavior.getGoal()); } return true; } @@ -222,7 +222,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("axis")) { - CGPgrey.setGoalAndPath(new GoalAxis()); + customGoalProcess.setGoalAndPath(new GoalAxis()); return true; } if (msg.equals("cancel") || msg.equals("stop")) { @@ -254,7 +254,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Inverting goal of player feet"); runAwayFrom = playerFeet(); } - CGPgrey.setGoalAndPath(new GoalRunAway(1, runAwayFrom) { + customGoalProcess.setGoalAndPath(new GoalRunAway(1, runAwayFrom) { @Override public boolean isInGoal(int x, int y, int z) { return false; @@ -329,7 +329,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { if (msg.startsWith("thisway")) { try { Goal goal = GoalXZ.fromDirection(playerFeetAsVec(), player().rotationYaw, Double.parseDouble(msg.substring(7).trim())); - CGPgrey.setGoal(goal); + customGoalProcess.setGoal(goal); logDirect("Goal: " + goal); } catch (NumberFormatException ex) { logDirect("Error unable to parse '" + msg.substring(7).trim() + "' to a double."); @@ -409,7 +409,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } Goal goal = new GoalBlock(waypoint.getLocation()); - CGPgrey.setGoalAndPath(goal); + customGoalProcess.setGoalAndPath(goal); return true; } if (msg.equals("spawn") || msg.equals("bed")) { @@ -419,10 +419,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper { // for some reason the default spawnpoint is underground sometimes Goal goal = new GoalXZ(spawnPoint.getX(), spawnPoint.getZ()); logDirect("spawn not saved, defaulting to world spawn. set goal to " + goal); - CGPgrey.setGoalAndPath(goal); + customGoalProcess.setGoalAndPath(goal); } else { Goal goal = new GoalGetToBlock(waypoint.getLocation()); - CGPgrey.setGoalAndPath(goal); + customGoalProcess.setGoalAndPath(goal); logDirect("Set goal to most recent bed " + goal); } return true; @@ -438,7 +438,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("home not saved"); } else { Goal goal = new GoalBlock(waypoint.getLocation()); - CGPgrey.setGoalAndPath(goal); + customGoalProcess.setGoalAndPath(goal); logDirect("Going to saved home " + goal); } return true; From d121ca182f2dedc08c3ec20c774caf61d13c5968 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 17:26:49 -0800 Subject: [PATCH 258/305] spammy --- src/main/java/baritone/utils/PathingControlManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 6d91b734..e75f7796 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -135,7 +135,7 @@ public class PathingControlManager { proc.onLostControl(); continue; } - System.out.println("Executing command " + exec.commandType + " " + exec.goal + " from " + proc.displayName()); + //System.out.println("Executing command " + exec.commandType + " " + exec.goal + " from " + proc.displayName()); inControlThisTick = proc; found = true; cancelOthers = !proc.isTemporary(); From d59c7cb7a8b0deaa28d516799345ce191834c809 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 17:30:45 -0800 Subject: [PATCH 259/305] temporarily disable cached region ram pruning --- src/api/java/baritone/api/Settings.java | 9 ++++++++- src/main/java/baritone/cache/CachedWorld.java | 3 +++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 0d8529dd..9cd69f95 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -24,8 +24,8 @@ import net.minecraft.util.text.ITextComponent; import java.awt.*; import java.lang.reflect.Field; -import java.util.List; import java.util.*; +import java.util.List; import java.util.function.Consumer; /** @@ -276,6 +276,13 @@ public class Settings { */ public Setting chunkCaching = new Setting<>(true); + /** + * On save, delete from RAM any cached regions that are more than 1024 blocks away from the player + *

+ * Temporarily disabled, see issue #248 + */ + public Setting pruneRegionsFromRAM = new Setting<>(false); + /** * Print all the debug messages to chat */ diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 14b66839..a5641eea 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -165,6 +165,9 @@ public final class CachedWorld implements ICachedWorld, Helper { * Delete regions that are too far from the player */ private synchronized void prune() { + if (!Baritone.settings().pruneRegionsFromRAM.get()) { + return; + } BlockPos pruneCenter = guessPosition(); for (CachedRegion region : allRegions()) { if (region == null) { From a1b71219cbbe9426e18aa4f68a20e4ddfb18d1ed Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 18:31:59 -0800 Subject: [PATCH 260/305] make sure to pick up dropped items while mining, fixes #170 --- src/api/java/baritone/api/Settings.java | 7 +++- .../baritone/process/GetToBlockProcess.java | 2 +- .../java/baritone/process/MineProcess.java | 42 +++++++++++++++---- 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 0d8529dd..6fbd14c6 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -24,8 +24,8 @@ import net.minecraft.util.text.ITextComponent; import java.awt.*; import java.lang.reflect.Field; -import java.util.List; import java.util.*; +import java.util.List; import java.util.function.Consumer; /** @@ -376,6 +376,11 @@ public class Settings { */ public Setting mineGoalUpdateInterval = new Setting<>(5); + /** + * While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)? + */ + public Setting mineScanDroppedItems = new Setting<>(true); + /** * Cancel the current path if the goal has changed, and the path originally ended in the goal but doesn't anymore. *

diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 7f5340ed..d35b4fb4 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -94,6 +94,6 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } private void rescan() { - knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64); + knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64, world()); } } \ No newline at end of file diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 2efeca03..e4f3db21 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -32,10 +32,13 @@ import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import net.minecraft.block.Block; +import net.minecraft.entity.Entity; +import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; import net.minecraft.world.chunk.EmptyChunk; import java.util.*; @@ -112,7 +115,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro private Goal updateGoal() { List locs = knownOreLocations; if (!locs.isEmpty()) { - List locs2 = prune(new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT); + List locs2 = prune(new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT, world()); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new)); knownOreLocations = locs2; @@ -147,7 +150,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (Baritone.settings().legitMine.get()) { return; } - List locs = searchWorld(mining, ORE_LOCATIONS_COUNT); + List locs = searchWorld(mining, ORE_LOCATIONS_COUNT, world()); + locs.addAll(droppedItemsScan(mining, world())); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); cancel(); @@ -178,7 +182,30 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } - public static List searchWorld(List mining, int max) { + public static List droppedItemsScan(List mining, World world) { + if (!Baritone.settings().mineScanDroppedItems.get()) { + return new ArrayList<>(); + } + Set searchingFor = new HashSet<>(); + for (Block block : mining) { + Item drop = block.getItemDropped(block.getDefaultState(), new Random(), 0); + Item ore = Item.getItemFromBlock(block); + searchingFor.add(drop); + searchingFor.add(ore); + } + List ret = new ArrayList<>(); + for (Entity entity : world.loadedEntityList) { + if (entity instanceof EntityItem) { + EntityItem ei = (EntityItem) entity; + if (searchingFor.contains(ei.getItem().getItem())) { + ret.add(entity.getPosition()); + } + } + } + return ret; + } + + public static List searchWorld(List mining, int max, World world) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); //long b = System.currentTimeMillis(); @@ -198,7 +225,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(uninteresting, max, 10, 26)); //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); } - return prune(locs, mining, max); + return prune(locs, mining, max, world); } public void addNearby() { @@ -214,15 +241,16 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } } - knownOreLocations = prune(knownOreLocations, mining, ORE_LOCATIONS_COUNT); + knownOreLocations = prune(knownOreLocations, mining, ORE_LOCATIONS_COUNT, world()); } - public static List prune(List locs2, List mining, int max) { + public static List prune(List locs2, List mining, int max, World world) { + List dropped = droppedItemsScan(mining, world); List locs = locs2 .stream() // remove any that are within loaded chunks that aren't actually what we want - .filter(pos -> Helper.HELPER.world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock())) + .filter(pos -> world.getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock()) || dropped.contains(pos)) // remove any that are implausible to mine (encased in bedrock, or touching lava) .filter(MineProcess::plausibleToBreak) From 6ca7f47bf9de5f54a9f17c8404482d123ff76fb7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 19:31:05 -0800 Subject: [PATCH 261/305] +0.5y not helpful --- src/main/java/baritone/process/MineProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index e4f3db21..bfceac75 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -198,7 +198,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (entity instanceof EntityItem) { EntityItem ei = (EntityItem) entity; if (searchingFor.contains(ei.getItem().getItem())) { - ret.add(entity.getPosition()); + ret.add(new BlockPos(entity)); } } } From 604ef2bb64e98c61d6201e3c41fa9336bfc04be0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 20:01:46 -0800 Subject: [PATCH 262/305] misc cleanup --- src/main/java/baritone/Baritone.java | 14 +++++++------- .../java/baritone/behavior/PathingBehavior.java | 4 ++-- src/main/java/baritone/cache/CachedWorld.java | 4 ++-- src/main/java/baritone/cache/WorldData.java | 2 +- src/main/java/baritone/cache/WorldProvider.java | 4 ++-- src/main/java/baritone/event/GameEventHandler.java | 8 +++++++- .../java/baritone/pathing/movement/Movement.java | 6 ------ .../java/baritone/process/GetToBlockProcess.java | 2 +- 8 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 50320289..69dc1b2a 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -67,7 +67,7 @@ public enum Baritone implements IBaritone { private GameEventHandler gameEventHandler; private Settings settings; private File dir; - private ThreadPoolExecutor threadPool; + private List behaviors; private PathingBehavior pathingBehavior; @@ -82,16 +82,16 @@ public enum Baritone implements IBaritone { private PathingControlManager pathingControlManager; + private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); + Baritone() { - this.gameEventHandler = new GameEventHandler(); + this.gameEventHandler = new GameEventHandler(this); } public synchronized void init() { if (initialized) { return; } - this.threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); - // Acquire the "singleton" instance of the settings directly from the API // We might want to change this... @@ -148,7 +148,7 @@ public enum Baritone implements IBaritone { return this.behaviors; } - public Executor getExecutor() { + public static Executor getExecutor() { return threadPool; } @@ -215,7 +215,7 @@ public enum Baritone implements IBaritone { return Baritone.INSTANCE.settings; // yolo } - public File getDir() { - return this.dir; + public static File getDir() { + return Baritone.INSTANCE.dir; // should be static I guess } } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index d2a55127..77c9839d 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -78,7 +78,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, toDispatch.drainTo(curr); calcFailedLastTick = curr.contains(PathEvent.CALC_FAILED); for (PathEvent event : curr) { - Baritone.INSTANCE.getGameEventHandler().onPathEvent(event); + baritone.getGameEventHandler().onPathEvent(event); } } @@ -370,7 +370,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, isPathCalcInProgress = true; } CalculationContext context = new CalculationContext(); // not safe to create on the other thread, it looks up a lot of stuff in minecraft - Baritone.INSTANCE.getExecutor().execute(() -> { + Baritone.getExecutor().execute(() -> { if (talkAboutIt) { logDebug("Starting to search for path from " + start + " to " + goal); } diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 14b66839..48e4ccb2 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -67,8 +67,8 @@ public final class CachedWorld implements ICachedWorld, Helper { System.out.println("Cached world directory: " + directory); // Insert an invalid region element cachedRegions.put(0, null); - Baritone.INSTANCE.getExecutor().execute(new PackerThread()); - Baritone.INSTANCE.getExecutor().execute(() -> { + Baritone.getExecutor().execute(new PackerThread()); + Baritone.getExecutor().execute(() -> { try { Thread.sleep(30000); while (true) { diff --git a/src/main/java/baritone/cache/WorldData.java b/src/main/java/baritone/cache/WorldData.java index b489d933..36a239fa 100644 --- a/src/main/java/baritone/cache/WorldData.java +++ b/src/main/java/baritone/cache/WorldData.java @@ -43,7 +43,7 @@ public class WorldData implements IWorldData { } public void onClose() { - Baritone.INSTANCE.getExecutor().execute(() -> { + Baritone.getExecutor().execute(() -> { System.out.println("Started saving the world in a new thread"); cache.save(); }); diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index 2aef54c6..e3a53bba 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -74,8 +74,8 @@ public enum WorldProvider implements IWorldProvider, Helper { } else { //remote - directory = new File(Baritone.INSTANCE.getDir(), mc.getCurrentServerData().serverIP); - readme = Baritone.INSTANCE.getDir(); + directory = new File(Baritone.getDir(), mc.getCurrentServerData().serverIP); + readme = Baritone.getDir(); } // lol wtf is this baritone folder in my minecraft save? try (FileOutputStream out = new FileOutputStream(new File(readme, "readme.txt"))) { diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index e7cd5847..fd031a0a 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -37,8 +37,14 @@ import java.util.ArrayList; */ public final class GameEventHandler implements IGameEventListener, Helper { + private final Baritone baritone; + private final ArrayList listeners = new ArrayList<>(); + public GameEventHandler(Baritone baritone) { + this.baritone = baritone; + } + @Override public final void onTick(TickEvent event) { listeners.forEach(l -> l.onTick(event)); @@ -51,7 +57,7 @@ public final class GameEventHandler implements IGameEventListener, Helper { @Override public final void onProcessKeyBinds() { - InputOverrideHandler inputHandler = Baritone.INSTANCE.getInputOverrideHandler(); + InputOverrideHandler inputHandler = baritone.getInputOverrideHandler(); // Simulate the key being held down this tick for (InputOverrideHandler.Input input : InputOverrideHandler.Input.values()) { diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index aacd7f9f..0bdedbf0 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -226,12 +226,6 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { state.getInputStates().forEach((input, forced) -> Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(input, forced)); } - public void cancel() { - currentState.getInputStates().replaceAll((input, forced) -> false); - currentState.getInputStates().forEach((input, forced) -> Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(input, forced)); - currentState.setStatus(MovementStatus.CANCELED); - } - @Override public void reset() { currentState = new MovementState().setStatus(MovementStatus.PREPPING); diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index d35b4fb4..94e02e03 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -73,7 +73,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain - Baritone.INSTANCE.getExecutor().execute(this::rescan); + Baritone.getExecutor().execute(this::rescan); } Goal goal = new GoalComposite(knownLocations.stream().map(GoalGetToBlock::new).toArray(Goal[]::new)); if (goal.isInGoal(playerFeet())) { From aac0d623fa238f0c8b7eed1ed10028ea5b6c1145 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 20:02:27 -0800 Subject: [PATCH 263/305] why not just... --- src/launch/java/baritone/launch/mixins/MixinMinecraft.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index b559ae86..3826f0d7 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -83,10 +83,9 @@ public class MixinMinecraft { ) ) private void runTick(CallbackInfo ci) { - Minecraft mc = (Minecraft) (Object) this; Baritone.INSTANCE.getGameEventHandler().onTick(new TickEvent( EventState.PRE, - (mc.player != null && mc.world != null) + (player != null && world != null) ? TickEvent.Type.IN : TickEvent.Type.OUT )); From a182c22d369315d95207a741ed6b67c04b5fea16 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 20:05:47 -0800 Subject: [PATCH 264/305] this can be moved i think --- .../java/baritone/event/GameEventHandler.java | 18 ------------------ .../baritone/utils/InputOverrideHandler.java | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index fd031a0a..1de1b728 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -24,10 +24,7 @@ import baritone.api.event.listener.IGameEventListener; import baritone.cache.WorldProvider; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; -import baritone.utils.InputOverrideHandler; -import net.minecraft.client.settings.KeyBinding; import net.minecraft.world.chunk.Chunk; -import org.lwjgl.input.Keyboard; import java.util.ArrayList; @@ -57,21 +54,6 @@ public final class GameEventHandler implements IGameEventListener, Helper { @Override public final void onProcessKeyBinds() { - InputOverrideHandler inputHandler = baritone.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 -> l.onProcessKeyBinds()); } diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 4d325fc7..f7239d0b 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -20,6 +20,7 @@ package baritone.utils; import baritone.Baritone; import baritone.behavior.Behavior; import net.minecraft.client.settings.KeyBinding; +import org.lwjgl.input.Keyboard; import java.util.HashMap; import java.util.Map; @@ -67,6 +68,22 @@ public final class InputOverrideHandler extends Behavior implements Helper { inputForceStateMap.put(input.getKeyBinding(), forced); } + @Override + public final void onProcessKeyBinds() { + // Simulate the key being held down this tick + for (InputOverrideHandler.Input input : Input.values()) { + KeyBinding keyBinding = input.getKeyBinding(); + + if (isInputForcedDown(keyBinding) && !keyBinding.isKeyDown()) { + int keyCode = keyBinding.getKeyCode(); + + if (keyCode < Keyboard.KEYBOARD_SIZE) { + KeyBinding.onTick(keyCode < 0 ? keyCode + 100 : keyCode); + } + } + } + } + /** * An {@link Enum} representing the possible inputs that we may want to force. */ From 527691a2ec803ff05c80d2f8aba333c4e183d899 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 5 Nov 2018 20:37:54 -0800 Subject: [PATCH 265/305] fix blockbreakhelper toxic cloud in movement --- .../baritone/pathing/movement/Movement.java | 47 ++++--------------- .../java/baritone/utils/BlockBreakHelper.java | 20 +++++++- .../baritone/utils/InputOverrideHandler.java | 12 +++++ 3 files changed, 39 insertions(+), 40 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 0bdedbf0..fb316ed3 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -24,14 +24,12 @@ import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.VecUtils; -import baritone.utils.BlockBreakHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.InputOverrideHandler; import net.minecraft.block.BlockLiquid; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.chunk.EmptyChunk; import java.util.ArrayList; @@ -115,52 +113,31 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { @Override public MovementStatus update() { player().capabilities.isFlying = false; - MovementState latestState = updateState(currentState); + currentState = updateState(currentState); if (MovementHelper.isLiquid(playerFeet())) { - latestState.setInput(Input.JUMP, true); + currentState.setInput(Input.JUMP, true); } if (player().isEntityInsideOpaqueBlock()) { - latestState.setInput(Input.CLICK_LEFT, true); + currentState.setInput(Input.CLICK_LEFT, 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 -> + currentState.getTarget().getRotation().ifPresent(rotation -> Baritone.INSTANCE.getLookBehavior().updateTarget( rotation, - latestState.getTarget().hasToForceRotations())); + currentState.getTarget().hasToForceRotations())); // 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) -> { - if (Baritone.settings().leftClickWorkaround.get()) { - 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; - } - } + currentState.getInputStates().forEach((input, forced) -> { Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(input, forced); }); - latestState.getInputStates().replaceAll((input, forced) -> false); - - if (!this.didBreakLastTick) { - BlockBreakHelper.stopBreakingBlock(); - } - - currentState = latestState; + currentState.getInputStates().replaceAll((input, forced) -> false); // If the current status indicates a completed movement if (currentState.getStatus().isComplete()) { - onFinish(latestState); + Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys(); } return currentState.getStatus(); @@ -218,14 +195,6 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { return dest; } - /** - * Run cleanup on state finish and declare success. - */ - public void onFinish(MovementState state) { - state.getInputStates().replaceAll((input, forced) -> false); - state.getInputStates().forEach((input, forced) -> Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(input, forced)); - } - @Override public void reset() { currentState = new MovementState().setStatus(MovementStatus.PREPPING); diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index 1bc4a44a..b1e9ae53 100644 --- a/src/main/java/baritone/utils/BlockBreakHelper.java +++ b/src/main/java/baritone/utils/BlockBreakHelper.java @@ -20,6 +20,7 @@ package baritone.utils; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; /** * @author Brady @@ -32,6 +33,7 @@ public final class BlockBreakHelper implements Helper { * between attempts, then we re-initialize the breaking process. */ private static BlockPos lastBlock; + private static boolean didBreakLastTick; private BlockBreakHelper() {} @@ -48,7 +50,23 @@ public final class BlockBreakHelper implements Helper { public static void stopBreakingBlock() { if (mc.playerController != null) { mc.playerController.resetBlockRemoving(); - } + } lastBlock = null; } + + public static boolean tick(boolean isLeftClick) { + RayTraceResult trace = mc.objectMouseOver; + boolean isBlockTrace = trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK; + + // 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) { + tryBreakBlock(trace.getBlockPos(), trace.sideHit); + didBreakLastTick = true; + } else if (didBreakLastTick) { + stopBreakingBlock(); + didBreakLastTick = false; + } + return !didBreakLastTick && isLeftClick; + } } diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index f7239d0b..b42b0ee1 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -18,6 +18,7 @@ package baritone.utils; import baritone.Baritone; +import baritone.api.event.events.TickEvent; import baritone.behavior.Behavior; import net.minecraft.client.settings.KeyBinding; import org.lwjgl.input.Keyboard; @@ -84,6 +85,17 @@ public final class InputOverrideHandler extends Behavior implements Helper { } } + @Override + public final void onTick(TickEvent event) { + if (event.getType() == TickEvent.Type.OUT) { + return; + } + if (Baritone.settings().leftClickWorkaround.get()) { + boolean stillClick = BlockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.keyBinding)); + setInputForceState(Input.CLICK_LEFT, stillClick); + } + } + /** * An {@link Enum} representing the possible inputs that we may want to force. */ From c50af5acfd5239181ed96e663307e5784e341415 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 6 Nov 2018 08:02:08 -0600 Subject: [PATCH 266/305] A couple minor cleanups --- .../java/baritone/api/IBaritoneProvider.java | 13 ++++++++- .../baritone/api/process/PathingCommand.java | 28 +++++++++++++++++-- .../java/baritone/event/GameEventHandler.java | 7 +++-- 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index 9bd96e7e..745842ce 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -19,6 +19,17 @@ package baritone.api; import net.minecraft.client.entity.EntityPlayerSP; +/** + * @author Leijurv + */ public interface IBaritoneProvider { - IBaritone getBaritoneForPlayer(EntityPlayerSP player); // tenor be like + + /** + * Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. This will likely be + * replaced with {@code #getBaritoneForUser(IBaritoneUser)} when {@code bot-system} is merged. + * + * @param player The player + * @return The {@link IBaritone} instance. + */ + IBaritone getBaritoneForPlayer(EntityPlayerSP player); } diff --git a/src/api/java/baritone/api/process/PathingCommand.java b/src/api/java/baritone/api/process/PathingCommand.java index 0d0d7db3..753e1a2d 100644 --- a/src/api/java/baritone/api/process/PathingCommand.java +++ b/src/api/java/baritone/api/process/PathingCommand.java @@ -19,17 +19,39 @@ package baritone.api.process; import baritone.api.pathing.goals.Goal; +import java.util.Objects; + +/** + * @author Leijurv + */ public class PathingCommand { + /** + * The target goal, may be {@code null}. + */ public final Goal goal; + /** + * The command type. + * + * @see PathingCommandType + */ public final PathingCommandType commandType; + /** + * Create a new {@link PathingCommand}. + * + * @see Goal + * @see PathingCommandType + * + * @param goal The target goal, may be {@code null}. + * @param commandType The command type, cannot be {@code null}. + * @throws NullPointerException if {@code commandType} is {@code null}. + */ public PathingCommand(Goal goal, PathingCommandType commandType) { + Objects.requireNonNull(commandType); + this.goal = goal; this.commandType = commandType; - if (commandType == null) { - throw new IllegalArgumentException(); - } } } diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 1de1b728..b42b3e06 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -27,6 +27,7 @@ import baritone.utils.Helper; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; +import java.util.List; /** * @author Brady @@ -36,7 +37,7 @@ public final class GameEventHandler implements IGameEventListener, Helper { private final Baritone baritone; - private final ArrayList listeners = new ArrayList<>(); + private final List listeners = new ArrayList<>(); public GameEventHandler(Baritone baritone) { this.baritone = baritone; @@ -54,7 +55,7 @@ public final class GameEventHandler implements IGameEventListener, Helper { @Override public final void onProcessKeyBinds() { - listeners.forEach(l -> l.onProcessKeyBinds()); + listeners.forEach(IGameEventListener::onProcessKeyBinds); } @Override @@ -131,7 +132,7 @@ public final class GameEventHandler implements IGameEventListener, Helper { @Override public void onPlayerDeath() { - listeners.forEach(l -> l.onPlayerDeath()); + listeners.forEach(IGameEventListener::onPlayerDeath); } @Override From ae200a56b008782bd1131c607597ffa47cb9cb94 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 6 Nov 2018 08:19:26 -0800 Subject: [PATCH 267/305] CaPiTaLiZe --- src/api/java/baritone/api/process/PathingCommand.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/process/PathingCommand.java b/src/api/java/baritone/api/process/PathingCommand.java index 753e1a2d..2caef158 100644 --- a/src/api/java/baritone/api/process/PathingCommand.java +++ b/src/api/java/baritone/api/process/PathingCommand.java @@ -22,7 +22,7 @@ import baritone.api.pathing.goals.Goal; import java.util.Objects; /** - * @author Leijurv + * @author leijurv */ public class PathingCommand { @@ -41,12 +41,11 @@ public class PathingCommand { /** * Create a new {@link PathingCommand}. * - * @see Goal - * @see PathingCommandType - * - * @param goal The target goal, may be {@code null}. + * @param goal The target goal, may be {@code null}. * @param commandType The command type, cannot be {@code null}. * @throws NullPointerException if {@code commandType} is {@code null}. + * @see Goal + * @see PathingCommandType */ public PathingCommand(Goal goal, PathingCommandType commandType) { Objects.requireNonNull(commandType); From 382c7e78882267a8275102eae5dacce9452a210a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 6 Nov 2018 08:22:19 -0800 Subject: [PATCH 268/305] reformat, optimize imports --- src/api/java/baritone/api/behavior/ILookBehavior.java | 2 +- src/api/java/baritone/api/behavior/IPathingBehavior.java | 2 +- src/api/java/baritone/api/cache/ICachedRegion.java | 3 +-- src/api/java/baritone/api/cache/ICachedWorld.java | 4 ++-- src/api/java/baritone/api/cache/IWaypointCollection.java | 6 ++---- src/api/java/baritone/api/pathing/calc/IPath.java | 3 +-- .../java/baritone/launch/mixins/MixinAnvilChunkLoader.java | 4 +++- .../baritone/launch/mixins/MixinChunkProviderServer.java | 4 +++- src/launch/java/baritone/launch/mixins/MixinEntity.java | 3 ++- .../java/baritone/launch/mixins/MixinEntityRenderer.java | 2 +- .../java/baritone/launch/mixins/MixinNetworkManager.java | 3 ++- src/main/java/baritone/cache/Waypoint.java | 6 +++--- 12 files changed, 22 insertions(+), 20 deletions(-) diff --git a/src/api/java/baritone/api/behavior/ILookBehavior.java b/src/api/java/baritone/api/behavior/ILookBehavior.java index b5b5d63b..058a5dd8 100644 --- a/src/api/java/baritone/api/behavior/ILookBehavior.java +++ b/src/api/java/baritone/api/behavior/ILookBehavior.java @@ -33,7 +33,7 @@ public interface ILookBehavior extends IBehavior { * otherwise, it should be {@code false}; * * @param rotation The target rotations - * @param force Whether or not to "force" the rotations + * @param force Whether or not to "force" the rotations */ void updateTarget(Rotation rotation, boolean force); } diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index c8728965..e9ebe405 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -55,7 +55,7 @@ public interface IPathingBehavior extends IBehavior { * Basically, "MAKE IT STOP". * * @return Whether or not the pathing behavior was canceled. All processes are guaranteed to be canceled, but the - * PathingBehavior might be in the middle of an uncancelable action like a parkour jump + * PathingBehavior might be in the middle of an uncancelable action like a parkour jump */ boolean cancelEverything(); diff --git a/src/api/java/baritone/api/cache/ICachedRegion.java b/src/api/java/baritone/api/cache/ICachedRegion.java index 5f9199fa..6b9048a5 100644 --- a/src/api/java/baritone/api/cache/ICachedRegion.java +++ b/src/api/java/baritone/api/cache/ICachedRegion.java @@ -29,11 +29,10 @@ public interface ICachedRegion extends IBlockTypeAccess { * however, the block coordinates should in on a scale from 0 to 511 (inclusive) * because region sizes are 512x512 blocks. * - * @see ICachedWorld#isCached(int, int) - * * @param blockX The block X coordinate * @param blockZ The block Z coordinate * @return Whether or not the specified XZ location is cached + * @see ICachedWorld#isCached(int, int) */ boolean isCached(int blockX, int blockZ); diff --git a/src/api/java/baritone/api/cache/ICachedWorld.java b/src/api/java/baritone/api/cache/ICachedWorld.java index f8196ebb..5e06a475 100644 --- a/src/api/java/baritone/api/cache/ICachedWorld.java +++ b/src/api/java/baritone/api/cache/ICachedWorld.java @@ -61,8 +61,8 @@ public interface ICachedWorld { * information that is returned by this method may not be up to date, because * older cached chunks can contain data that is much more likely to have changed. * - * @param block The special block to search for - * @param maximum The maximum number of position results to receive + * @param block The special block to search for + * @param maximum The maximum number of position results to receive * @param maxRegionDistanceSq The maximum region distance, squared * @return The locations found that match the special block */ diff --git a/src/api/java/baritone/api/cache/IWaypointCollection.java b/src/api/java/baritone/api/cache/IWaypointCollection.java index 051b199e..4dd80a3e 100644 --- a/src/api/java/baritone/api/cache/IWaypointCollection.java +++ b/src/api/java/baritone/api/cache/IWaypointCollection.java @@ -50,19 +50,17 @@ public interface IWaypointCollection { /** * Gets all of the waypoints that have the specified tag * - * @see IWaypointCollection#getAllWaypoints() - * * @param tag The tag * @return All of the waypoints with the specified tag + * @see IWaypointCollection#getAllWaypoints() */ Set getByTag(IWaypoint.Tag tag); /** * Gets all of the waypoints in this collection, regardless of the tag. * - * @see IWaypointCollection#getByTag(IWaypoint.Tag) - * * @return All of the waypoints in this collection + * @see IWaypointCollection#getByTag(IWaypoint.Tag) */ Set getAllWaypoints(); } diff --git a/src/api/java/baritone/api/pathing/calc/IPath.java b/src/api/java/baritone/api/pathing/calc/IPath.java index c9d58818..fddc0232 100644 --- a/src/api/java/baritone/api/pathing/calc/IPath.java +++ b/src/api/java/baritone/api/pathing/calc/IPath.java @@ -125,10 +125,9 @@ public interface IPath { * Cuts off this path using the min length and cutoff factor settings, and returns the resulting path. * Default implementation just returns this path, without the intended functionality. * + * @return The result of this cut-off operation * @see Settings#pathCutoffMinimumLength * @see Settings#pathCutoffFactor - * - * @return The result of this cut-off operation */ default IPath staticCutoff(Goal destination) { return this; diff --git a/src/launch/java/baritone/launch/mixins/MixinAnvilChunkLoader.java b/src/launch/java/baritone/launch/mixins/MixinAnvilChunkLoader.java index 4ffb5abc..8b3ea0af 100644 --- a/src/launch/java/baritone/launch/mixins/MixinAnvilChunkLoader.java +++ b/src/launch/java/baritone/launch/mixins/MixinAnvilChunkLoader.java @@ -32,7 +32,9 @@ import java.io.File; @Mixin(AnvilChunkLoader.class) public class MixinAnvilChunkLoader implements IAnvilChunkLoader { - @Shadow @Final private File chunkSaveLocation; + @Shadow + @Final + private File chunkSaveLocation; @Override public File getChunkSaveLocation() { diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkProviderServer.java b/src/launch/java/baritone/launch/mixins/MixinChunkProviderServer.java index 246c368e..6d5a5421 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkProviderServer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkProviderServer.java @@ -31,7 +31,9 @@ import org.spongepowered.asm.mixin.Shadow; @Mixin(ChunkProviderServer.class) public class MixinChunkProviderServer implements IChunkProviderServer { - @Shadow @Final private IChunkLoader chunkLoader; + @Shadow + @Final + private IChunkLoader chunkLoader; @Override public IChunkLoader getChunkLoader() { diff --git a/src/launch/java/baritone/launch/mixins/MixinEntity.java b/src/launch/java/baritone/launch/mixins/MixinEntity.java index db8b513f..c2a1e107 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntity.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntity.java @@ -37,7 +37,8 @@ import static org.spongepowered.asm.lib.Opcodes.GETFIELD; @Mixin(Entity.class) public class MixinEntity { - @Shadow public float rotationYaw; + @Shadow + public float rotationYaw; /** * Event called to override the movement direction when walking diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java b/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java index 0fc1b246..174b9e3c 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java @@ -33,7 +33,7 @@ public class MixinEntityRenderer { at = @At( value = "INVOKE_STRING", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", - args = { "ldc=hand" } + args = {"ldc=hand"} ) ) private void renderWorldPass(int pass, float partialTicks, long finishTimeNano, CallbackInfo ci) { diff --git a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java index 3f5f297b..bf15bfc3 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java @@ -77,7 +77,8 @@ public class MixinNetworkManager { ) private void preProcessPacket(ChannelHandlerContext context, Packet packet, CallbackInfo ci) { if (this.direction == EnumPacketDirection.CLIENTBOUND) { - Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet));} + Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet)); + } } @Inject( diff --git a/src/main/java/baritone/cache/Waypoint.java b/src/main/java/baritone/cache/Waypoint.java index 00f4410a..19e574f9 100644 --- a/src/main/java/baritone/cache/Waypoint.java +++ b/src/main/java/baritone/cache/Waypoint.java @@ -42,9 +42,9 @@ public class Waypoint implements IWaypoint { * Constructor called when a Waypoint is read from disk, adds the creationTimestamp * as a parameter so that it is reserved after a waypoint is wrote to the disk. * - * @param name The waypoint name - * @param tag The waypoint tag - * @param location The waypoint location + * @param name The waypoint name + * @param tag The waypoint tag + * @param location The waypoint location * @param creationTimestamp When the waypoint was created */ Waypoint(String name, Tag tag, BlockPos location, long creationTimestamp) { From 9c93d3a474d41dc6eb07af47e1fd1af3d4ac2142 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 6 Nov 2018 11:18:13 -0800 Subject: [PATCH 269/305] splice next into current if no backtrack, fixes #122, fixes #249 --- src/api/java/baritone/api/Settings.java | 10 +++ .../java/baritone/api/pathing/calc/IPath.java | 30 +++++++ .../baritone/behavior/PathingBehavior.java | 6 +- src/main/java/baritone/pathing/calc/Path.java | 27 +----- .../pathing/{calc => path}/CutoffPath.java | 13 ++- .../baritone/pathing/path/PathExecutor.java | 37 ++++++++ .../baritone/pathing/path/SplicedPath.java | 88 +++++++++++++++++++ 7 files changed, 180 insertions(+), 31 deletions(-) rename src/main/java/baritone/pathing/{calc => path}/CutoffPath.java (78%) create mode 100644 src/main/java/baritone/pathing/path/SplicedPath.java diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 8cf6a845..48385313 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -377,6 +377,16 @@ public class Settings { */ public Setting walkWhileBreaking = new Setting<>(true); + /** + * If we are more than 500 movements into the current path, discard the oldest segments, as they are no longer useful + */ + public Setting maxPathHistoryLength = new Setting<>(500); + + /** + * If the current path is too long, cut off this many movements from the beginning. + */ + public Setting pathHistoryCutoffAmount = new Setting<>(100); + /** * Rescan for the goal once every 5 ticks. * Set to 0 to disable. diff --git a/src/api/java/baritone/api/pathing/calc/IPath.java b/src/api/java/baritone/api/pathing/calc/IPath.java index fddc0232..f2309e0e 100644 --- a/src/api/java/baritone/api/pathing/calc/IPath.java +++ b/src/api/java/baritone/api/pathing/calc/IPath.java @@ -21,6 +21,7 @@ import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; import baritone.api.utils.BetterBlockPos; +import net.minecraft.util.math.BlockPos; import java.util.List; @@ -132,4 +133,33 @@ public interface IPath { default IPath staticCutoff(Goal destination) { return this; } + + + /** + * Performs a series of checks to ensure that the assembly of the path went as expected. + */ + default void sanityCheck() { + List path = positions(); + List movements = movements(); + if (!getSrc().equals(path.get(0))) { + throw new IllegalStateException("Start node does not equal first path element"); + } + if (!getDest().equals(path.get(path.size() - 1))) { + throw new IllegalStateException("End node does not equal last path element"); + } + if (path.size() != movements.size() + 1) { + throw new IllegalStateException("Size of path array is unexpected"); + } + for (int i = 0; i < path.size() - 1; i++) { + BlockPos src = path.get(i); + BlockPos dest = path.get(i + 1); + IMovement movement = movements.get(i); + if (!src.equals(movement.getSrc())) { + throw new IllegalStateException("Path source is not equal to the movement source"); + } + if (!dest.equals(movement.getDest())) { + throw new IllegalStateException("Path destination is not equal to the movement destination"); + } + } + } } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 77c9839d..53b771da 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -31,9 +31,9 @@ import baritone.api.utils.BetterBlockPos; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AbstractNodeCostSearch; -import baritone.pathing.calc.CutoffPath; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; +import baritone.pathing.path.CutoffPath; import baritone.pathing.path.PathExecutor; import baritone.utils.BlockBreakHelper; import baritone.utils.Helper; @@ -156,6 +156,10 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, current.onTick(); return; } + current = current.trySplice(next); + if (next != null && current.getPath().getDest().equals(next.getPath().getDest())) { + next = null; + } synchronized (pathCalcLock) { if (isPathCalcInProgress) { // if we aren't calculating right now diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index adcd9b71..93f021c6 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -24,6 +24,7 @@ import baritone.api.pathing.movement.IMovement; import baritone.api.utils.BetterBlockPos; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; +import baritone.pathing.path.CutoffPath; import net.minecraft.client.Minecraft; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; @@ -104,32 +105,6 @@ class Path implements IPath { path.addAll(tempPath); } - /** - * Performs a series of checks to ensure that the assembly of the path went as expected. - */ - private void sanityCheck() { - if (!start.equals(path.get(0))) { - throw new IllegalStateException("Start node does not equal first path element"); - } - if (!end.equals(path.get(path.size() - 1))) { - throw new IllegalStateException("End node does not equal last path element"); - } - if (path.size() != movements.size() + 1) { - throw new IllegalStateException("Size of path array is unexpected"); - } - for (int i = 0; i < path.size() - 1; i++) { - BlockPos src = path.get(i); - BlockPos dest = path.get(i + 1); - Movement movement = movements.get(i); - if (!src.equals(movement.getSrc())) { - throw new IllegalStateException("Path source is not equal to the movement source"); - } - if (!dest.equals(movement.getDest())) { - throw new IllegalStateException("Path destination is not equal to the movement destination"); - } - } - } - private void assembleMovements() { if (path.isEmpty() || !movements.isEmpty()) { throw new IllegalStateException(); diff --git a/src/main/java/baritone/pathing/calc/CutoffPath.java b/src/main/java/baritone/pathing/path/CutoffPath.java similarity index 78% rename from src/main/java/baritone/pathing/calc/CutoffPath.java rename to src/main/java/baritone/pathing/path/CutoffPath.java index 53e0c560..9714d8ce 100644 --- a/src/main/java/baritone/pathing/calc/CutoffPath.java +++ b/src/main/java/baritone/pathing/path/CutoffPath.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.pathing.calc; +package baritone.pathing.path; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; @@ -35,11 +35,16 @@ public class CutoffPath implements IPath { private final Goal goal; - CutoffPath(IPath prev, int lastPositionToInclude) { - path = prev.positions().subList(0, lastPositionToInclude + 1); - movements = prev.movements().subList(0, lastPositionToInclude + 1); + public CutoffPath(IPath prev, int firstPositionToInclude, int lastPositionToInclude) { + path = prev.positions().subList(firstPositionToInclude, lastPositionToInclude + 1); + movements = prev.movements().subList(firstPositionToInclude, lastPositionToInclude); numNodes = prev.getNumNodesConsidered(); goal = prev.getGoal(); + sanityCheck(); + } + + public CutoffPath(IPath prev, int lastPositionToInclude) { + this(prev, 0, lastPositionToInclude); } @Override diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index e5f9c864..5cc472e6 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -454,6 +454,43 @@ public class PathExecutor implements IPathExecutor, Helper { return pathPosition; } + public PathExecutor trySplice(PathExecutor next) { + if (next == null) { + return cutIfTooLong(); + } + return SplicedPath.trySplice(path, next.path).map(path -> { + if (!path.getDest().equals(next.getPath().getDest())) { + throw new IllegalStateException(); + } + PathExecutor ret = new PathExecutor(path); + ret.pathPosition = pathPosition; + ret.currentMovementOriginalCostEstimate = currentMovementOriginalCostEstimate; + ret.costEstimateIndex = costEstimateIndex; + ret.ticksOnCurrent = ticksOnCurrent; + return ret; + }).orElse(cutIfTooLong()); + } + + private PathExecutor cutIfTooLong() { + if (pathPosition > Baritone.settings().maxPathHistoryLength.get()) { + int cutoffAmt = Baritone.settings().pathHistoryCutoffAmount.get(); + CutoffPath newPath = new CutoffPath(path, cutoffAmt, path.length() - 1); + if (!newPath.getDest().equals(path.getDest())) { + throw new IllegalStateException(); + } + logDebug("Discarding earliest segment movements, length cut from " + path.length() + " to " + newPath.length()); + PathExecutor ret = new PathExecutor(newPath); + ret.pathPosition = pathPosition - cutoffAmt; + ret.currentMovementOriginalCostEstimate = currentMovementOriginalCostEstimate; + if (costEstimateIndex != null) { + ret.costEstimateIndex = costEstimateIndex - cutoffAmt; + } + ret.ticksOnCurrent = ticksOnCurrent; + return ret; + } + return this; + } + @Override public IPath getPath() { return path; diff --git a/src/main/java/baritone/pathing/path/SplicedPath.java b/src/main/java/baritone/pathing/path/SplicedPath.java new file mode 100644 index 00000000..33b0b97f --- /dev/null +++ b/src/main/java/baritone/pathing/path/SplicedPath.java @@ -0,0 +1,88 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.pathing.path; + +import baritone.api.pathing.calc.IPath; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.movement.IMovement; +import baritone.api.utils.BetterBlockPos; + +import java.util.*; + +public class SplicedPath implements IPath { + private final List path; + + private final List movements; + + private final int numNodes; + + private final Goal goal; + + private SplicedPath(List path, List movements, int numNodesConsidered, Goal goal) { + this.path = path; + this.movements = movements; + this.numNodes = numNodesConsidered; + this.goal = goal; + sanityCheck(); + } + + @Override + public Goal getGoal() { + return goal; + } + + @Override + public List movements() { + return Collections.unmodifiableList(movements); + } + + @Override + public List positions() { + return Collections.unmodifiableList(path); + } + + @Override + public int getNumNodesConsidered() { + return numNodes; + } + + public static Optional trySplice(IPath first, IPath second) { + if (second == null || first == null) { + return Optional.empty(); + } + if (!Objects.equals(first.getGoal(), second.getGoal())) { + return Optional.empty(); + } + if (!first.getDest().equals(second.getSrc())) { + return Optional.empty(); + } + HashSet a = new HashSet<>(first.positions()); + for (int i = 1; i < second.length(); i++) { + if (a.contains(second.positions().get(i))) { + return Optional.empty(); + } + } + List positions = new ArrayList<>(); + List movements = new ArrayList<>(); + positions.addAll(first.positions()); + positions.addAll(second.positions().subList(1, second.length())); + movements.addAll(first.movements()); + movements.addAll(second.movements()); + return Optional.of(new SplicedPath(positions, movements, first.getNumNodesConsidered() + second.getNumNodesConsidered(), first.getGoal())); + } +} From a1778f401f96441c7e7e4c7c102ba9d2b78224c2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 6 Nov 2018 11:20:39 -0800 Subject: [PATCH 270/305] tweak a bit --- src/api/java/baritone/api/Settings.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 48385313..419e8e71 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -380,12 +380,12 @@ public class Settings { /** * If we are more than 500 movements into the current path, discard the oldest segments, as they are no longer useful */ - public Setting maxPathHistoryLength = new Setting<>(500); + public Setting maxPathHistoryLength = new Setting<>(300); /** * If the current path is too long, cut off this many movements from the beginning. */ - public Setting pathHistoryCutoffAmount = new Setting<>(100); + public Setting pathHistoryCutoffAmount = new Setting<>(50); /** * Rescan for the goal once every 5 ticks. From 83348e6b3cc0c8f9dcbc60426be84a6e320af303 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 6 Nov 2018 20:12:02 -0800 Subject: [PATCH 271/305] rearrange readme --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ef568f0c..d88647f3 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,13 @@ [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) -A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), -the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). +A Minecraft pathfinder bot. Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. +This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), +the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). + Here are some links to help to get started: - [Features](FEATURES.md) From 4a1951b027867a1400fc31dd183901d3782a5015 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 7 Nov 2018 14:09:23 -0800 Subject: [PATCH 272/305] many fixes --- src/api/java/baritone/api/Settings.java | 2 +- .../api/pathing/calc/IPathFinder.java | 3 +- .../api/process/PathingCommandType.java | 2 +- .../api/utils/PathCalculationResult.java | 41 +++++++++++++++++++ .../baritone/behavior/PathingBehavior.java | 15 ++++--- .../pathing/calc/AbstractNodeCostSearch.java | 15 ++++++- .../baritone/process/GetToBlockProcess.java | 13 +++--- .../java/baritone/process/MineProcess.java | 30 +++++++++----- .../baritone/utils/PathingControlManager.java | 13 +++++- 9 files changed, 108 insertions(+), 26 deletions(-) create mode 100644 src/api/java/baritone/api/utils/PathCalculationResult.java diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 419e8e71..e2e4604d 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -411,7 +411,7 @@ public class Settings { *

* Also on cosmic prisons this should be set to true since you don't actually mine the ore it just gets replaced with stone. */ - public Setting cancelOnGoalInvalidation = new Setting<>(false); + public Setting cancelOnGoalInvalidation = new Setting<>(true); /** * The "axis" command (aka GoalAxis) will go to a axis, or diagonal axis, at this Y level. diff --git a/src/api/java/baritone/api/pathing/calc/IPathFinder.java b/src/api/java/baritone/api/pathing/calc/IPathFinder.java index 446f7e05..f70196a6 100644 --- a/src/api/java/baritone/api/pathing/calc/IPathFinder.java +++ b/src/api/java/baritone/api/pathing/calc/IPathFinder.java @@ -18,6 +18,7 @@ package baritone.api.pathing.calc; import baritone.api.pathing.goals.Goal; +import baritone.api.utils.PathCalculationResult; import java.util.Optional; @@ -35,7 +36,7 @@ public interface IPathFinder { * * @return The final path */ - Optional calculate(long timeout); + PathCalculationResult calculate(long timeout); /** * Intended to be called concurrently with calculatePath from a different thread to tell if it's finished yet diff --git a/src/api/java/baritone/api/process/PathingCommandType.java b/src/api/java/baritone/api/process/PathingCommandType.java index f2336d26..da64748a 100644 --- a/src/api/java/baritone/api/process/PathingCommandType.java +++ b/src/api/java/baritone/api/process/PathingCommandType.java @@ -49,7 +49,7 @@ public enum PathingCommandType { /** * Set the goal and path. *

- * Revalidate the current goal, and cancel if it's no longer valid, or if the new goal is {@code null}. + * Cancel the current path if the goals are not equal */ FORCE_REVALIDATE_GOAL_AND_PATH } diff --git a/src/api/java/baritone/api/utils/PathCalculationResult.java b/src/api/java/baritone/api/utils/PathCalculationResult.java new file mode 100644 index 00000000..69d2a9b3 --- /dev/null +++ b/src/api/java/baritone/api/utils/PathCalculationResult.java @@ -0,0 +1,41 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils; + +import baritone.api.pathing.calc.IPath; + +import java.util.Optional; + +public class PathCalculationResult { + + public final Optional path; + public final Type type; + + public PathCalculationResult(Type type, Optional path) { + this.path = path; + this.type = type; + } + + public enum Type { + SUCCESS_TO_GOAL, + SUCCESS_SEGMENT, + FAILURE, + CANCELLATION, + EXCEPTION, + } +} diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 53b771da..6315e15f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -28,6 +28,7 @@ import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.PathCalculationResult; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AbstractNodeCostSearch; @@ -379,7 +380,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, logDebug("Starting to search for path from " + start + " to " + goal); } - Optional path = findPath(start, previous, context); + PathCalculationResult calcResult = findPath(start, previous, context); + Optional path = calcResult.path; if (Baritone.settings().cutoffAtLoadBoundary.get()) { path = path.map(p -> { IPath result = p.cutoffAtLoadedChunks(); @@ -411,7 +413,10 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, queuePathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING); current = executor.get(); } else { - queuePathEvent(PathEvent.CALC_FAILED); + if (calcResult.type != PathCalculationResult.Type.CANCELLATION && calcResult.type != PathCalculationResult.Type.EXCEPTION) { + // don't dispatch CALC_FAILED on cancellation + queuePathEvent(PathEvent.CALC_FAILED); + } } } else { if (next == null) { @@ -447,11 +452,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * @param start * @return */ - private Optional findPath(BlockPos start, Optional previous, CalculationContext context) { + private PathCalculationResult findPath(BlockPos start, Optional previous, CalculationContext context) { Goal goal = this.goal; if (goal == null) { logDebug("no goal"); - return Optional.empty(); + return new PathCalculationResult(PathCalculationResult.Type.CANCELLATION, Optional.empty()); } if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) { BlockPos pos = ((IGoalRenderPos) goal).getGoalPos(); @@ -478,7 +483,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } catch (Exception e) { logDebug("Pathing exception: " + e); e.printStackTrace(); - return Optional.empty(); + return new PathCalculationResult(PathCalculationResult.Type.EXCEPTION, Optional.empty()); } } diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index bbbe32ad..981ff733 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -21,6 +21,7 @@ import baritone.Baritone; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; +import baritone.api.utils.PathCalculationResult; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import java.util.Optional; @@ -82,7 +83,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { cancelRequested = true; } - public synchronized Optional calculate(long timeout) { + public synchronized PathCalculationResult calculate(long timeout) { if (isFinished) { throw new IllegalStateException("Path Finder is currently in use, and cannot be reused!"); } @@ -91,7 +92,17 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { Optional path = calculate0(timeout); path.ifPresent(IPath::postProcess); isFinished = true; - return path; + if (cancelRequested) { + return new PathCalculationResult(PathCalculationResult.Type.CANCELLATION, path); + } + if (!path.isPresent()) { + return new PathCalculationResult(PathCalculationResult.Type.FAILURE, path); + } + if (goal.isInGoal(path.get().getDest())) { + return new PathCalculationResult(PathCalculationResult.Type.SUCCESS_TO_GOAL, path); + } else { + return new PathCalculationResult(PathCalculationResult.Type.SUCCESS_SEGMENT, path); + } } finally { // this is run regardless of what exception may or may not be raised by calculate0 currentlyRunning = null; diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 94e02e03..241fafa1 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -28,6 +28,7 @@ import baritone.utils.BaritoneProcessHelper; import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; +import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -44,7 +45,8 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl @Override public void getToBlock(Block block) { gettingTo = block; - rescan(); + knownLocations = null; + rescan(new ArrayList<>()); } @Override @@ -55,7 +57,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (knownLocations == null) { - rescan(); + rescan(new ArrayList<>()); } if (knownLocations.isEmpty()) { logDirect("No known locations of " + gettingTo + ", canceling GetToBlock"); @@ -73,7 +75,8 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain - Baritone.getExecutor().execute(this::rescan); + List current = new ArrayList<>(knownLocations); + Baritone.getExecutor().execute(() -> rescan(current)); } Goal goal = new GoalComposite(knownLocations.stream().map(GoalGetToBlock::new).toArray(Goal[]::new)); if (goal.isInGoal(playerFeet())) { @@ -93,7 +96,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl return "Get To Block " + gettingTo; } - private void rescan() { - knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64, world()); + private void rescan(List known) { + knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64, world(), known); } } \ No newline at end of file diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index bfceac75..48325dbb 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -87,7 +87,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain - baritone.getExecutor().execute(this::rescan); + List curr = new ArrayList<>(knownOreLocations); + baritone.getExecutor().execute(() -> rescan(curr)); } if (Baritone.settings().legitMine.get()) { addNearby(); @@ -99,7 +100,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro cancel(); return null; } - return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH); + return new PathingCommand(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); } @Override @@ -126,8 +127,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return null; } // only in non-Xray mode (aka legit mode) do we do this + int y = Baritone.settings().legitMineYLevel.get(); if (branchPoint == null) { - int y = Baritone.settings().legitMineYLevel.get(); if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) { // cool, path is over and we are at desired y branchPoint = playerFeet(); @@ -136,21 +137,26 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } - if (playerFeet().equals(branchPoint)) { + /*if (playerFeet().equals(branchPoint)) { // TODO mine 1x1 shafts to either side branchPoint = branchPoint.north(10); - } - return new GoalBlock(branchPoint); + }*/ + return new GoalRunAway(1, Optional.of(y), branchPoint) { + @Override + public boolean isInGoal(int x, int y, int z) { + return false; + } + }; } - private void rescan() { + private void rescan(List already) { if (mining == null) { return; } if (Baritone.settings().legitMine.get()) { return; } - List locs = searchWorld(mining, ORE_LOCATIONS_COUNT, world()); + List locs = searchWorld(mining, ORE_LOCATIONS_COUNT, world(), already); locs.addAll(droppedItemsScan(mining, world())); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); @@ -205,7 +211,10 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return ret; } - public static List searchWorld(List mining, int max, World world) { + /*public static List searchWorld(List mining, int max, World world) { + + }*/ + public static List searchWorld(List mining, int max, World world, List alreadyKnown) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); //long b = System.currentTimeMillis(); @@ -225,6 +234,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(uninteresting, max, 10, 26)); //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); } + locs.addAll(alreadyKnown); return prune(locs, mining, max, world); } @@ -283,6 +293,6 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro this.desiredQuantity = quantity; this.knownOreLocations = new ArrayList<>(); this.branchPoint = null; - rescan(); + rescan(new ArrayList<>()); } } diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index e75f7796..5d1b0303 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -78,7 +78,7 @@ public class PathingControlManager { break; case FORCE_REVALIDATE_GOAL_AND_PATH: p.secretInternalSetGoalAndPath(cmd.goal); - if (cmd.goal == null || revalidateGoal(cmd.goal)) { + if (cmd.goal == null || forceRevalidate(cmd.goal) || revalidateGoal(cmd.goal)) { // pwnage p.cancelSegmentIfSafe(); } @@ -100,6 +100,17 @@ public class PathingControlManager { } } + public boolean forceRevalidate(Goal newGoal) { + PathExecutor current = baritone.getPathingBehavior().getCurrent(); + if (current != null) { + if (newGoal.isInGoal(current.getPath().getDest())) { + return false; + } + return !newGoal.toString().equals(current.getPath().getGoal().toString()); + } + return false; + } + public boolean revalidateGoal(Goal newGoal) { PathExecutor current = baritone.getPathingBehavior().getCurrent(); if (current != null) { From 96da07821977227966255d57bf479b50f86648c3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 7 Nov 2018 14:37:23 -0800 Subject: [PATCH 273/305] cutoff path up until movement failure, don't throw exception and fail entire path --- .../java/baritone/api/pathing/calc/IPath.java | 4 +- src/main/java/baritone/pathing/calc/Path.java | 54 +++++++++++++------ .../baritone/pathing/movement/Movement.java | 2 +- 3 files changed, 42 insertions(+), 18 deletions(-) diff --git a/src/api/java/baritone/api/pathing/calc/IPath.java b/src/api/java/baritone/api/pathing/calc/IPath.java index f2309e0e..05e0a3bc 100644 --- a/src/api/java/baritone/api/pathing/calc/IPath.java +++ b/src/api/java/baritone/api/pathing/calc/IPath.java @@ -52,7 +52,9 @@ public interface IPath { * This path is actually going to be executed in the world. Do whatever additional processing is required. * (as opposed to Path objects that are just constructed every frame for rendering) */ - default void postProcess() {} + default IPath postProcess() { + return this; + } /** * Returns the number of positions in this path. Equivalent to {@code positions().size()}. diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 93f021c6..de13bd34 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -25,6 +25,7 @@ import baritone.api.utils.BetterBlockPos; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.pathing.path.CutoffPath; +import baritone.utils.Helper; import net.minecraft.client.Minecraft; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; @@ -59,6 +60,8 @@ class Path implements IPath { private final List movements; + private final List nodes; + private final Goal goal; private final int numNodes; @@ -71,8 +74,9 @@ class Path implements IPath { this.numNodes = numNodes; this.path = new ArrayList<>(); this.movements = new ArrayList<>(); + this.nodes = new ArrayList<>(); this.goal = goal; - assemblePath(start, end); + assemblePath(end); } @Override @@ -81,62 +85,80 @@ class Path implements IPath { } /** - * Assembles this path given the start and end nodes. + * Assembles this path given the end node. * - * @param start The start node - * @param end The end node + * @param end The end node */ - private void assemblePath(PathNode start, PathNode end) { + private void assemblePath(PathNode end) { if (!path.isEmpty() || !movements.isEmpty()) { throw new IllegalStateException(); } PathNode current = end; LinkedList tempPath = new LinkedList<>(); + LinkedList tempNodes = new LinkedList(); // Repeatedly inserting to the beginning of an arraylist is O(n^2) // Instead, do it into a linked list, then convert at the end - while (!current.equals(start)) { + while (current != null) { + tempNodes.addFirst(current); tempPath.addFirst(new BetterBlockPos(current.x, current.y, current.z)); current = current.previous; } - tempPath.addFirst(this.start); // Can't directly convert from the PathNode pseudo linked list to an array because we don't know how long it is // inserting into a LinkedList keeps track of length, then when we addall (which calls .toArray) it's able // to performantly do that conversion since it knows the length. path.addAll(tempPath); + nodes.addAll(tempNodes); } - private void assembleMovements() { + private boolean assembleMovements() { if (path.isEmpty() || !movements.isEmpty()) { throw new IllegalStateException(); } for (int i = 0; i < path.size() - 1; i++) { - movements.add(runBackwards(path.get(i), path.get(i + 1))); + double cost = nodes.get(i + 1).cost - nodes.get(i).cost; + Movement move = runBackwards(path.get(i), path.get(i + 1), cost); + if (move == null) { + return true; + } else { + movements.add(move); + } } + return false; } - private static Movement runBackwards(BetterBlockPos src, BetterBlockPos dest) { // TODO this is horrifying + private static Movement runBackwards(BetterBlockPos src, BetterBlockPos dest, double cost) { for (Moves moves : Moves.values()) { Movement move = moves.apply0(src); if (move.getDest().equals(dest)) { - // TODO instead of recalculating here, could we take pathNode.cost - pathNode.prevNode.cost to get the cost as-calculated? - move.recalculateCost(); // have to calculate the cost at calculation time so we can accurately judge whether a cost increase happened between cached calculation and real execution + // have to calculate the cost at calculation time so we can accurately judge whether a cost increase happened between cached calculation and real execution + move.override(cost); return move; } } // this is no longer called from bestPathSoFar, now it's in postprocessing - throw new IllegalStateException("Movement became impossible during calculation " + src + " " + dest + " " + dest.subtract(src)); + Helper.HELPER.logDebug("Movement became impossible during calculation " + src + " " + dest + " " + dest.subtract(src)); + return null; } @Override - public void postProcess() { + public IPath postProcess() { if (verified) { throw new IllegalStateException(); } verified = true; - assembleMovements(); - // more post processing here + boolean failed = assembleMovements(); movements.forEach(Movement::checkLoadedChunk); + + if (failed) { // at least one movement became impossible during calculation + CutoffPath res = new CutoffPath(this, movements().size()); + if (res.movements().size() != movements.size()) { + throw new IllegalStateException(); + } + return res; + } + // more post processing here sanityCheck(); + return this; } @Override diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index fb316ed3..31dd952b 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -95,7 +95,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { return getCost(); } - protected void override(double cost) { + public void override(double cost) { this.cost = cost; } From 842e50adb97abfe9b5783e4b9b12dae9bde1493a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 7 Nov 2018 17:16:34 -0800 Subject: [PATCH 274/305] path cleanup --- .../pathing/calc/AbstractNodeCostSearch.java | 2 +- src/main/java/baritone/pathing/calc/Path.java | 31 +---------- .../baritone/pathing/path/CutoffPath.java | 3 +- .../baritone/pathing/path/SplicedPath.java | 3 +- .../java/baritone/utils/pathing/PathBase.java | 52 +++++++++++++++++++ 5 files changed, 59 insertions(+), 32 deletions(-) create mode 100644 src/main/java/baritone/utils/pathing/PathBase.java diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 981ff733..708b5ab0 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -90,7 +90,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { this.cancelRequested = false; try { Optional path = calculate0(timeout); - path.ifPresent(IPath::postProcess); + path = path.map(IPath::postProcess); isFinished = true; if (cancelRequested) { return new PathCalculationResult(PathCalculationResult.Type.CANCELLATION, path); diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index de13bd34..873fef64 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -17,7 +17,6 @@ package baritone.pathing.calc; -import baritone.api.BaritoneAPI; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; @@ -26,9 +25,7 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.pathing.path.CutoffPath; import baritone.utils.Helper; -import net.minecraft.client.Minecraft; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.chunk.EmptyChunk; +import baritone.utils.pathing.PathBase; import java.util.ArrayList; import java.util.Collections; @@ -40,7 +37,7 @@ import java.util.List; * * @author leijurv */ -class Path implements IPath { +class Path extends PathBase { /** * The start position of this path @@ -188,28 +185,4 @@ class Path implements IPath { public BetterBlockPos getDest() { return end; } - - @Override - public IPath cutoffAtLoadedChunks() { - for (int i = 0; i < positions().size(); i++) { - BlockPos pos = positions().get(i); - if (Minecraft.getMinecraft().world.getChunk(pos) instanceof EmptyChunk) { - return new CutoffPath(this, i); - } - } - return this; - } - - @Override - public IPath staticCutoff(Goal destination) { - if (length() < BaritoneAPI.getSettings().pathCutoffMinimumLength.get()) { - return this; - } - if (destination == null || destination.isInGoal(getDest())) { - return this; - } - double factor = BaritoneAPI.getSettings().pathCutoffFactor.get(); - int newLength = (int) (length() * factor); - return new CutoffPath(this, newLength); - } } diff --git a/src/main/java/baritone/pathing/path/CutoffPath.java b/src/main/java/baritone/pathing/path/CutoffPath.java index 9714d8ce..30b2d4e9 100644 --- a/src/main/java/baritone/pathing/path/CutoffPath.java +++ b/src/main/java/baritone/pathing/path/CutoffPath.java @@ -21,11 +21,12 @@ import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; import baritone.api.utils.BetterBlockPos; +import baritone.utils.pathing.PathBase; import java.util.Collections; import java.util.List; -public class CutoffPath implements IPath { +public class CutoffPath extends PathBase { private final List path; diff --git a/src/main/java/baritone/pathing/path/SplicedPath.java b/src/main/java/baritone/pathing/path/SplicedPath.java index 33b0b97f..5048a84a 100644 --- a/src/main/java/baritone/pathing/path/SplicedPath.java +++ b/src/main/java/baritone/pathing/path/SplicedPath.java @@ -21,10 +21,11 @@ import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; import baritone.api.utils.BetterBlockPos; +import baritone.utils.pathing.PathBase; import java.util.*; -public class SplicedPath implements IPath { +public class SplicedPath extends PathBase { private final List path; private final List movements; diff --git a/src/main/java/baritone/utils/pathing/PathBase.java b/src/main/java/baritone/utils/pathing/PathBase.java new file mode 100644 index 00000000..57ee941d --- /dev/null +++ b/src/main/java/baritone/utils/pathing/PathBase.java @@ -0,0 +1,52 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils.pathing; + +import baritone.api.BaritoneAPI; +import baritone.api.pathing.calc.IPath; +import baritone.api.pathing.goals.Goal; +import baritone.pathing.path.CutoffPath; +import net.minecraft.client.Minecraft; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.chunk.EmptyChunk; + +public abstract class PathBase implements IPath { + @Override + public IPath cutoffAtLoadedChunks() { + for (int i = 0; i < positions().size(); i++) { + BlockPos pos = positions().get(i); + if (Minecraft.getMinecraft().world.getChunk(pos) instanceof EmptyChunk) { + return new CutoffPath(this, i); + } + } + return this; + } + + @Override + public IPath staticCutoff(Goal destination) { + if (length() < BaritoneAPI.getSettings().pathCutoffMinimumLength.get()) { + return this; + } + if (destination == null || destination.isInGoal(getDest())) { + return this; + } + double factor = BaritoneAPI.getSettings().pathCutoffFactor.get(); + int newLength = (int) ((length() - 1) * factor); + return new CutoffPath(this, newLength); + } +} From 40da7b37342646546ba2439f61747e353b0b4276 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 7 Nov 2018 17:18:43 -0800 Subject: [PATCH 275/305] don't fail silently in the future --- src/api/java/baritone/api/pathing/calc/IPath.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/pathing/calc/IPath.java b/src/api/java/baritone/api/pathing/calc/IPath.java index 05e0a3bc..ad25911a 100644 --- a/src/api/java/baritone/api/pathing/calc/IPath.java +++ b/src/api/java/baritone/api/pathing/calc/IPath.java @@ -53,7 +53,7 @@ public interface IPath { * (as opposed to Path objects that are just constructed every frame for rendering) */ default IPath postProcess() { - return this; + throw new UnsupportedOperationException(); } /** @@ -121,7 +121,7 @@ public interface IPath { * @return The result of this cut-off operation */ default IPath cutoffAtLoadedChunks() { - return this; + throw new UnsupportedOperationException(); } /** @@ -133,7 +133,7 @@ public interface IPath { * @see Settings#pathCutoffFactor */ default IPath staticCutoff(Goal destination) { - return this; + throw new UnsupportedOperationException(); } From 5b395ce3da2de3b83ecd039c65b9db83753ef8e9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 7 Nov 2018 17:23:36 -0800 Subject: [PATCH 276/305] should be in the synchronized block --- .../baritone/behavior/PathingBehavior.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 6315e15f..51550995 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -430,18 +430,16 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, 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())) { - logDebug("Finished finding a path from " + start + " to " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered"); - } else { - logDebug("Found path segment from " + start + " towards " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered"); - + if (talkAboutIt && current != null && current.getPath() != null) { + if (goal == null || goal.isInGoal(current.getPath().getDest())) { + logDebug("Finished finding a path from " + start + " to " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered"); + } else { + logDebug("Found path segment from " + start + " towards " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered"); + } + } + synchronized (pathCalcLock) { + isPathCalcInProgress = false; } - } - synchronized (pathCalcLock) { - isPathCalcInProgress = false; } }); } From 7dc89b019009a0ecc6848a364587c7cc83c3241a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 7 Nov 2018 17:27:57 -0800 Subject: [PATCH 277/305] single runaway goal object, allows splicing better --- .../java/baritone/process/MineProcess.java | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 48325dbb..1a2e9847 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -56,6 +56,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro private List mining; private List knownOreLocations; private BlockPos branchPoint; + private GoalRunAway branchPointRunaway; private int desiredQuantity; private int tickCount; @@ -132,6 +133,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) { // cool, path is over and we are at desired y branchPoint = playerFeet(); + branchPointRunaway = null; } else { return new GoalYLevel(y); } @@ -141,12 +143,15 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro // TODO mine 1x1 shafts to either side branchPoint = branchPoint.north(10); }*/ - return new GoalRunAway(1, Optional.of(y), branchPoint) { - @Override - public boolean isInGoal(int x, int y, int z) { - return false; - } - }; + if (branchPointRunaway == null) { + branchPointRunaway = new GoalRunAway(1, Optional.of(y), branchPoint) { + @Override + public boolean isInGoal(int x, int y, int z) { + return false; + } + }; + } + return branchPointRunaway; } private void rescan(List already) { @@ -293,6 +298,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro this.desiredQuantity = quantity; this.knownOreLocations = new ArrayList<>(); this.branchPoint = null; + this.branchPointRunaway = null; rescan(new ArrayList<>()); } } From dc6389c46fc1241cbe215a3904fb13ea3ab50da8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 8 Nov 2018 14:58:18 -0800 Subject: [PATCH 278/305] comment --- src/main/java/baritone/process/MineProcess.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 1a2e9847..1db47fc8 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -138,11 +138,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return new GoalYLevel(y); } } - - /*if (playerFeet().equals(branchPoint)) { - // TODO mine 1x1 shafts to either side - branchPoint = branchPoint.north(10); - }*/ + // TODO shaft mode, mine 1x1 shafts to either side + // TODO also, see if the GoalRunAway with maintain Y at 11 works even from the surface if (branchPointRunaway == null) { branchPointRunaway = new GoalRunAway(1, Optional.of(y), branchPoint) { @Override From f2dcdda9b3da87ef3311f7e20e0b827e95a6c7b6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 9 Nov 2018 14:49:25 -0800 Subject: [PATCH 279/305] revamp follow and fix some bugs in mine --- .../baritone/api/process/IFollowProcess.java | 15 +++-- .../baritone/behavior/PathingBehavior.java | 18 ++++- .../java/baritone/process/FollowProcess.java | 66 ++++++++++++++++--- .../java/baritone/process/MineProcess.java | 2 + .../utils/ExampleBaritoneControl.java | 8 ++- .../baritone/utils/PathingControlManager.java | 65 ++++++++++++++---- 6 files changed, 143 insertions(+), 31 deletions(-) diff --git a/src/api/java/baritone/api/process/IFollowProcess.java b/src/api/java/baritone/api/process/IFollowProcess.java index cb9ecde6..ef869da4 100644 --- a/src/api/java/baritone/api/process/IFollowProcess.java +++ b/src/api/java/baritone/api/process/IFollowProcess.java @@ -19,6 +19,9 @@ package baritone.api.process; import net.minecraft.entity.Entity; +import java.util.List; +import java.util.function.Predicate; + /** * @author Brady * @since 9/23/2018 @@ -26,16 +29,18 @@ import net.minecraft.entity.Entity; public interface IFollowProcess extends IBaritoneProcess { /** - * Set the follow target to the specified entity; + * Set the follow target to any entities matching this predicate * - * @param entity The entity to follow + * @param filter the predicate */ - void follow(Entity entity); + void follow(Predicate filter); /** - * @return The entity that is currently being followed + * @return The entities that are currently being followed. null if not currently following, empty if nothing matches the predicate */ - Entity following(); + List following(); + + Predicate currentFilter(); /** * Cancels the follow behavior, this will clear the current follow target. diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 51550995..c9c95c87 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -55,6 +55,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private boolean safeToCancel; private boolean pauseRequestedLastTick; + private boolean cancelRequested; private boolean calcFailedLastTick; private volatile boolean isPathCalcInProgress; @@ -91,18 +92,22 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, baritone.getPathingControlManager().cancelEverything(); return; } + baritone.getPathingControlManager().preTick(); tickPath(); dispatchEvents(); } private void tickPath() { - baritone.getPathingControlManager().doTheThingWithTheStuff(); if (pauseRequestedLastTick && safeToCancel) { pauseRequestedLastTick = false; baritone.getInputOverrideHandler().clearAllKeys(); BlockBreakHelper.stopBreakingBlock(); return; } + if (cancelRequested) { + cancelRequested = false; + baritone.getInputOverrideHandler().clearAllKeys(); + } if (current == null) { return; } @@ -273,6 +278,17 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return calcFailedLastTick; } + public void softCancelIfSafe() { + if (!isSafeToCancel()) { + return; + } + current = null; + next = null; + cancelRequested = true; + AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(AbstractNodeCostSearch::cancel); + // do everything BUT clear keys + } + // just cancel the current path public void secretInternalSegmentCancel() { queuePathEvent(PathEvent.CANCELED); diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index f662fa1d..41a59808 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -18,6 +18,8 @@ package baritone.process; import baritone.Baritone; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalNear; import baritone.api.pathing.goals.GoalXZ; import baritone.api.process.IFollowProcess; @@ -27,6 +29,12 @@ import baritone.utils.BaritoneProcessHelper; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + /** * Follow an entity * @@ -34,7 +42,8 @@ import net.minecraft.util.math.BlockPos; */ public final class FollowProcess extends BaritoneProcessHelper implements IFollowProcess { - private Entity following; + private Predicate filter; + private List cache; public FollowProcess(Baritone baritone) { super(baritone, 1); @@ -42,39 +51,76 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + scanWorld(); + Goal goal = new GoalComposite(cache.stream().map(this::towards).toArray(Goal[]::new)); + return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH); + } + + private Goal towards(Entity following) { // lol this is trashy but it works BlockPos pos; if (Baritone.settings().followOffsetDistance.get() == 0) { - pos = following.getPosition(); + pos = new BlockPos(following); } else { GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.get(), Baritone.settings().followOffsetDistance.get()); pos = new BlockPos(g.getX(), following.posY, g.getZ()); } - return new PathingCommand(new GoalNear(pos, Baritone.settings().followRadius.get()), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); + return new GoalNear(pos, Baritone.settings().followRadius.get()); + } + + + private boolean followable(Entity entity) { + if (entity == null) { + return false; + } + if (entity.isDead) { + return false; + } + if (entity.equals(player())) { + return false; + } + if (!world().loadedEntityList.contains(entity) && !world().playerEntities.contains(entity)) { + return false; + } + return true; + } + + private void scanWorld() { + cache = Stream.of(world().loadedEntityList, world().playerEntities).flatMap(List::stream).filter(this::followable).filter(this.filter).distinct().collect(Collectors.toCollection(ArrayList::new)); } @Override public boolean isActive() { - return following != null; + if (filter == null) { + return false; + } + scanWorld(); + return !cache.isEmpty(); } @Override public void onLostControl() { - following = null; + filter = null; + cache = null; } @Override public String displayName() { - return "Follow " + following; + return "Follow " + cache; } @Override - public void follow(Entity entity) { - this.following = entity; + public void follow(Predicate filter) { + this.filter = filter; } @Override - public Entity following() { - return this.following; + public List following() { + return cache; + } + + @Override + public Predicate currentFilter() { + return filter; } } diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 1db47fc8..0c39f2fb 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -241,6 +241,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } public void addNearby() { + knownOreLocations.addAll(droppedItemsScan(mining, world())); BlockPos playerFeet = playerFeet(); int searchDist = 4;//why four? idk for (int x = playerFeet.getX() - searchDist; x <= playerFeet.getX() + searchDist; x++) { @@ -260,6 +261,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro List dropped = droppedItemsScan(mining, world); List locs = locs2 .stream() + .distinct() // remove any that are within loaded chunks that aren't actually what we want .filter(pos -> world.getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock()) || dropped.contains(pos)) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index e908d1c4..f4defbfd 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -262,6 +262,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { }); return true; } + if (msg.startsWith("followplayers")) { + baritone.getFollowProcess().follow(EntityPlayer.class::isInstance); // O P P A + logDirect("Following any players"); + return true; + } if (msg.startsWith("follow")) { String name = msg.substring(6).trim(); Optional toFollow = Optional.empty(); @@ -279,7 +284,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Not found"); return true; } - baritone.getFollowProcess().follow(toFollow.get()); + Entity effectivelyFinal = toFollow.get(); + baritone.getFollowProcess().follow(x -> effectivelyFinal.equals(x)); logDirect("Following " + toFollow.get()); return true; } diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 5d1b0303..9ea193a1 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -18,10 +18,13 @@ package baritone.utils; import baritone.Baritone; +import baritone.api.event.events.TickEvent; +import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.pathing.goals.Goal; import baritone.api.process.IBaritoneProcess; import baritone.api.process.PathingCommand; import baritone.behavior.PathingBehavior; +import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.path.PathExecutor; import net.minecraft.util.math.BlockPos; @@ -36,10 +39,20 @@ public class PathingControlManager { private final HashSet processes; // unGh private IBaritoneProcess inControlLastTick; private IBaritoneProcess inControlThisTick; + private PathingCommand command; public PathingControlManager(Baritone baritone) { this.baritone = baritone; this.processes = new HashSet<>(); + baritone.registerEventListener(new AbstractGameEventListener() { // needs to be after all behavior ticks + @Override + public void onTick(TickEvent event) { + if (event.getType() == TickEvent.Type.OUT) { + return; + } + postTick(); + } + }); } public void registerProcess(IBaritoneProcess process) { @@ -61,38 +74,35 @@ public class PathingControlManager { return inControlThisTick; } - public void doTheThingWithTheStuff() { + public void preTick() { inControlLastTick = inControlThisTick; - PathingCommand cmd = doTheStuff(); - if (cmd == null) { + command = doTheStuff(); + if (command == null) { return; } PathingBehavior p = baritone.getPathingBehavior(); - switch (cmd.commandType) { + switch (command.commandType) { case REQUEST_PAUSE: p.requestPause(); break; case CANCEL_AND_SET_GOAL: - p.secretInternalSetGoal(cmd.goal); + p.secretInternalSetGoal(command.goal); p.cancelSegmentIfSafe(); break; case FORCE_REVALIDATE_GOAL_AND_PATH: - p.secretInternalSetGoalAndPath(cmd.goal); - if (cmd.goal == null || forceRevalidate(cmd.goal) || revalidateGoal(cmd.goal)) { - // pwnage - p.cancelSegmentIfSafe(); + if (!p.isPathing() && !AbstractNodeCostSearch.getCurrentlyRunning().isPresent()) { + p.secretInternalSetGoalAndPath(command.goal); } break; case REVALIDATE_GOAL_AND_PATH: - p.secretInternalSetGoalAndPath(cmd.goal); - if (Baritone.settings().cancelOnGoalInvalidation.get() && (cmd.goal == null || revalidateGoal(cmd.goal))) { - p.cancelSegmentIfSafe(); + if (!p.isPathing() && !AbstractNodeCostSearch.getCurrentlyRunning().isPresent()) { + p.secretInternalSetGoalAndPath(command.goal); } break; case SET_GOAL_AND_PATH: // now this i can do - if (cmd.goal != null) { - baritone.getPathingBehavior().secretInternalSetGoalAndPath(cmd.goal); + if (command.goal != null) { + baritone.getPathingBehavior().secretInternalSetGoalAndPath(command.goal); } break; default: @@ -100,6 +110,33 @@ public class PathingControlManager { } } + public void postTick() { + // if we did this in pretick, it would suck + // we use the time between ticks as calculation time + // therefore, we only cancel and recalculate after the tick for the current path has executed + // "it would suck" means it would actually execute a path every other tick + if (command == null) { + return; + } + PathingBehavior p = baritone.getPathingBehavior(); + switch (command.commandType) { + case FORCE_REVALIDATE_GOAL_AND_PATH: + if (command.goal == null || forceRevalidate(command.goal) || revalidateGoal(command.goal)) { + // pwnage + p.softCancelIfSafe(); + } + p.secretInternalSetGoalAndPath(command.goal); + break; + case REVALIDATE_GOAL_AND_PATH: + if (Baritone.settings().cancelOnGoalInvalidation.get() && (command.goal == null || revalidateGoal(command.goal))) { + p.softCancelIfSafe(); + } + p.secretInternalSetGoalAndPath(command.goal); + break; + default: + } + } + public boolean forceRevalidate(Goal newGoal) { PathExecutor current = baritone.getPathingBehavior().getCurrent(); if (current != null) { From 13505a052f88c8edc04a532ab3d161f9907b0e85 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 9 Nov 2018 15:59:03 -0800 Subject: [PATCH 280/305] wait a tick until objectMouseOver matches, fixes #254 --- .../java/baritone/pathing/movement/Movement.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 31dd952b..6d9f5487 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -20,10 +20,7 @@ package baritone.pathing.movement; import baritone.Baritone; import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.Rotation; -import baritone.api.utils.RotationUtils; -import baritone.api.utils.VecUtils; +import baritone.api.utils.*; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.InputOverrideHandler; @@ -34,6 +31,7 @@ import net.minecraft.world.chunk.EmptyChunk; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Optional; import static baritone.utils.InputOverrideHandler.Input; @@ -154,7 +152,10 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { Optional reachable = RotationUtils.reachable(player(), blockPos); if (reachable.isPresent()) { MovementHelper.switchToBestToolFor(BlockStateInterface.get(blockPos)); - state.setTarget(new MovementState.MovementTarget(reachable.get(), true)).setInput(Input.CLICK_LEFT, true); + state.setTarget(new MovementState.MovementTarget(reachable.get(), true)); + if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), blockPos)) { + state.setInput(Input.CLICK_LEFT, true); + } return false; } //get rekt minecraft @@ -163,7 +164,9 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { //you dont own me!!!! state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(player().getPositionEyes(1.0F), VecUtils.getBlockPosCenter(blockPos)), true) - ).setInput(InputOverrideHandler.Input.CLICK_LEFT, true); + ); + // don't check selectedblock on this one, this is a fallback when we can't see any face directly, it's intended to be breaking the "incorrect" block + state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); return false; } } From a2a60e9847cb19d57c06e770b69ce2a06171e9e0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 9 Nov 2018 16:55:31 -0800 Subject: [PATCH 281/305] misc cleanup --- src/main/java/baritone/pathing/movement/MovementHelper.java | 3 +-- .../baritone/pathing/movement/movements/MovementPillar.java | 5 ++--- .../pathing/movement/movements/MovementTraverse.java | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 0ea254b1..75361635 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -28,7 +28,6 @@ import baritone.utils.ToolSet; import net.minecraft.block.*; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.init.Blocks; import net.minecraft.item.ItemPickaxe; @@ -398,7 +397,7 @@ public interface MovementHelper extends ActionCosts, Helper { } static boolean throwaway(boolean select) { - EntityPlayerSP p = Minecraft.getMinecraft().player; + EntityPlayerSP p = Helper.HELPER.player(); NonNullList inv = p.inventory.mainInventory; for (byte i = 0; i < 9; i++) { ItemStack item = inv.get(i); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index d85a6b55..b19556fd 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -30,7 +30,6 @@ import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; @@ -215,10 +214,10 @@ public class MovementPillar extends Movement { if (!blockIsThere) { Block fr = BlockStateInterface.get(src).getBlock(); - if (!(fr instanceof BlockAir || fr.isReplaceable(Minecraft.getMinecraft().world, src))) { + if (!(fr instanceof BlockAir || fr.isReplaceable(world(), src))) { state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); blockIsThere = false; - } else if (Minecraft.getMinecraft().player.isSneaking()) { // 1 tick after we're able to place + } else if (player().isSneaking()) { // 1 tick after we're able to place state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 1f56ffe4..93dfcf44 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -265,7 +265,7 @@ public class MovementTraverse extends Movement { state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true)); EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; - if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (Minecraft.getMinecraft().player.isSneaking() || Baritone.settings().assumeSafeWalk.get()) && RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { + if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } //System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); From dd08b2c8255f63a43b5cf31e8121210d384b8891 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 9 Nov 2018 17:21:02 -0800 Subject: [PATCH 282/305] no more references to player() from pathing thread --- .../pathing/calc/AStarPathFinder.java | 6 +- .../pathing/calc/AbstractNodeCostSearch.java | 10 ++- src/main/java/baritone/pathing/calc/Path.java | 10 ++- .../pathing/movement/CalculationContext.java | 27 ++++++-- .../pathing/movement/MovementHelper.java | 2 +- .../java/baritone/pathing/movement/Moves.java | 62 +++++++++---------- .../utils/ExampleBaritoneControl.java | 3 +- src/main/java/baritone/utils/Helper.java | 3 + src/main/java/baritone/utils/ToolSet.java | 20 +++--- 9 files changed, 87 insertions(+), 56 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index 83830ac0..41c11ea5 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -44,7 +44,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel private final CalculationContext calcContext; public AStarPathFinder(int startX, int startY, int startZ, Goal goal, Optional> favoredPositions, CalculationContext context) { - super(startX, startY, startZ, goal); + super(startX, startY, startZ, goal, context); this.favoredPositions = favoredPositions; this.calcContext = context; } @@ -95,7 +95,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel numNodes++; if (goal.isInGoal(currentNode.x, currentNode.y, currentNode.z)) { logDebug("Took " + (System.nanoTime() / 1000000L - startTime) + "ms, " + numMovementsConsidered + " movements considered"); - return Optional.of(new Path(startNode, currentNode, numNodes, goal)); + return Optional.of(new Path(startNode, currentNode, numNodes, goal, calcContext)); } for (Moves moves : Moves.values()) { int newX = currentNode.x + moves.xOffset; @@ -198,7 +198,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel System.out.println("But I'm going to do it anyway, because yolo"); } System.out.println("Path goes for " + Math.sqrt(dist) + " blocks"); - return Optional.of(new Path(startNode, bestSoFar[i], numNodes, goal)); + return Optional.of(new Path(startNode, bestSoFar[i], numNodes, goal, calcContext)); } } logDebug("Even with a cost coefficient of " + COEFFICIENTS[COEFFICIENTS.length - 1] + ", I couldn't get more than " + Math.sqrt(bestDist) + " blocks"); diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 708b5ab0..79a56037 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -22,6 +22,7 @@ import baritone.api.pathing.calc.IPath; import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; import baritone.api.utils.PathCalculationResult; +import baritone.pathing.movement.CalculationContext; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import java.util.Optional; @@ -44,6 +45,8 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { protected final Goal goal; + private final CalculationContext context; + /** * @see Issue #107 */ @@ -71,11 +74,12 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { */ protected final static double MIN_DIST_PATH = 5; - AbstractNodeCostSearch(int startX, int startY, int startZ, Goal goal) { + AbstractNodeCostSearch(int startX, int startY, int startZ, Goal goal, CalculationContext context) { this.startX = startX; this.startY = startY; this.startZ = startZ; this.goal = goal; + this.context = context; this.map = new Long2ObjectOpenHashMap<>(Baritone.settings().pathingMapDefaultSize.value, Baritone.settings().pathingMapLoadFactor.get()); } @@ -171,7 +175,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { @Override public Optional pathToMostRecentNodeConsidered() { try { - return Optional.ofNullable(mostRecentConsidered).map(node -> new Path(startNode, node, 0, goal)); + return Optional.ofNullable(mostRecentConsidered).map(node -> new Path(startNode, node, 0, goal, context)); } catch (IllegalStateException ex) { System.out.println("Unable to construct path to render"); return Optional.empty(); @@ -193,7 +197,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { } if (getDistFromStartSq(bestSoFar[i]) > MIN_DIST_PATH * MIN_DIST_PATH) { // square the comparison since distFromStartSq is squared try { - return Optional.of(new Path(startNode, bestSoFar[i], 0, goal)); + return Optional.of(new Path(startNode, bestSoFar[i], 0, goal, context)); } catch (IllegalStateException ex) { System.out.println("Unable to construct path to render"); return Optional.empty(); diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 873fef64..58e1e661 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -21,6 +21,7 @@ import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; import baritone.api.utils.BetterBlockPos; +import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.pathing.path.CutoffPath; @@ -63,9 +64,11 @@ class Path extends PathBase { private final int numNodes; + private final CalculationContext context; + private volatile boolean verified; - Path(PathNode start, PathNode end, int numNodes, Goal goal) { + Path(PathNode start, PathNode end, int numNodes, Goal goal, CalculationContext context) { this.start = new BetterBlockPos(start.x, start.y, start.z); this.end = new BetterBlockPos(end.x, end.y, end.z); this.numNodes = numNodes; @@ -73,6 +76,7 @@ class Path extends PathBase { this.movements = new ArrayList<>(); this.nodes = new ArrayList<>(); this.goal = goal; + this.context = context; assemblePath(end); } @@ -123,9 +127,9 @@ class Path extends PathBase { return false; } - private static Movement runBackwards(BetterBlockPos src, BetterBlockPos dest, double cost) { + private Movement runBackwards(BetterBlockPos src, BetterBlockPos dest, double cost) { for (Moves moves : Moves.values()) { - Movement move = moves.apply0(src); + Movement move = moves.apply0(context, src); if (move.getDest().equals(dest)) { // have to calculate the cost at calculation time so we can accurately judge whether a cost increase happened between cached calculation and real execution move.override(cost); diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index ca6936a5..10aa03c0 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -22,19 +22,23 @@ import baritone.api.pathing.movement.ActionCosts; import baritone.utils.Helper; import baritone.utils.ToolSet; import baritone.utils.pathing.BetterWorldBorder; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; +import net.minecraft.world.World; /** * @author Brady * @since 8/7/2018 4:30 PM */ -public class CalculationContext implements Helper { +public class CalculationContext { private static final ItemStack STACK_BUCKET_WATER = new ItemStack(Items.WATER_BUCKET); + private final EntityPlayerSP player; + private final World world; private final ToolSet toolSet; private final boolean hasWaterBucket; private final boolean hasThrowaway; @@ -48,15 +52,17 @@ public class CalculationContext implements Helper { private final BetterWorldBorder worldBorder; public CalculationContext() { - this.toolSet = new ToolSet(); + this.player = Helper.HELPER.player(); + this.world = Helper.HELPER.world(); + this.toolSet = new ToolSet(player); this.hasThrowaway = Baritone.settings().allowPlace.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.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(); - int depth = EnchantmentHelper.getDepthStriderModifier(player()); + int depth = EnchantmentHelper.getDepthStriderModifier(player); if (depth > 3) { depth = 3; } @@ -66,7 +72,7 @@ public class CalculationContext implements Helper { // 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. - this.worldBorder = new BetterWorldBorder(world().getWorldBorder()); + this.worldBorder = new BetterWorldBorder(world.getWorldBorder()); } public boolean canPlaceThrowawayAt(int x, int y, int z) { @@ -91,6 +97,15 @@ public class CalculationContext implements Helper { return false; } + public World world() { + return world; + } + + public EntityPlayerSP player() { + return player; + } + + public ToolSet getToolSet() { return toolSet; } diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 75361635..7f2f4e0d 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -383,7 +383,7 @@ public interface MovementHelper extends ActionCosts, Helper { * @param b the blockstate to mine */ static void switchToBestToolFor(IBlockState b) { - switchToBestToolFor(b, new ToolSet()); + switchToBestToolFor(b, new ToolSet(Helper.HELPER.player())); } /** diff --git a/src/main/java/baritone/pathing/movement/Moves.java b/src/main/java/baritone/pathing/movement/Moves.java index 80a6c4d5..340122b3 100644 --- a/src/main/java/baritone/pathing/movement/Moves.java +++ b/src/main/java/baritone/pathing/movement/Moves.java @@ -30,7 +30,7 @@ import net.minecraft.util.EnumFacing; public enum Moves { DOWNWARD(0, -1, 0) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementDownward(src, src.down()); } @@ -42,7 +42,7 @@ public enum Moves { PILLAR(0, +1, 0) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementPillar(src, src.up()); } @@ -54,7 +54,7 @@ public enum Moves { TRAVERSE_NORTH(0, 0, -1) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementTraverse(src, src.north()); } @@ -66,7 +66,7 @@ public enum Moves { TRAVERSE_SOUTH(0, 0, +1) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementTraverse(src, src.south()); } @@ -78,7 +78,7 @@ public enum Moves { TRAVERSE_EAST(+1, 0, 0) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementTraverse(src, src.east()); } @@ -90,7 +90,7 @@ public enum Moves { TRAVERSE_WEST(-1, 0, 0) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementTraverse(src, src.west()); } @@ -102,7 +102,7 @@ public enum Moves { ASCEND_NORTH(0, +1, -1) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementAscend(src, new BetterBlockPos(src.x, src.y + 1, src.z - 1)); } @@ -114,7 +114,7 @@ public enum Moves { ASCEND_SOUTH(0, +1, +1) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementAscend(src, new BetterBlockPos(src.x, src.y + 1, src.z + 1)); } @@ -126,7 +126,7 @@ public enum Moves { ASCEND_EAST(+1, +1, 0) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementAscend(src, new BetterBlockPos(src.x + 1, src.y + 1, src.z)); } @@ -138,7 +138,7 @@ public enum Moves { ASCEND_WEST(-1, +1, 0) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementAscend(src, new BetterBlockPos(src.x - 1, src.y + 1, src.z)); } @@ -150,9 +150,9 @@ public enum Moves { DESCEND_EAST(+1, -1, 0, false, true) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(new CalculationContext(), src.x, src.y, src.z, res); + apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); } else { @@ -168,9 +168,9 @@ public enum Moves { DESCEND_WEST(-1, -1, 0, false, true) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(new CalculationContext(), src.x, src.y, src.z, res); + apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); } else { @@ -186,9 +186,9 @@ public enum Moves { DESCEND_NORTH(0, -1, -1, false, true) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(new CalculationContext(), src.x, src.y, src.z, res); + apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); } else { @@ -204,9 +204,9 @@ public enum Moves { DESCEND_SOUTH(0, -1, +1, false, true) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(new CalculationContext(), src.x, src.y, src.z, res); + apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); } else { @@ -222,7 +222,7 @@ public enum Moves { DIAGONAL_NORTHEAST(+1, 0, -1) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementDiagonal(src, EnumFacing.NORTH, EnumFacing.EAST); } @@ -234,7 +234,7 @@ public enum Moves { DIAGONAL_NORTHWEST(-1, 0, -1) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementDiagonal(src, EnumFacing.NORTH, EnumFacing.WEST); } @@ -246,7 +246,7 @@ public enum Moves { DIAGONAL_SOUTHEAST(+1, 0, +1) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementDiagonal(src, EnumFacing.SOUTH, EnumFacing.EAST); } @@ -258,7 +258,7 @@ public enum Moves { DIAGONAL_SOUTHWEST(-1, 0, +1) { @Override - public Movement apply0(BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { return new MovementDiagonal(src, EnumFacing.SOUTH, EnumFacing.WEST); } @@ -270,8 +270,8 @@ public enum Moves { PARKOUR_NORTH(0, 0, -4, true, false) { @Override - public Movement apply0(BetterBlockPos src) { - return MovementParkour.cost(new CalculationContext(), src, EnumFacing.NORTH); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return MovementParkour.cost(context, src, EnumFacing.NORTH); } @Override @@ -282,8 +282,8 @@ public enum Moves { PARKOUR_SOUTH(0, 0, +4, true, false) { @Override - public Movement apply0(BetterBlockPos src) { - return MovementParkour.cost(new CalculationContext(), src, EnumFacing.SOUTH); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return MovementParkour.cost(context, src, EnumFacing.SOUTH); } @Override @@ -294,8 +294,8 @@ public enum Moves { PARKOUR_EAST(+4, 0, 0, true, false) { @Override - public Movement apply0(BetterBlockPos src) { - return MovementParkour.cost(new CalculationContext(), src, EnumFacing.EAST); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return MovementParkour.cost(context, src, EnumFacing.EAST); } @Override @@ -306,8 +306,8 @@ public enum Moves { PARKOUR_WEST(-4, 0, 0, true, false) { @Override - public Movement apply0(BetterBlockPos src) { - return MovementParkour.cost(new CalculationContext(), src, EnumFacing.WEST); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return MovementParkour.cost(context, src, EnumFacing.WEST); } @Override @@ -335,7 +335,7 @@ public enum Moves { this(x, y, z, false, false); } - public abstract Movement apply0(BetterBlockPos src); + public abstract Movement apply0(CalculationContext context, BetterBlockPos src); public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { if (dynamicXZ || dynamicY) { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index f4defbfd..2fbf05f7 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -31,6 +31,7 @@ import baritone.cache.ChunkPacker; import baritone.cache.Waypoint; import baritone.cache.WorldProvider; import baritone.pathing.calc.AbstractNodeCostSearch; +import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; @@ -450,7 +451,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("costs")) { - List moves = Stream.of(Moves.values()).map(x -> x.apply0(playerFeet())).collect(Collectors.toCollection(ArrayList::new)); + List moves = Stream.of(Moves.values()).map(x -> x.apply0(new CalculationContext(), playerFeet())).collect(Collectors.toCollection(ArrayList::new)); while (moves.contains(null)) { moves.remove(null); } diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index 2a34ecc0..a80e5660 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -51,6 +51,9 @@ public interface Helper { Minecraft mc = Minecraft.getMinecraft(); default EntityPlayerSP player() { + if (!mc.isCallingFromMinecraftThread()) { + throw new IllegalStateException("h00000000"); + } return mc.player; } diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 0c618294..026ec199 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -20,6 +20,7 @@ package baritone.utils; import baritone.Baritone; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.init.Enchantments; import net.minecraft.init.MobEffects; @@ -36,7 +37,7 @@ import java.util.function.Function; * * @author Avery, Brady, leijurv */ -public class ToolSet implements Helper { +public class ToolSet { /** * A cache mapping a {@link Block} to how long it will take to break * with this toolset, given the optimum tool is used. @@ -48,8 +49,11 @@ public class ToolSet implements Helper { */ private final Function backendCalculation; - public ToolSet() { + private final EntityPlayerSP player; + + public ToolSet(EntityPlayerSP player) { breakStrengthCache = new HashMap<>(); + this.player = player; if (Baritone.settings().considerPotionEffects.get()) { double amplifier = potionAmplifier(); @@ -98,7 +102,7 @@ public class ToolSet implements Helper { int materialCost = Integer.MIN_VALUE; IBlockState blockState = b.getDefaultState(); for (byte i = 0; i < 9; i++) { - ItemStack itemStack = player().inventory.getStackInSlot(i); + ItemStack itemStack = player.inventory.getStackInSlot(i); double v = calculateStrVsBlock(itemStack, blockState); if (v > value) { value = v; @@ -123,7 +127,7 @@ public class ToolSet implements Helper { * @return A double containing the destruction ticks with the best tool */ private double getBestDestructionTime(Block b) { - ItemStack stack = player().inventory.getStackInSlot(getBestSlot(b)); + ItemStack stack = player.inventory.getStackInSlot(getBestSlot(b)); return calculateStrVsBlock(stack, b.getDefaultState()); } @@ -164,11 +168,11 @@ public class ToolSet implements Helper { */ private double potionAmplifier() { double speed = 1; - if (player().isPotionActive(MobEffects.HASTE)) { - speed *= 1 + (player().getActivePotionEffect(MobEffects.HASTE).getAmplifier() + 1) * 0.2; + if (player.isPotionActive(MobEffects.HASTE)) { + speed *= 1 + (player.getActivePotionEffect(MobEffects.HASTE).getAmplifier() + 1) * 0.2; } - if (player().isPotionActive(MobEffects.MINING_FATIGUE)) { - switch (player().getActivePotionEffect(MobEffects.MINING_FATIGUE).getAmplifier()) { + if (player.isPotionActive(MobEffects.MINING_FATIGUE)) { + switch (player.getActivePotionEffect(MobEffects.MINING_FATIGUE).getAmplifier()) { case 0: speed *= 0.3; break; From 1a1686b7c351af8fd29cd65ee2d699501e505a39 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 9 Nov 2018 18:55:50 -0800 Subject: [PATCH 283/305] fix yet more player references --- src/api/java/baritone/api/utils/Rotation.java | 35 +++++++++++++++-- .../baritone/pathing/movement/Movement.java | 4 +- .../pathing/movement/MovementHelper.java | 16 ++++---- .../movement/movements/MovementAscend.java | 4 +- .../movement/movements/MovementFall.java | 8 +++- .../movement/movements/MovementParkour.java | 4 +- .../movement/movements/MovementPillar.java | 8 ++-- .../movement/movements/MovementTraverse.java | 2 + .../java/baritone/process/MineProcess.java | 2 +- .../utils/ExampleBaritoneControl.java | 1 - src/main/java/baritone/utils/Helper.java | 8 ++++ .../java/baritone}/utils/RayTraceUtils.java | 28 +++++++------ .../java/baritone}/utils/RotationUtils.java | 39 ++----------------- 13 files changed, 82 insertions(+), 77 deletions(-) rename src/{api/java/baritone/api => main/java/baritone}/utils/RayTraceUtils.java (85%) rename src/{api/java/baritone/api => main/java/baritone}/utils/RotationUtils.java (90%) diff --git a/src/api/java/baritone/api/utils/Rotation.java b/src/api/java/baritone/api/utils/Rotation.java index dc697169..ea10c7ec 100644 --- a/src/api/java/baritone/api/utils/Rotation.java +++ b/src/api/java/baritone/api/utils/Rotation.java @@ -86,7 +86,7 @@ public class Rotation { public Rotation clamp() { return new Rotation( this.yaw, - RotationUtils.clampPitch(this.pitch) + clampPitch(this.pitch) ); } @@ -95,7 +95,7 @@ public class Rotation { */ public Rotation normalize() { return new Rotation( - RotationUtils.normalizeYaw(this.yaw), + normalizeYaw(this.yaw), this.pitch ); } @@ -105,8 +105,35 @@ public class Rotation { */ public Rotation normalizeAndClamp() { return new Rotation( - RotationUtils.normalizeYaw(this.yaw), - RotationUtils.clampPitch(this.pitch) + normalizeYaw(this.yaw), + clampPitch(this.pitch) ); } + + /** + * Clamps the specified pitch value between -90 and 90. + * + * @param pitch The input pitch + * @return The clamped pitch + */ + public static float clampPitch(float pitch) { + return Math.max(-90, Math.min(90, pitch)); + } + + /** + * Normalizes the specified yaw value between -180 and 180. + * + * @param yaw The input yaw + * @return The normalized yaw + */ + public static float normalizeYaw(float yaw) { + float newYaw = yaw % 360F; + if (newYaw < -180F) { + newYaw += 360F; + } + if (newYaw >= 180F) { + newYaw -= 360F; + } + return newYaw; + } } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 6d9f5487..1089d83e 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -21,9 +21,7 @@ import baritone.Baritone; import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.*; -import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; -import baritone.utils.InputOverrideHandler; +import baritone.utils.*; import net.minecraft.block.BlockLiquid; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 7f2f4e0d..f9268d4f 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -19,12 +19,11 @@ package baritone.pathing.movement; import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; -import baritone.api.utils.*; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Rotation; +import baritone.api.utils.VecUtils; import baritone.pathing.movement.MovementState.MovementTarget; -import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; -import baritone.utils.InputOverrideHandler; -import baritone.utils.ToolSet; +import baritone.utils.*; import net.minecraft.block.*; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.IBlockState; @@ -393,7 +392,7 @@ public interface MovementHelper extends ActionCosts, Helper { * @param ts previously calculated ToolSet */ static void switchToBestToolFor(IBlockState b, ToolSet ts) { - mc.player.inventory.currentItem = ts.getBestSlot(b.getBlock()); + Helper.HELPER.player().inventory.currentItem = ts.getBestSlot(b.getBlock()); } static boolean throwaway(boolean select) { @@ -433,10 +432,11 @@ public interface MovementHelper extends ActionCosts, Helper { } static void moveTowards(MovementState state, BlockPos pos) { + EntityPlayerSP player = Helper.HELPER.player(); state.setTarget(new MovementTarget( - new Rotation(RotationUtils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F), + new Rotation(RotationUtils.calcRotationFromVec3d(player.getPositionEyes(1.0F), VecUtils.getBlockPosCenter(pos), - new Rotation(mc.player.rotationYaw, mc.player.rotationPitch)).getYaw(), mc.player.rotationPitch), + new Rotation(player.rotationYaw, player.rotationPitch)).getYaw(), player.rotationPitch), false )).setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index cd0744e4..aa1d7a5b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -20,8 +20,8 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.RayTraceUtils; -import baritone.api.utils.RotationUtils; +import baritone.utils.RayTraceUtils; +import baritone.utils.RotationUtils; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 8f9feb41..63930ee8 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -19,13 +19,17 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.pathing.movement.MovementStatus; -import baritone.api.utils.*; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Rotation; +import baritone.api.utils.VecUtils; 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.MovementTarget; import baritone.utils.InputOverrideHandler; +import baritone.utils.RayTraceUtils; +import baritone.utils.RotationUtils; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; @@ -67,7 +71,7 @@ public class MovementFall extends Movement { return state.setStatus(MovementStatus.UNREACHABLE); } - if (player().posY - dest.getY() < mc.playerController.getBlockReachDistance()) { + if (player().posY - dest.getY() < playerController().getBlockReachDistance()) { player().inventory.currentItem = player().inventory.getSlotFor(STACK_BUCKET_WATER); targetRotation = new Rotation(player().rotationYaw, 90.0F); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 68bddae0..fed636a5 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -20,9 +20,9 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.RayTraceUtils; +import baritone.utils.RayTraceUtils; import baritone.api.utils.Rotation; -import baritone.api.utils.RotationUtils; +import baritone.utils.RotationUtils; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index b19556fd..795884b0 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -20,7 +20,6 @@ package baritone.pathing.movement.movements; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; -import baritone.api.utils.RotationUtils; import baritone.api.utils.VecUtils; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -28,6 +27,7 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; +import baritone.utils.RotationUtils; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -157,11 +157,11 @@ public class MovementPillar extends Movement { } boolean ladder = fromDown.getBlock() instanceof BlockLadder || fromDown.getBlock() instanceof BlockVine; boolean vine = fromDown.getBlock() instanceof BlockVine; - Rotation rotation = RotationUtils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F), + Rotation rotation = RotationUtils.calcRotationFromVec3d(player().getPositionEyes(1.0F), VecUtils.getBlockPosCenter(positionToPlace), - new Rotation(mc.player.rotationYaw, mc.player.rotationPitch)); + new Rotation(player().rotationYaw, player().rotationPitch)); if (!ladder) { - state.setTarget(new MovementState.MovementTarget(new Rotation(mc.player.rotationYaw, rotation.getPitch()), true)); + state.setTarget(new MovementState.MovementTarget(new Rotation(player().rotationYaw, rotation.getPitch()), true)); } boolean blockIsThere = MovementHelper.canWalkOn(src) || ladder; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 93dfcf44..db31bb00 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -26,6 +26,8 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; +import baritone.utils.RayTraceUtils; +import baritone.utils.RotationUtils; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 0c39f2fb..1f4a120e 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -22,7 +22,7 @@ import baritone.api.pathing.goals.*; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.api.utils.RotationUtils; +import baritone.utils.RotationUtils; import baritone.cache.CachedChunk; import baritone.cache.ChunkPacker; import baritone.cache.WorldProvider; diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 2fbf05f7..70f6c1b9 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -23,7 +23,6 @@ import baritone.api.cache.IWaypoint; import baritone.api.event.events.ChatEvent; import baritone.api.pathing.goals.*; import baritone.api.pathing.movement.ActionCosts; -import baritone.api.utils.RayTraceUtils; import baritone.api.utils.SettingsUtil; import baritone.behavior.Behavior; import baritone.behavior.PathingBehavior; diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index a80e5660..27aa2bc1 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -23,6 +23,7 @@ import baritone.api.utils.Rotation; import net.minecraft.block.BlockSlab; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.util.math.Vec3d; import net.minecraft.util.text.ITextComponent; @@ -57,6 +58,13 @@ public interface Helper { return mc.player; } + default PlayerControllerMP playerController() { // idk + if (!mc.isCallingFromMinecraftThread()) { + throw new IllegalStateException("h00000000"); + } + return mc.playerController; + } + default WorldClient world() { return mc.world; } diff --git a/src/api/java/baritone/api/utils/RayTraceUtils.java b/src/main/java/baritone/utils/RayTraceUtils.java similarity index 85% rename from src/api/java/baritone/api/utils/RayTraceUtils.java rename to src/main/java/baritone/utils/RayTraceUtils.java index 1444c7e1..d4955bf9 100644 --- a/src/api/java/baritone/api/utils/RayTraceUtils.java +++ b/src/main/java/baritone/utils/RayTraceUtils.java @@ -15,9 +15,10 @@ * along with Baritone. If not, see . */ -package baritone.api.utils; +package baritone.utils; -import net.minecraft.client.Minecraft; +import baritone.api.utils.Rotation; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; @@ -29,11 +30,7 @@ import java.util.Optional; * @author Brady * @since 8/25/2018 */ -public final class RayTraceUtils { - /** - * The {@link Minecraft} instance - */ - private static final Minecraft mc = Minecraft.getMinecraft(); +public final class RayTraceUtils implements Helper { private RayTraceUtils() {} @@ -50,19 +47,20 @@ public final class RayTraceUtils { * @return The calculated raytrace result */ public static RayTraceResult simulateRayTrace(float yaw, float pitch) { + EntityPlayerSP player = Helper.HELPER.player(); RayTraceResult oldTrace = mc.objectMouseOver; - float oldYaw = mc.player.rotationYaw; - float oldPitch = mc.player.rotationPitch; + float oldYaw = player.rotationYaw; + float oldPitch = player.rotationPitch; - mc.player.rotationYaw = yaw; - mc.player.rotationPitch = pitch; + player.rotationYaw = yaw; + player.rotationPitch = pitch; mc.entityRenderer.getMouseOver(1.0F); RayTraceResult result = mc.objectMouseOver; mc.objectMouseOver = oldTrace; - mc.player.rotationYaw = oldYaw; - mc.player.rotationPitch = oldPitch; + player.rotationYaw = oldYaw; + player.rotationPitch = oldPitch; return result; } @@ -76,8 +74,8 @@ public final class RayTraceUtils { * @return The calculated raytrace result */ public static RayTraceResult rayTraceTowards(Rotation rotation) { - double blockReachDistance = mc.playerController.getBlockReachDistance(); - Vec3d start = mc.player.getPositionEyes(1.0F); + double blockReachDistance = Helper.HELPER.playerController().getBlockReachDistance(); + Vec3d start = Helper.HELPER.player().getPositionEyes(1.0F); Vec3d direction = RotationUtils.calcVec3dFromRotation(rotation); Vec3d end = start.add( direction.x * blockReachDistance, diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/main/java/baritone/utils/RotationUtils.java similarity index 90% rename from src/api/java/baritone/api/utils/RotationUtils.java rename to src/main/java/baritone/utils/RotationUtils.java index a8449dc7..b9dc0589 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/main/java/baritone/utils/RotationUtils.java @@ -15,11 +15,12 @@ * along with Baritone. If not, see . */ -package baritone.api.utils; +package baritone.utils; +import baritone.api.utils.Rotation; +import baritone.api.utils.VecUtils; import net.minecraft.block.BlockFire; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.util.math.*; @@ -29,12 +30,7 @@ import java.util.Optional; * @author Brady * @since 9/25/2018 */ -public final class RotationUtils { - - /** - * The {@link Minecraft} instance - */ - private static final Minecraft mc = Minecraft.getMinecraft(); +public final class RotationUtils implements Helper { /** * Constant that a degree value is multiplied by to get the equivalent radian value @@ -60,33 +56,6 @@ public final class RotationUtils { private RotationUtils() {} - /** - * Clamps the specified pitch value between -90 and 90. - * - * @param pitch The input pitch - * @return The clamped pitch - */ - public static float clampPitch(float pitch) { - return Math.max(-90, Math.min(90, pitch)); - } - - /** - * Normalizes the specified yaw value between -180 and 180. - * - * @param yaw The input yaw - * @return The normalized yaw - */ - public static float normalizeYaw(float yaw) { - float newYaw = yaw % 360F; - if (newYaw < -180F) { - newYaw += 360F; - } - if (newYaw >= 180F) { - newYaw -= 360F; - } - return newYaw; - } - /** * Calculates the rotation from BlockPosdest to BlockPosorig * From 3ddf6b2335df0e84a73fe4c3527cf32494f66694 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 9 Nov 2018 19:12:36 -0800 Subject: [PATCH 284/305] player and player controller toxic cloud --- .../baritone/api}/utils/RayTraceUtils.java | 45 +++---------------- .../baritone/api}/utils/RotationUtils.java | 22 +++++---- .../baritone/pathing/movement/Movement.java | 2 +- .../pathing/movement/MovementHelper.java | 4 +- .../movement/movements/MovementAscend.java | 4 +- .../movement/movements/MovementFall.java | 5 +-- .../movement/movements/MovementParkour.java | 10 ++--- .../movement/movements/MovementPillar.java | 2 +- .../movement/movements/MovementTraverse.java | 4 +- .../java/baritone/process/MineProcess.java | 4 +- .../utils/ExampleBaritoneControl.java | 1 + 11 files changed, 33 insertions(+), 70 deletions(-) rename src/{main/java/baritone => api/java/baritone/api}/utils/RayTraceUtils.java (61%) rename src/{main/java/baritone => api/java/baritone/api}/utils/RotationUtils.java (94%) diff --git a/src/main/java/baritone/utils/RayTraceUtils.java b/src/api/java/baritone/api/utils/RayTraceUtils.java similarity index 61% rename from src/main/java/baritone/utils/RayTraceUtils.java rename to src/api/java/baritone/api/utils/RayTraceUtils.java index d4955bf9..8b37ef9d 100644 --- a/src/main/java/baritone/utils/RayTraceUtils.java +++ b/src/api/java/baritone/api/utils/RayTraceUtils.java @@ -15,10 +15,9 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.api.utils; -import baritone.api.utils.Rotation; -import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; @@ -30,41 +29,12 @@ import java.util.Optional; * @author Brady * @since 8/25/2018 */ -public final class RayTraceUtils implements Helper { +public final class RayTraceUtils { + + private static final Minecraft mc = Minecraft.getMinecraft(); private RayTraceUtils() {} - /** - * Simulates a "vanilla" raytrace. A RayTraceResult returned by this method - * will be that of the next render pass given that the local player's yaw and - * pitch match the specified yaw and pitch values. This is particularly useful - * when you would like to simulate a "legit" raytrace with certainty that the only - * thing to achieve the desired outcome (whether it is hitting and entity or placing - * a block) can be done just by modifying user input. - * - * @param yaw The yaw to raytrace with - * @param pitch The pitch to raytrace with - * @return The calculated raytrace result - */ - public static RayTraceResult simulateRayTrace(float yaw, float pitch) { - EntityPlayerSP player = Helper.HELPER.player(); - RayTraceResult oldTrace = mc.objectMouseOver; - float oldYaw = player.rotationYaw; - float oldPitch = player.rotationPitch; - - player.rotationYaw = yaw; - player.rotationPitch = pitch; - - mc.entityRenderer.getMouseOver(1.0F); - RayTraceResult result = mc.objectMouseOver; - mc.objectMouseOver = oldTrace; - - player.rotationYaw = oldYaw; - player.rotationPitch = oldPitch; - - return result; - } - /** * Performs a block raytrace with the specified rotations. This should only be used when * any entity collisions can be ignored, because this method will not recognize if an @@ -73,9 +43,8 @@ public final class RayTraceUtils implements Helper { * @param rotation The rotation to raytrace towards * @return The calculated raytrace result */ - public static RayTraceResult rayTraceTowards(Rotation rotation) { - double blockReachDistance = Helper.HELPER.playerController().getBlockReachDistance(); - Vec3d start = Helper.HELPER.player().getPositionEyes(1.0F); + public static RayTraceResult rayTraceTowards(Entity entity, Rotation rotation, double blockReachDistance) { + Vec3d start = entity.getPositionEyes(1.0F); Vec3d direction = RotationUtils.calcVec3dFromRotation(rotation); Vec3d end = start.add( direction.x * blockReachDistance, diff --git a/src/main/java/baritone/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java similarity index 94% rename from src/main/java/baritone/utils/RotationUtils.java rename to src/api/java/baritone/api/utils/RotationUtils.java index b9dc0589..e1726812 100644 --- a/src/main/java/baritone/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -15,10 +15,8 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.api.utils; -import baritone.api.utils.Rotation; -import baritone.api.utils.VecUtils; import net.minecraft.block.BlockFire; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; @@ -30,7 +28,7 @@ import java.util.Optional; * @author Brady * @since 9/25/2018 */ -public final class RotationUtils implements Helper { +public final class RotationUtils { /** * Constant that a degree value is multiplied by to get the equivalent radian value @@ -137,7 +135,7 @@ public final class RotationUtils implements Helper { * @param pos The target block position * @return The optional rotation */ - public static Optional reachable(Entity entity, BlockPos pos) { + public static Optional reachable(Entity entity, BlockPos pos, double blockReachDistance) { if (pos.equals(RayTraceUtils.getSelectedBlock().orElse(null))) { /* * why add 0.0001? @@ -151,19 +149,19 @@ public final class RotationUtils implements Helper { */ return Optional.of(new Rotation(entity.rotationYaw, entity.rotationPitch + 0.0001F)); } - Optional possibleRotation = reachableCenter(entity, pos); + Optional possibleRotation = reachableCenter(entity, pos, blockReachDistance); //System.out.println("center: " + possibleRotation); if (possibleRotation.isPresent()) { return possibleRotation; } - IBlockState state = mc.world.getBlockState(pos); + IBlockState state = entity.world.getBlockState(pos); AxisAlignedBB aabb = state.getBoundingBox(entity.world, pos); for (Vec3d sideOffset : BLOCK_SIDE_MULTIPLIERS) { double xDiff = aabb.minX * sideOffset.x + aabb.maxX * (1 - sideOffset.x); double yDiff = aabb.minY * sideOffset.y + aabb.maxY * (1 - sideOffset.y); double zDiff = aabb.minZ * sideOffset.z + aabb.maxZ * (1 - sideOffset.z); - possibleRotation = reachableOffset(entity, pos, new Vec3d(pos).add(xDiff, yDiff, zDiff)); + possibleRotation = reachableOffset(entity, pos, new Vec3d(pos).add(xDiff, yDiff, zDiff), blockReachDistance); if (possibleRotation.isPresent()) { return possibleRotation; } @@ -181,9 +179,9 @@ public final class RotationUtils implements Helper { * @param offsetPos The position of the block with the offset applied. * @return The optional rotation */ - public static Optional reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos) { + public static Optional reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance) { Rotation rotation = calcRotationFromVec3d(entity.getPositionEyes(1.0F), offsetPos); - RayTraceResult result = RayTraceUtils.rayTraceTowards(rotation); + RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance); //System.out.println(result); if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { if (result.getBlockPos().equals(pos)) { @@ -204,7 +202,7 @@ public final class RotationUtils implements Helper { * @param pos The target block position * @return The optional rotation */ - public static Optional reachableCenter(Entity entity, BlockPos pos) { - return reachableOffset(entity, pos, VecUtils.calculateBlockCenter(pos)); + public static Optional reachableCenter(Entity entity, BlockPos pos, double blockReachDistance) { + return reachableOffset(entity, pos, VecUtils.calculateBlockCenter(pos), blockReachDistance); } } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 1089d83e..f5c569c0 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -147,7 +147,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { for (BetterBlockPos blockPos : positionsToBreak) { if (!MovementHelper.canWalkThrough(blockPos) && !(BlockStateInterface.getBlock(blockPos) instanceof BlockLiquid)) { // can't break liquid, so don't try somethingInTheWay = true; - Optional reachable = RotationUtils.reachable(player(), blockPos); + Optional reachable = RotationUtils.reachable(player(), blockPos, playerController().getBlockReachDistance()); if (reachable.isPresent()) { MovementHelper.switchToBestToolFor(BlockStateInterface.get(blockPos)); state.setTarget(new MovementState.MovementTarget(reachable.get(), true)); diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index f9268d4f..b20cbf5f 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -19,9 +19,7 @@ package baritone.pathing.movement; import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.Rotation; -import baritone.api.utils.VecUtils; +import baritone.api.utils.*; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.*; import net.minecraft.block.*; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index aa1d7a5b..cd0744e4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -20,8 +20,8 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.utils.RayTraceUtils; -import baritone.utils.RotationUtils; +import baritone.api.utils.RayTraceUtils; +import baritone.api.utils.RotationUtils; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 63930ee8..1467fe1b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -28,8 +28,7 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.InputOverrideHandler; -import baritone.utils.RayTraceUtils; -import baritone.utils.RotationUtils; +import baritone.api.utils.RotationUtils; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; @@ -76,7 +75,7 @@ public class MovementFall extends Movement { targetRotation = new Rotation(player().rotationYaw, 90.0F); - RayTraceResult trace = RayTraceUtils.simulateRayTrace(player().rotationYaw, 90.0F); + RayTraceResult trace = mc.objectMouseOver; if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK) { state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index fed636a5..73aace38 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -20,16 +20,14 @@ package baritone.pathing.movement.movements; import baritone.Baritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.utils.RayTraceUtils; +import baritone.api.utils.RayTraceUtils; import baritone.api.utils.Rotation; -import baritone.utils.RotationUtils; +import baritone.api.utils.RotationUtils; 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.Helper; -import baritone.utils.InputOverrideHandler; +import baritone.utils.*; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -227,7 +225,7 @@ public class MovementParkour extends Movement { double faceY = (dest.getY() + against1.getY()) * 0.5D; double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; Rotation place = RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()); - RayTraceResult res = RayTraceUtils.rayTraceTowards(place); + RayTraceResult res = RayTraceUtils.rayTraceTowards(player(), place, playerController().getBlockReachDistance()); if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(dest.down())) { state.setTarget(new MovementState.MovementTarget(place, true)); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 795884b0..76006da5 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -27,7 +27,7 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; -import baritone.utils.RotationUtils; +import baritone.api.utils.RotationUtils; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index db31bb00..0cf64a72 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -26,8 +26,8 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; -import baritone.utils.RayTraceUtils; -import baritone.utils.RotationUtils; +import baritone.api.utils.RayTraceUtils; +import baritone.api.utils.RotationUtils; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 1f4a120e..27da4496 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -22,7 +22,6 @@ import baritone.api.pathing.goals.*; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.utils.RotationUtils; import baritone.cache.CachedChunk; import baritone.cache.ChunkPacker; import baritone.cache.WorldProvider; @@ -31,6 +30,7 @@ import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; +import baritone.api.utils.RotationUtils; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; @@ -248,7 +248,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro for (int y = playerFeet.getY() - searchDist; y <= playerFeet.getY() + searchDist; y++) { for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) { BlockPos pos = new BlockPos(x, y, z); - if (mining.contains(BlockStateInterface.getBlock(pos)) && RotationUtils.reachable(player(), pos).isPresent()) {//crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught + if (mining.contains(BlockStateInterface.getBlock(pos)) && RotationUtils.reachable(player(), pos, playerController().getBlockReachDistance()).isPresent()) {//crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught knownOreLocations.add(pos); } } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 70f6c1b9..2fbf05f7 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -23,6 +23,7 @@ import baritone.api.cache.IWaypoint; import baritone.api.event.events.ChatEvent; import baritone.api.pathing.goals.*; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.utils.RayTraceUtils; import baritone.api.utils.SettingsUtil; import baritone.behavior.Behavior; import baritone.behavior.PathingBehavior; From b054e9dbe841ccb5e101cf9b11bb2e389636f1b9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 9 Nov 2018 19:24:02 -0800 Subject: [PATCH 285/305] toxic cloud to get around two references to mc.player.dimension --- src/main/java/baritone/cache/CachedChunk.java | 10 ++++------ src/main/java/baritone/cache/CachedRegion.java | 7 +++++-- src/main/java/baritone/cache/CachedWorld.java | 7 +++++-- src/main/java/baritone/cache/ChunkPacker.java | 4 ++-- src/main/java/baritone/cache/WorldData.java | 6 ++++-- src/main/java/baritone/cache/WorldProvider.java | 2 +- 6 files changed, 21 insertions(+), 15 deletions(-) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index c554b926..abc741a5 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -17,7 +17,6 @@ package baritone.cache; -import baritone.api.cache.IBlockTypeAccess; import baritone.utils.Helper; import baritone.utils.pathing.PathingBlockType; import net.minecraft.block.Block; @@ -31,7 +30,7 @@ import java.util.*; * @author Brady * @since 8/3/2018 1:04 AM */ -public final class CachedChunk implements IBlockTypeAccess, Helper { +public final class CachedChunk implements Helper { public static final Set BLOCKS_TO_KEEP_TRACK_OF; @@ -143,8 +142,7 @@ public final class CachedChunk implements IBlockTypeAccess, Helper { calculateHeightMap(); } - @Override - public final IBlockState getBlock(int x, int y, int z) { + public final IBlockState getBlock(int x, int y, int z, int dimension) { int internalPos = z << 4 | x; if (heightMap[internalPos] == y) { // we have this exact block, it's a surface block @@ -155,10 +153,10 @@ public final class CachedChunk implements IBlockTypeAccess, Helper { return overview[internalPos]; } PathingBlockType type = getType(x, y, z); - if (type == PathingBlockType.SOLID && y == 127 && mc.player.dimension == -1) { + if (type == PathingBlockType.SOLID && y == 127 && dimension == -1) { return Blocks.BEDROCK.getDefaultState(); } - return ChunkPacker.pathingTypeToBlock(type); + return ChunkPacker.pathingTypeToBlock(type, dimension); } private PathingBlockType getType(int x, int y, int z) { diff --git a/src/main/java/baritone/cache/CachedRegion.java b/src/main/java/baritone/cache/CachedRegion.java index c25139ac..95c20f37 100644 --- a/src/main/java/baritone/cache/CachedRegion.java +++ b/src/main/java/baritone/cache/CachedRegion.java @@ -59,22 +59,25 @@ public final class CachedRegion implements ICachedRegion { */ private final int z; + private final int dimension; + /** * Has this region been modified since its most recent load or save */ private boolean hasUnsavedChanges; - CachedRegion(int x, int z) { + CachedRegion(int x, int z, int dimension) { this.x = x; this.z = z; this.hasUnsavedChanges = false; + this.dimension = dimension; } @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 chunk.getBlock(x & 15, y, z & 15, dimension); } return null; } diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index b1fcd6fd..ad04755b 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -56,7 +56,9 @@ public final class CachedWorld implements ICachedWorld, Helper { private final LinkedBlockingQueue toPack = new LinkedBlockingQueue<>(); - CachedWorld(Path directory) { + private final int dimension; + + CachedWorld(Path directory, int dimension) { if (!Files.exists(directory)) { try { Files.createDirectories(directory); @@ -64,6 +66,7 @@ public final class CachedWorld implements ICachedWorld, Helper { } } this.directory = directory.toString(); + this.dimension = dimension; System.out.println("Cached world directory: " + directory); // Insert an invalid region element cachedRegions.put(0, null); @@ -241,7 +244,7 @@ public final class CachedWorld implements ICachedWorld, Helper { */ private synchronized CachedRegion getOrCreateRegion(int regionX, int regionZ) { return cachedRegions.computeIfAbsent(getRegionID(regionX, regionZ), id -> { - CachedRegion newRegion = new CachedRegion(regionX, regionZ); + CachedRegion newRegion = new CachedRegion(regionX, regionZ, dimension); newRegion.load(this.directory); return newRegion; }); diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index e29bde00..d73cdb03 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -144,7 +144,7 @@ public final class ChunkPacker implements Helper { return PathingBlockType.SOLID; } - public static IBlockState pathingTypeToBlock(PathingBlockType type) { + public static IBlockState pathingTypeToBlock(PathingBlockType type, int dimension) { switch (type) { case AIR: return Blocks.AIR.getDefaultState(); @@ -154,7 +154,7 @@ public final class ChunkPacker implements Helper { return Blocks.LAVA.getDefaultState(); case SOLID: // Dimension solid types - switch (mc.player.dimension) { + switch (dimension) { case -1: return Blocks.NETHERRACK.getDefaultState(); case 0: diff --git a/src/main/java/baritone/cache/WorldData.java b/src/main/java/baritone/cache/WorldData.java index 36a239fa..897a0d87 100644 --- a/src/main/java/baritone/cache/WorldData.java +++ b/src/main/java/baritone/cache/WorldData.java @@ -35,11 +35,13 @@ public class WorldData implements IWorldData { private final Waypoints waypoints; //public final MapData map; public final Path directory; + public final int dimension; - WorldData(Path directory) { + WorldData(Path directory, int dimension) { this.directory = directory; - this.cache = new CachedWorld(directory.resolve("cache")); + this.cache = new CachedWorld(directory.resolve("cache"), dimension); this.waypoints = new Waypoints(directory.resolve("waypoints")); + this.dimension = dimension; } public void onClose() { diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index e3a53bba..45b46fdb 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -91,7 +91,7 @@ public enum WorldProvider implements IWorldProvider, Helper { } catch (IOException ignored) {} } System.out.println("Baritone world data dir: " + dir); - this.currentWorld = this.worldCache.computeIfAbsent(dir, WorldData::new); + this.currentWorld = this.worldCache.computeIfAbsent(dir, d -> new WorldData(d, dimensionID)); } public final void closeWorld() { From 0bd46e88a5c7ae5f1edbea3a26c77b148d60f7a1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 9 Nov 2018 20:21:58 -0800 Subject: [PATCH 286/305] branch compatibility message --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d88647f3..445d34bb 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Building Baritone: $ gradlew build ``` -For example, to replace out Impact 4.4's Baritone build with a customized one, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). +For example, to replace out Impact 4.4's Baritone build with a customized one, switch to the `impact4.4-compat` branch, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). ## IntelliJ's Gradle UI - Open the project in IntelliJ as a Gradle project From 1c80950a70a78827fb0406d093ab12351ed67edd Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 9 Nov 2018 22:32:21 -0600 Subject: [PATCH 287/305] Add note to MixinBlockPos I looked at this Mixin for a second and thought wtf why did I make this and then remembered why, so it's probably important to let anybody else that looks at it know why. --- src/launch/java/baritone/launch/mixins/MixinBlockPos.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/launch/java/baritone/launch/mixins/MixinBlockPos.java b/src/launch/java/baritone/launch/mixins/MixinBlockPos.java index 013980a9..b0aa75ba 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBlockPos.java +++ b/src/launch/java/baritone/launch/mixins/MixinBlockPos.java @@ -35,6 +35,12 @@ public class MixinBlockPos extends Vec3i { super(xIn, yIn, zIn); } + /** + * The purpose of this was to ensure a friendly name for when we print raw + * block positions to chat in the context of an obfuscated environment. + * + * @return a string representation of the object. + */ @Override @Nonnull public String toString() { From 232644feb0e8a41a7d39682e4b836bed5650412c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 10 Nov 2018 09:25:35 -0800 Subject: [PATCH 288/305] these are cool and should default on --- src/api/java/baritone/api/Settings.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index e2e4604d..7fce0254 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -312,17 +312,17 @@ public class Settings { /** * Ignore depth when rendering the goal */ - public Setting renderGoalIgnoreDepth = new Setting<>(false); + public Setting renderGoalIgnoreDepth = new Setting<>(true); /** * Ignore depth when rendering the selection boxes (to break, to place, to walk into) */ - public Setting renderSelectionBoxesIgnoreDepth = new Setting<>(false); + public Setting renderSelectionBoxesIgnoreDepth = new Setting<>(true); /** * Ignore depth when rendering the path */ - public Setting renderPathIgnoreDepth = new Setting<>(false); + public Setting renderPathIgnoreDepth = new Setting<>(true); /** * Line width of the path when rendered, in pixels From 73d4e9bbb9c051b13cfa67d6f251894a2d8cd12b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 10 Nov 2018 09:37:23 -0800 Subject: [PATCH 289/305] another day another static world reference gone --- src/api/java/baritone/api/pathing/calc/IPath.java | 3 ++- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- src/main/java/baritone/utils/pathing/PathBase.java | 6 +++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/pathing/calc/IPath.java b/src/api/java/baritone/api/pathing/calc/IPath.java index ad25911a..0844ab90 100644 --- a/src/api/java/baritone/api/pathing/calc/IPath.java +++ b/src/api/java/baritone/api/pathing/calc/IPath.java @@ -22,6 +22,7 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; import baritone.api.utils.BetterBlockPos; import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; import java.util.List; @@ -120,7 +121,7 @@ public interface IPath { * * @return The result of this cut-off operation */ - default IPath cutoffAtLoadedChunks() { + default IPath cutoffAtLoadedChunks(World world) { throw new UnsupportedOperationException(); } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index c9c95c87..93a8c35c 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -400,7 +400,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, Optional path = calcResult.path; if (Baritone.settings().cutoffAtLoadBoundary.get()) { path = path.map(p -> { - IPath result = p.cutoffAtLoadedChunks(); + IPath result = p.cutoffAtLoadedChunks(context.world()); if (result instanceof CutoffPath) { logDebug("Cutting off path at edge of loaded chunks"); diff --git a/src/main/java/baritone/utils/pathing/PathBase.java b/src/main/java/baritone/utils/pathing/PathBase.java index 57ee941d..aaf36895 100644 --- a/src/main/java/baritone/utils/pathing/PathBase.java +++ b/src/main/java/baritone/utils/pathing/PathBase.java @@ -21,16 +21,16 @@ import baritone.api.BaritoneAPI; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.pathing.path.CutoffPath; -import net.minecraft.client.Minecraft; import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; import net.minecraft.world.chunk.EmptyChunk; public abstract class PathBase implements IPath { @Override - public IPath cutoffAtLoadedChunks() { + public IPath cutoffAtLoadedChunks(World world) { for (int i = 0; i < positions().size(); i++) { BlockPos pos = positions().get(i); - if (Minecraft.getMinecraft().world.getChunk(pos) instanceof EmptyChunk) { + if (world.getChunk(pos) instanceof EmptyChunk) { return new CutoffPath(this, i); } } From f854d886d17038c4f2affc5b06fdff703e370e2a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 10 Nov 2018 11:26:52 -0800 Subject: [PATCH 290/305] fix water bucket being placed one tick too early --- .../baritone/pathing/movement/movements/MovementFall.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 1467fe1b..ba57eeac 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -21,6 +21,7 @@ import baritone.Baritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; +import baritone.api.utils.RotationUtils; import baritone.api.utils.VecUtils; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -28,7 +29,6 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.InputOverrideHandler; -import baritone.api.utils.RotationUtils; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; @@ -76,7 +76,7 @@ public class MovementFall extends Movement { targetRotation = new Rotation(player().rotationYaw, 90.0F); RayTraceResult trace = mc.objectMouseOver; - if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK) { + if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK && player().rotationPitch > 89.0F) { state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); } } From a83074e77327e677ab0896356be172108e94e298 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Nov 2018 14:20:38 -0600 Subject: [PATCH 291/305] Map Input to state in InputOverrideHandler --- src/main/java/baritone/behavior/Behavior.java | 2 +- .../baritone/utils/InputOverrideHandler.java | 49 +++++++++++++++---- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/main/java/baritone/behavior/Behavior.java b/src/main/java/baritone/behavior/Behavior.java index 154897d1..66434d7a 100644 --- a/src/main/java/baritone/behavior/Behavior.java +++ b/src/main/java/baritone/behavior/Behavior.java @@ -21,7 +21,7 @@ import baritone.Baritone; import baritone.api.behavior.IBehavior; /** - * A type of game event listener that can be toggled. + * A type of game event listener that is given {@link Baritone} instance context. * * @author Brady * @since 8/1/2018 6:29 PM diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index b42b0ee1..9c3eed7f 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -23,6 +23,7 @@ import baritone.behavior.Behavior; import net.minecraft.client.settings.KeyBinding; import org.lwjgl.input.Keyboard; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -41,13 +42,9 @@ public final class InputOverrideHandler extends Behavior implements Helper { } /** - * Maps keybinds to whether or not we are forcing their state down. + * Maps inputs to whether or not we are forcing their state down. */ - private final Map inputForceStateMap = new HashMap<>(); - - public final void clearAllKeys() { - inputForceStateMap.clear(); - } + private final Map inputForceStateMap = new HashMap<>(); /** * Returns whether or not we are forcing down the specified {@link KeyBinding}. @@ -56,7 +53,17 @@ public final class InputOverrideHandler extends Behavior implements Helper { * @return Whether or not it is being forced down */ public final boolean isInputForcedDown(KeyBinding key) { - return inputForceStateMap.getOrDefault(key, false); + return isInputForcedDown(Input.getInputForBind(key)); + } + + /** + * Returns whether or not we are forcing down the specified {@link Input}. + * + * @param input The input + * @return Whether or not it is being forced down + */ + public final boolean isInputForcedDown(Input input) { + return input == null ? false : this.inputForceStateMap.getOrDefault(input, false); } /** @@ -66,7 +73,14 @@ public final class InputOverrideHandler extends Behavior implements Helper { * @param forced Whether or not the state is being forced */ public final void setInputForceState(Input input, boolean forced) { - inputForceStateMap.put(input.getKeyBinding(), forced); + this.inputForceStateMap.put(input, forced); + } + + /** + * Clears the override state for all keys + */ + public final void clearAllKeys() { + this.inputForceStateMap.clear(); } @Override @@ -97,7 +111,9 @@ public final class InputOverrideHandler extends Behavior implements Helper { } /** - * An {@link Enum} representing the possible inputs that we may want to force. + * An {@link Enum} representing the inputs that control the player's + * behavior. This includes moving, interacting with blocks, jumping, + * sneaking, and sprinting. */ public enum Input { @@ -146,6 +162,11 @@ public final class InputOverrideHandler extends Behavior implements Helper { */ SPRINT(mc.gameSettings.keyBindSprint); + /** + * Map of {@link KeyBinding} to {@link Input}. Values should be queried through {@link #getInputForBind(KeyBinding)} + */ + private static final Map bindToInputMap = new HashMap<>(); + /** * The actual game {@link KeyBinding} being forced. */ @@ -161,5 +182,15 @@ public final class InputOverrideHandler extends Behavior implements Helper { public final KeyBinding getKeyBinding() { return this.keyBinding; } + + /** + * Finds the {@link Input} constant that is associated with the specified {@link KeyBinding}. + * + * @param binding The {@link KeyBinding} to find the associated {@link Input} for + * @return The {@link Input} associated with the specified {@link KeyBinding} + */ + public static Input getInputForBind(KeyBinding binding) { + return bindToInputMap.computeIfAbsent(binding, b -> Arrays.stream(values()).filter(input -> input.keyBinding == b).findFirst().orElse(null)); + } } } From 45e4239b2615f4cee6cd096b3ce15b38da6e8a4d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 11 Nov 2018 12:35:04 -0800 Subject: [PATCH 292/305] context specific blockstateinterface lookups. also toxic --- src/main/java/baritone/Baritone.java | 6 +- .../baritone/behavior/MemoryBehavior.java | 7 +-- src/main/java/baritone/cache/CachedWorld.java | 2 +- .../java/baritone/cache/WorldProvider.java | 6 +- .../java/baritone/event/GameEventHandler.java | 4 +- .../pathing/calc/AStarPathFinder.java | 4 +- src/main/java/baritone/pathing/calc/Path.java | 2 +- .../pathing/movement/CalculationContext.java | 16 +++++ .../baritone/pathing/movement/Movement.java | 8 ++- .../pathing/movement/MovementHelper.java | 61 +++++++++---------- .../movement/movements/MovementAscend.java | 14 ++--- .../movement/movements/MovementDescend.java | 21 +++---- .../movement/movements/MovementDiagonal.java | 25 ++++---- .../movement/movements/MovementDownward.java | 5 +- .../movement/movements/MovementParkour.java | 28 +++++---- .../movement/movements/MovementPillar.java | 42 ++++++------- .../movement/movements/MovementTraverse.java | 14 ++--- .../baritone/process/GetToBlockProcess.java | 2 +- .../java/baritone/process/MineProcess.java | 11 ++-- .../baritone/utils/BlockStateInterface.java | 22 ++++--- .../utils/ExampleBaritoneControl.java | 23 ++++--- src/main/java/baritone/utils/Helper.java | 3 + 22 files changed, 175 insertions(+), 151 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 69dc1b2a..6df47147 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -82,6 +82,8 @@ public enum Baritone implements IBaritone { private PathingControlManager pathingControlManager; + private WorldProvider worldProvider; + private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); Baritone() { @@ -115,6 +117,8 @@ public enum Baritone implements IBaritone { getToBlockProcess = new GetToBlockProcess(this); } + this.worldProvider = new WorldProvider(); + if (BaritoneAutoTest.ENABLE_AUTO_TEST) { registerEventListener(BaritoneAutoTest.INSTANCE); } @@ -194,7 +198,7 @@ public enum Baritone implements IBaritone { @Override public WorldProvider getWorldProvider() { - return WorldProvider.INSTANCE; + return worldProvider; } @Override diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 510cecff..1e8e069a 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -26,7 +26,6 @@ import baritone.api.event.events.PacketEvent; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.type.EventState; import baritone.cache.Waypoint; -import baritone.cache.WorldProvider; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import net.minecraft.block.BlockBed; @@ -122,13 +121,13 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H @Override public void onBlockInteract(BlockInteractEvent event) { if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(event.getPos()) instanceof BlockBed) { - WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos())); + baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos())); } } @Override public void onPlayerDeath() { - WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, playerFeet())); + baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, playerFeet())); } private Optional getInventoryFromWindow(int windowId) { @@ -143,7 +142,7 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H } private WorldDataContainer getCurrentContainer() { - return this.worldDataContainers.computeIfAbsent(WorldProvider.INSTANCE.getCurrentWorld(), data -> new WorldDataContainer()); + return this.worldDataContainers.computeIfAbsent(baritone.getWorldProvider().getCurrentWorld(), data -> new WorldDataContainer()); } @Override diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index ad04755b..b775902e 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -190,7 +190,7 @@ public final class CachedWorld implements ICachedWorld, Helper { * If we are still in this world and dimension, return player feet, otherwise return most recently modified chunk */ private BlockPos guessPosition() { - WorldData data = WorldProvider.INSTANCE.getCurrentWorld(); + WorldData data = Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); if (data != null && data.getCachedWorld() == this) { return playerFeet(); } diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index 45b46fdb..d6f3aab1 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -39,11 +39,9 @@ import java.util.function.Consumer; * @author Brady * @since 8/4/2018 11:06 AM */ -public enum WorldProvider implements IWorldProvider, Helper { +public class WorldProvider implements IWorldProvider, Helper { - INSTANCE; - - private final Map worldCache = new HashMap<>(); + private static final Map worldCache = new HashMap<>(); // this is how the bots have the same cached world private WorldData currentWorld; diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index b42b3e06..2859731a 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -79,7 +79,7 @@ public final class GameEventHandler implements IGameEventListener, Helper { && mc.world.getChunkProvider().isChunkGeneratedAt(event.getX(), event.getZ()); if (isPostPopulate || isPreUnload) { - WorldProvider.INSTANCE.ifWorldLoaded(world -> { + baritone.getWorldProvider().ifWorldLoaded(world -> { Chunk chunk = mc.world.getChunk(event.getX(), event.getZ()); world.getCachedWorld().queueForPacking(chunk); }); @@ -96,7 +96,7 @@ public final class GameEventHandler implements IGameEventListener, Helper { @Override public final void onWorldEvent(WorldEvent event) { - WorldProvider cache = WorldProvider.INSTANCE; + WorldProvider cache = baritone.getWorldProvider(); BlockStateInterface.clearCachedChunk(); diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index 41c11ea5..9d69959d 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -65,7 +65,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel } MutableMoveResult res = new MutableMoveResult(); HashSet favored = favoredPositions.orElse(null); - BetterWorldBorder worldBorder = new BetterWorldBorder(world().getWorldBorder()); + BetterWorldBorder worldBorder = new BetterWorldBorder(calcContext.world().getWorldBorder()); BlockStateInterface.clearCachedChunk(); long startTime = System.nanoTime() / 1000000L; boolean slowPath = Baritone.settings().slowPath.get(); @@ -100,7 +100,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel for (Moves moves : Moves.values()) { int newX = currentNode.x + moves.xOffset; int newZ = currentNode.z + moves.zOffset; - if ((newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) && !BlockStateInterface.isLoaded(newX, newZ)) { + if ((newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) && !BlockStateInterface.isLoaded(calcContext, newX, newZ)) { // only need to check if the destination is a loaded chunk if it's in a different chunk than the start of the movement if (!moves.dynamicXZ) { // only increment the counter if the movement would have gone out of bounds guaranteed numEmptyChunk++; diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 58e1e661..0b5b2cc7 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -148,7 +148,7 @@ class Path extends PathBase { } verified = true; boolean failed = assembleMovements(); - movements.forEach(Movement::checkLoadedChunk); + movements.forEach(m -> m.checkLoadedChunk(context)); if (failed) { // at least one movement became impossible during calculation CutoffPath res = new CutoffPath(this, movements().size()); diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 10aa03c0..5f367f00 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -19,14 +19,18 @@ package baritone.pathing.movement; import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; +import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.ToolSet; import baritone.utils.pathing.BetterWorldBorder; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; +import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; /** @@ -75,6 +79,18 @@ public class CalculationContext { this.worldBorder = new BetterWorldBorder(world.getWorldBorder()); } + public IBlockState get(int x, int y, int z) { + return BlockStateInterface.get(world, x, y, z); + } + + public IBlockState get(BlockPos pos) { + return get(pos.getX(), pos.getY(), pos.getZ()); + } + + public Block getBlock(int x, int y, int z) { + return get(x, y, z).getBlock(); + } + public boolean canPlaceThrowawayAt(int x, int y, int z) { if (!hasThrowaway()) { // only true if allowPlace is true, see constructor return false; diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index f5c569c0..f11e1955 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -21,7 +21,9 @@ import baritone.Baritone; import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.*; -import baritone.utils.*; +import baritone.utils.BlockStateInterface; +import baritone.utils.Helper; +import baritone.utils.InputOverrideHandler; import net.minecraft.block.BlockLiquid; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -226,8 +228,8 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { return getDest().subtract(getSrc()); } - public void checkLoadedChunk() { - calculatedWhileLoaded = !(world().getChunk(getDest()) instanceof EmptyChunk); + public void checkLoadedChunk(CalculationContext context) { + calculatedWhileLoaded = !(context.world().getChunk(getDest()) instanceof EmptyChunk); } @Override diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index b20cbf5f..a7e9c378 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -21,7 +21,10 @@ import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; import baritone.api.utils.*; import baritone.pathing.movement.MovementState.MovementTarget; -import baritone.utils.*; +import baritone.utils.BlockStateInterface; +import baritone.utils.Helper; +import baritone.utils.InputOverrideHandler; +import baritone.utils.ToolSet; import net.minecraft.block.*; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.IBlockState; @@ -41,16 +44,16 @@ import net.minecraft.world.chunk.EmptyChunk; */ public interface MovementHelper extends ActionCosts, Helper { - static boolean avoidBreaking(int x, int y, int z, IBlockState state) { + static boolean avoidBreaking(CalculationContext context, int x, int y, int z, IBlockState state) { Block b = state.getBlock(); return b == Blocks.ICE // ice becomes water, and water can mess up the path || b instanceof BlockSilverfish // obvious reasons - // call BlockStateInterface.get directly with x,y,z. no need to make 5 new BlockPos for no reason - || BlockStateInterface.get(x, y + 1, z).getBlock() instanceof BlockLiquid//don't break anything touching liquid on any side - || BlockStateInterface.get(x + 1, y, z).getBlock() instanceof BlockLiquid - || BlockStateInterface.get(x - 1, y, z).getBlock() instanceof BlockLiquid - || BlockStateInterface.get(x, y, z + 1).getBlock() instanceof BlockLiquid - || BlockStateInterface.get(x, y, z - 1).getBlock() instanceof BlockLiquid; + // call context.get directly with x,y,z. no need to make 5 new BlockPos for no reason + || context.get(x, y + 1, z).getBlock() instanceof BlockLiquid//don't break anything touching liquid on any side + || context.get(x + 1, y, z).getBlock() instanceof BlockLiquid + || context.get(x - 1, y, z).getBlock() instanceof BlockLiquid + || context.get(x, y, z + 1).getBlock() instanceof BlockLiquid + || context.get(x, y, z - 1).getBlock() instanceof BlockLiquid; } /** @@ -60,14 +63,14 @@ public interface MovementHelper extends ActionCosts, Helper { * @return */ static boolean canWalkThrough(BetterBlockPos pos) { - return canWalkThrough(pos.x, pos.y, pos.z, BlockStateInterface.get(pos)); + return canWalkThrough(new CalculationContext(), pos.x, pos.y, pos.z, BlockStateInterface.get(pos)); } - static boolean canWalkThrough(int x, int y, int z) { - return canWalkThrough(x, y, z, BlockStateInterface.get(x, y, z)); + static boolean canWalkThrough(CalculationContext context, int x, int y, int z) { + return canWalkThrough(context, x, y, z, context.get(x, y, z)); } - static boolean canWalkThrough(int x, int y, int z, IBlockState state) { + static boolean canWalkThrough(CalculationContext context, int x, int y, int z, IBlockState state) { Block block = state.getBlock(); if (block == Blocks.AIR) { // early return for most common case return true; @@ -108,7 +111,7 @@ public interface MovementHelper extends ActionCosts, Helper { if (Baritone.settings().assumeWalkOnWater.get()) { return false; } - IBlockState up = BlockStateInterface.get(x, y + 1, z); + IBlockState up = context.get(x, y + 1, z); if (up.getBlock() instanceof BlockLiquid || up.getBlock() instanceof BlockLilyPad) { return false; } @@ -126,8 +129,8 @@ public interface MovementHelper extends ActionCosts, Helper { * * @return */ - static boolean fullyPassable(int x, int y, int z) { - return fullyPassable(BlockStateInterface.get(x, y, z)); + static boolean fullyPassable(CalculationContext context, int x, int y, int z) { + return fullyPassable(context.get(x, y, z)); } static boolean fullyPassable(IBlockState state) { @@ -242,7 +245,7 @@ public interface MovementHelper extends ActionCosts, Helper { * * @return */ - static boolean canWalkOn(int x, int y, int z, IBlockState state) { + static boolean canWalkOn(CalculationContext context, int x, int y, int z, IBlockState state) { Block block = state.getBlock(); if (block == Blocks.AIR || block == Blocks.MAGMA) { // early return for most common case (air) @@ -264,7 +267,7 @@ public interface MovementHelper extends ActionCosts, Helper { if (isWater(block)) { // since this is called literally millions of times per second, the benefit of not allocating millions of useless "pos.up()" // BlockPos s that we'd just garbage collect immediately is actually noticeable. I don't even think its a decrease in readability - Block up = BlockStateInterface.get(x, y + 1, z).getBlock(); + Block up = context.get(x, y + 1, z).getBlock(); if (up == Blocks.WATERLILY) { return true; } @@ -292,19 +295,19 @@ public interface MovementHelper extends ActionCosts, Helper { } static boolean canWalkOn(BetterBlockPos pos, IBlockState state) { - return canWalkOn(pos.x, pos.y, pos.z, state); + return canWalkOn(new CalculationContext(), pos.x, pos.y, pos.z, state); } static boolean canWalkOn(BetterBlockPos pos) { - return canWalkOn(pos.x, pos.y, pos.z, BlockStateInterface.get(pos)); + return canWalkOn(new CalculationContext(), pos.x, pos.y, pos.z, BlockStateInterface.get(pos)); } - static boolean canWalkOn(int x, int y, int z) { - return canWalkOn(x, y, z, BlockStateInterface.get(x, y, z)); + static boolean canWalkOn(CalculationContext context, int x, int y, int z) { + return canWalkOn(context, x, y, z, context.get(x, y, z)); } - static boolean canPlaceAgainst(int x, int y, int z) { - return canPlaceAgainst(BlockStateInterface.get(x, y, z)); + static boolean canPlaceAgainst(CalculationContext context, int x, int y, int z) { + return canPlaceAgainst(context.get(x, y, z)); } static boolean canPlaceAgainst(BlockPos pos) { @@ -317,16 +320,16 @@ public interface MovementHelper extends ActionCosts, Helper { } static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, boolean includeFalling) { - return getMiningDurationTicks(context, x, y, z, BlockStateInterface.get(x, y, z), includeFalling); + return getMiningDurationTicks(context, x, y, z, context.get(x, y, z), includeFalling); } static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) { Block block = state.getBlock(); - if (!canWalkThrough(x, y, z, state)) { + if (!canWalkThrough(context, x, y, z, state)) { if (!context.canBreakAt(x, y, z)) { return COST_INF; } - if (avoidBreaking(x, y, z, state)) { + if (avoidBreaking(context, x, y, z, state)) { return COST_INF; } if (block instanceof BlockLiquid) { @@ -341,7 +344,7 @@ public interface MovementHelper extends ActionCosts, Helper { double result = m / strVsBlock; result += context.breakBlockAdditionalCost(); if (includeFalling) { - IBlockState above = BlockStateInterface.get(x, y + 1, z); + IBlockState above = context.get(x, y + 1, z); if (above.getBlock() instanceof BlockFalling) { result += getMiningDurationTicks(context, x, y + 1, z, above, true); } @@ -357,10 +360,6 @@ public interface MovementHelper extends ActionCosts, Helper { && state.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.BOTTOM; } - static boolean isBottomSlab(BlockPos pos) { - return isBottomSlab(BlockStateInterface.get(pos)); - } - /** * AutoTool */ diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index cd0744e4..1d161554 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -58,20 +58,20 @@ public class MovementAscend extends Movement { } public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) { - IBlockState srcDown = BlockStateInterface.get(x, y - 1, z); + IBlockState srcDown = context.get(x, y - 1, z); if (srcDown.getBlock() == Blocks.LADDER || srcDown.getBlock() == Blocks.VINE) { return COST_INF; } // we can jump from soul sand, but not from a bottom slab boolean jumpingFromBottomSlab = MovementHelper.isBottomSlab(srcDown); - IBlockState toPlace = BlockStateInterface.get(destX, y, destZ); + IBlockState toPlace = context.get(destX, y, destZ); boolean jumpingToBottomSlab = MovementHelper.isBottomSlab(toPlace); if (jumpingFromBottomSlab && !jumpingToBottomSlab) { return COST_INF;// the only thing we can ascend onto from a bottom slab is another bottom slab } boolean hasToPlace = false; - if (!MovementHelper.canWalkOn(destX, y, destZ, toPlace)) { + if (!MovementHelper.canWalkOn(context, destX, y, destZ, toPlace)) { if (!context.canPlaceThrowawayAt(destX, y, destZ)) { return COST_INF; } @@ -87,7 +87,7 @@ public class MovementAscend extends Movement { if (againstX == x && againstZ == z) { continue; } - if (MovementHelper.canPlaceAgainst(againstX, y, againstZ)) { + if (MovementHelper.canPlaceAgainst(context, againstX, y, againstZ)) { hasToPlace = true; break; } @@ -97,7 +97,7 @@ public class MovementAscend extends Movement { } } IBlockState srcUp2 = null; - if (BlockStateInterface.get(x, y + 3, z).getBlock() instanceof BlockFalling && (MovementHelper.canWalkThrough(x, y + 1, z) || !((srcUp2 = BlockStateInterface.get(x, y + 2, z)).getBlock() instanceof BlockFalling))) {//it would fall on us and possibly suffocate us + if (context.get(x, y + 3, z).getBlock() instanceof BlockFalling && (MovementHelper.canWalkThrough(context, x, y + 1, z) || !((srcUp2 = context.get(x, y + 2, z)).getBlock() instanceof BlockFalling))) {//it would fall on us and possibly suffocate us // HOWEVER, we assume that we're standing in the start position // 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 @@ -138,7 +138,7 @@ public class MovementAscend extends Movement { totalCost += context.placeBlockCost(); } if (srcUp2 == null) { - srcUp2 = BlockStateInterface.get(x, y + 2, z); + srcUp2 = context.get(x, y + 2, z); } totalCost += MovementHelper.getMiningDurationTicks(context, x, y + 2, z, srcUp2, false); // TODO MAKE ABSOLUTELY SURE we don't need includeFalling here, from the falling check above if (totalCost >= COST_INF) { @@ -204,7 +204,7 @@ public class MovementAscend extends Movement { return state.setStatus(MovementStatus.UNREACHABLE); } MovementHelper.moveTowards(state, dest); - if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(src.down())) { + if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(BlockStateInterface.get(src.down()))) { return state; // don't jump while walking from a non double slab into a bottom slab } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index a8874989..84f0d781 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -24,7 +24,6 @@ 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.pathing.MutableMoveResult; import net.minecraft.block.Block; @@ -58,13 +57,13 @@ public class MovementDescend extends Movement { } public static void cost(CalculationContext context, int x, int y, int z, int destX, int destZ, MutableMoveResult res) { - Block fromDown = BlockStateInterface.get(x, y - 1, z).getBlock(); + Block fromDown = context.get(x, y - 1, z).getBlock(); if (fromDown == Blocks.LADDER || fromDown == Blocks.VINE) { return; } double totalCost = 0; - IBlockState destDown = BlockStateInterface.get(destX, y - 1, destZ); + IBlockState destDown = context.get(destX, y - 1, destZ); totalCost += MovementHelper.getMiningDurationTicks(context, destX, y - 1, destZ, destDown, false); if (totalCost >= COST_INF) { return; @@ -88,8 +87,8 @@ public class MovementDescend extends Movement { //A is plausibly breakable by either descend or fall //C, D, etc determine the length of the fall - IBlockState below = BlockStateInterface.get(destX, y - 2, destZ); - if (!MovementHelper.canWalkOn(destX, y - 2, destZ, below)) { + IBlockState below = context.get(destX, y - 2, destZ); + if (!MovementHelper.canWalkOn(context, destX, y - 2, destZ, below)) { dynamicFallCost(context, x, y, z, destX, destZ, totalCost, below, res); return; } @@ -112,13 +111,13 @@ public class MovementDescend extends Movement { } public static void dynamicFallCost(CalculationContext context, int x, int y, int z, int destX, int destZ, double frontBreak, IBlockState below, MutableMoveResult res) { - if (frontBreak != 0 && BlockStateInterface.get(destX, y + 2, destZ).getBlock() instanceof BlockFalling) { + if (frontBreak != 0 && context.get(destX, y + 2, destZ).getBlock() instanceof BlockFalling) { // if frontBreak is 0 we can actually get through this without updating the falling block and making it actually fall // but if frontBreak is nonzero, we're breaking blocks in front, so don't let anything fall through this column, // and potentially replace the water we're going to fall into return; } - if (!MovementHelper.canWalkThrough(destX, y - 2, destZ, below) && below.getBlock() != Blocks.WATER) { + if (!MovementHelper.canWalkThrough(context, destX, y - 2, destZ, below) && below.getBlock() != Blocks.WATER) { return; } for (int fallHeight = 3; true; fallHeight++) { @@ -128,9 +127,9 @@ public class MovementDescend extends Movement { // this check prevents it from getting the block at y=-1 and crashing return; } - IBlockState ontoBlock = BlockStateInterface.get(destX, newY, destZ); + IBlockState ontoBlock = context.get(destX, newY, destZ); double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[fallHeight] + frontBreak; - if (ontoBlock.getBlock() == Blocks.WATER && !MovementHelper.isFlowing(ontoBlock) && BlockStateInterface.getBlock(destX, newY + 1, destZ) != Blocks.WATERLILY) { // TODO flowing check required here? + if (ontoBlock.getBlock() == Blocks.WATER && !MovementHelper.isFlowing(ontoBlock) && context.getBlock(destX, newY + 1, destZ) != Blocks.WATERLILY) { // TODO flowing check required here? // lilypads are canWalkThrough, but we can't end a fall that should be broken by water if it's covered by a lilypad // however, don't return impossible in the lilypad scenario, because we could still jump right on it (water that's below a lilypad is canWalkOn so it works) if (Baritone.settings().assumeWalkOnWater.get()) { @@ -146,10 +145,10 @@ public class MovementDescend extends Movement { if (ontoBlock.getBlock() == Blocks.FLOWING_WATER) { return; } - if (MovementHelper.canWalkThrough(destX, newY, destZ, ontoBlock)) { + if (MovementHelper.canWalkThrough(context, destX, newY, destZ, ontoBlock)) { continue; } - if (!MovementHelper.canWalkOn(destX, newY, destZ, ontoBlock)) { + if (!MovementHelper.canWalkOn(context, destX, newY, destZ, ontoBlock)) { return; } if (MovementHelper.isBottomSlab(ontoBlock)) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 9848d671..8e5dd910 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -23,7 +23,6 @@ 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.block.Block; import net.minecraft.block.state.IBlockState; @@ -57,16 +56,16 @@ public class MovementDiagonal extends Movement { } public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) { - Block fromDown = BlockStateInterface.get(x, y - 1, z).getBlock(); + Block fromDown = context.get(x, y - 1, z).getBlock(); if (fromDown == Blocks.LADDER || fromDown == Blocks.VINE) { return COST_INF; } - IBlockState destInto = BlockStateInterface.get(destX, y, destZ); - if (!MovementHelper.canWalkThrough(destX, y, destZ, destInto) || !MovementHelper.canWalkThrough(destX, y + 1, destZ)) { + IBlockState destInto = context.get(destX, y, destZ); + if (!MovementHelper.canWalkThrough(context, destX, y, destZ, destInto) || !MovementHelper.canWalkThrough(context, destX, y + 1, destZ)) { return COST_INF; } - IBlockState destWalkOn = BlockStateInterface.get(destX, y - 1, destZ); - if (!MovementHelper.canWalkOn(destX, y - 1, destZ, destWalkOn)) { + IBlockState destWalkOn = context.get(destX, y - 1, destZ); + if (!MovementHelper.canWalkOn(context, destX, y - 1, destZ, destWalkOn)) { return COST_INF; } double multiplier = WALK_ONE_BLOCK_COST; @@ -77,16 +76,16 @@ public class MovementDiagonal extends Movement { if (fromDown == Blocks.SOUL_SAND) { multiplier += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2; } - Block cuttingOver1 = BlockStateInterface.get(x, y - 1, destZ).getBlock(); + Block cuttingOver1 = context.get(x, y - 1, destZ).getBlock(); if (cuttingOver1 == Blocks.MAGMA || MovementHelper.isLava(cuttingOver1)) { return COST_INF; } - Block cuttingOver2 = BlockStateInterface.get(destX, y - 1, z).getBlock(); + Block cuttingOver2 = context.get(destX, y - 1, z).getBlock(); if (cuttingOver2 == Blocks.MAGMA || MovementHelper.isLava(cuttingOver2)) { return COST_INF; } - IBlockState pb0 = BlockStateInterface.get(x, y, destZ); - IBlockState pb2 = BlockStateInterface.get(destX, y, z); + IBlockState pb0 = context.get(x, y, destZ); + IBlockState pb2 = context.get(destX, y, z); double optionA = MovementHelper.getMiningDurationTicks(context, x, y, destZ, pb0, false); double optionB = MovementHelper.getMiningDurationTicks(context, destX, y, z, pb2, false); if (optionA != 0 && optionB != 0) { @@ -94,13 +93,13 @@ public class MovementDiagonal extends Movement { // so no need to check pb1 as well, might as well return early here return COST_INF; } - IBlockState pb1 = BlockStateInterface.get(x, y + 1, destZ); + IBlockState pb1 = context.get(x, y + 1, destZ); optionA += MovementHelper.getMiningDurationTicks(context, x, y + 1, destZ, pb1, true); if (optionA != 0 && optionB != 0) { // same deal, if pb1 makes optionA nonzero and option B already was nonzero, pb3 can't affect the result return COST_INF; } - IBlockState pb3 = BlockStateInterface.get(destX, y + 1, z); + IBlockState pb3 = context.get(destX, y + 1, z); if (optionA == 0 && ((MovementHelper.avoidWalkingInto(pb2.getBlock()) && pb2.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb3.getBlock()) && pb3.getBlock() != Blocks.WATER))) { // at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction return COST_INF; @@ -115,7 +114,7 @@ public class MovementDiagonal extends Movement { return COST_INF; } boolean water = false; - if (MovementHelper.isWater(BlockStateInterface.getBlock(x, y, z)) || MovementHelper.isWater(destInto.getBlock())) { + if (MovementHelper.isWater(context.getBlock(x, y, z)) || MovementHelper.isWater(destInto.getBlock())) { // 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 diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java index 0ac4f2b0..07c101e6 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java @@ -23,7 +23,6 @@ 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.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -48,10 +47,10 @@ public class MovementDownward extends Movement { } public static double cost(CalculationContext context, int x, int y, int z) { - if (!MovementHelper.canWalkOn(x, y - 2, z)) { + if (!MovementHelper.canWalkOn(context, x, y - 2, z)) { return COST_INF; } - IBlockState d = BlockStateInterface.get(x, y - 1, z); + IBlockState d = context.get(x, y - 1, z); Block td = d.getBlock(); boolean ladder = td == Blocks.LADDER || td == Blocks.VINE; if (ladder) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 73aace38..2b255d62 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -27,7 +27,9 @@ import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; -import baritone.utils.*; +import baritone.utils.BlockStateInterface; +import baritone.utils.Helper; +import baritone.utils.InputOverrideHandler; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -65,30 +67,30 @@ public class MovementParkour extends Movement { if (!Baritone.settings().allowParkour.get()) { return; } - IBlockState standingOn = BlockStateInterface.get(x, y - 1, z); + IBlockState standingOn = context.get(x, y - 1, z); if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || MovementHelper.isBottomSlab(standingOn)) { return; } int xDiff = dir.getXOffset(); int zDiff = dir.getZOffset(); - IBlockState adj = BlockStateInterface.get(x + xDiff, y - 1, z + zDiff); + IBlockState adj = context.get(x + xDiff, y - 1, z + zDiff); if (MovementHelper.avoidWalkingInto(adj.getBlock()) && adj.getBlock() != Blocks.WATER && adj.getBlock() != Blocks.FLOWING_WATER) { // magma sucks return; } - if (MovementHelper.canWalkOn(x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now) + if (MovementHelper.canWalkOn(context,x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now) return; } - if (!MovementHelper.fullyPassable(x + xDiff, y, z + zDiff)) { + if (!MovementHelper.fullyPassable(context,x + xDiff, y, z + zDiff)) { return; } - if (!MovementHelper.fullyPassable(x + xDiff, y + 1, z + zDiff)) { + if (!MovementHelper.fullyPassable(context,x + xDiff, y + 1, z + zDiff)) { return; } - if (!MovementHelper.fullyPassable(x + xDiff, y + 2, z + zDiff)) { + if (!MovementHelper.fullyPassable(context,x + xDiff, y + 2, z + zDiff)) { return; } - if (!MovementHelper.fullyPassable(x, y + 2, z)) { + if (!MovementHelper.fullyPassable(context,x, y + 2, z)) { return; } int maxJump; @@ -104,11 +106,11 @@ public class MovementParkour extends Movement { for (int i = 2; i <= maxJump; i++) { // TODO perhaps dest.up(3) doesn't need to be fullyPassable, just canWalkThrough, possibly? for (int y2 = 0; y2 < 4; y2++) { - if (!MovementHelper.fullyPassable(x + xDiff * i, y + y2, z + zDiff * i)) { + if (!MovementHelper.fullyPassable(context,x + xDiff * i, y + y2, z + zDiff * i)) { return; } } - if (MovementHelper.canWalkOn(x + xDiff * i, y - 1, z + zDiff * i)) { + if (MovementHelper.canWalkOn(context,x + xDiff * i, y - 1, z + zDiff * i)) { res.x = x + xDiff * i; res.y = y; res.z = z + zDiff * i; @@ -128,7 +130,7 @@ public class MovementParkour extends Movement { } int destX = x + 4 * xDiff; int destZ = z + 4 * zDiff; - IBlockState toPlace = BlockStateInterface.get(destX, y - 1, destZ); + IBlockState toPlace = context.get(destX, y - 1, destZ); if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { return; } @@ -141,7 +143,7 @@ public class MovementParkour extends Movement { if (againstX == x + xDiff * 3 && againstZ == z + zDiff * 3) { // we can't turn around that fast continue; } - if (MovementHelper.canPlaceAgainst(againstX, y - 1, againstZ)) { + if (MovementHelper.canPlaceAgainst(context,againstX, y - 1, againstZ)) { res.x = destX; res.y = y; res.z = destZ; @@ -259,4 +261,4 @@ public class MovementParkour extends Movement { } return state; } -} \ No newline at end of file +} diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 76006da5..846e4018 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -20,6 +20,7 @@ package baritone.pathing.movement.movements; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; +import baritone.api.utils.RotationUtils; import baritone.api.utils.VecUtils; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -27,7 +28,6 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; -import baritone.api.utils.RotationUtils; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -46,9 +46,9 @@ public class MovementPillar extends Movement { } public static double cost(CalculationContext context, int x, int y, int z) { - Block fromDown = BlockStateInterface.get(x, y, z).getBlock(); + Block fromDown = context.get(x, y, z).getBlock(); boolean ladder = fromDown instanceof BlockLadder || fromDown instanceof BlockVine; - IBlockState fromDownDown = BlockStateInterface.get(x, y - 1, z); + IBlockState fromDownDown = context.get(x, y - 1, z); if (!ladder) { if (fromDownDown.getBlock() instanceof BlockLadder || fromDownDown.getBlock() instanceof BlockVine) { return COST_INF; @@ -57,17 +57,17 @@ public class MovementPillar extends Movement { return COST_INF; // can't pillar up from a bottom slab onto a non ladder } } - if (fromDown instanceof BlockVine && !hasAgainst(x, y, z)) { + if (fromDown instanceof BlockVine && !hasAgainst(context, x, y, z)) { return COST_INF; } - IBlockState toBreak = BlockStateInterface.get(x, y + 2, z); + IBlockState toBreak = context.get(x, y + 2, z); Block toBreakBlock = toBreak.getBlock(); if (toBreakBlock instanceof BlockFenceGate) { return COST_INF; } Block srcUp = null; if (MovementHelper.isWater(toBreakBlock) && MovementHelper.isWater(fromDown)) { - srcUp = BlockStateInterface.get(x, y + 1, z).getBlock(); + srcUp = context.get(x, y + 1, z).getBlock(); if (MovementHelper.isWater(srcUp)) { return LADDER_UP_ONE_COST; } @@ -83,11 +83,11 @@ public class MovementPillar extends Movement { if (toBreakBlock instanceof BlockLadder || toBreakBlock instanceof BlockVine) { hardness = 0; // we won't actually need to break the ladder / vine because we're going to use it } else { - IBlockState check = BlockStateInterface.get(x, y + 3, z); + IBlockState check = context.get(x, y + 3, z); if (check.getBlock() instanceof BlockFalling) { // see MovementAscend's identical check for breaking a falling block above our head if (srcUp == null) { - srcUp = BlockStateInterface.get(x, y + 1, z).getBlock(); + srcUp = context.get(x, y + 1, z).getBlock(); } if (!(toBreakBlock instanceof BlockFalling) || !(srcUp instanceof BlockFalling)) { return COST_INF; @@ -112,24 +112,24 @@ public class MovementPillar extends Movement { } } - public static boolean hasAgainst(int x, int y, int z) { - return BlockStateInterface.get(x + 1, y, z).isBlockNormalCube() || - BlockStateInterface.get(x - 1, y, z).isBlockNormalCube() || - BlockStateInterface.get(x, y, z + 1).isBlockNormalCube() || - BlockStateInterface.get(x, y, z - 1).isBlockNormalCube(); + public static boolean hasAgainst(CalculationContext context, int x, int y, int z) { + return context.get(x + 1, y, z).isBlockNormalCube() || + context.get(x - 1, y, z).isBlockNormalCube() || + context.get(x, y, z + 1).isBlockNormalCube() || + context.get(x, y, z - 1).isBlockNormalCube(); } - public static BlockPos getAgainst(BlockPos vine) { - if (BlockStateInterface.get(vine.north()).isBlockNormalCube()) { + public static BlockPos getAgainst(CalculationContext context, BetterBlockPos vine) { + if (context.get(vine.north()).isBlockNormalCube()) { return vine.north(); } - if (BlockStateInterface.get(vine.south()).isBlockNormalCube()) { + if (context.get(vine.south()).isBlockNormalCube()) { return vine.south(); } - if (BlockStateInterface.get(vine.east()).isBlockNormalCube()) { + if (context.get(vine.east()).isBlockNormalCube()) { return vine.east(); } - if (BlockStateInterface.get(vine.west()).isBlockNormalCube()) { + if (context.get(vine.west()).isBlockNormalCube()) { return vine.west(); } return null; @@ -166,7 +166,7 @@ public class MovementPillar extends Movement { boolean blockIsThere = MovementHelper.canWalkOn(src) || ladder; if (ladder) { - BlockPos against = vine ? getAgainst(src) : src.offset(fromDown.getValue(BlockLadder.FACING).getOpposite()); + BlockPos against = vine ? getAgainst(new CalculationContext(), src) : src.offset(fromDown.getValue(BlockLadder.FACING).getOpposite()); if (against == null) { logDebug("Unable to climb vines"); return state.setStatus(MovementStatus.UNREACHABLE); @@ -175,7 +175,7 @@ public class MovementPillar extends Movement { if (playerFeet().equals(against.up()) || playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } - if (MovementHelper.isBottomSlab(src.down())) { + if (MovementHelper.isBottomSlab(BlockStateInterface.get(src.down()))) { state.setInput(InputOverrideHandler.Input.JUMP, true); } /* @@ -244,4 +244,4 @@ public class MovementPillar extends Movement { } return super.prepared(state); } -} \ No newline at end of file +} diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 0cf64a72..a4f32855 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -26,8 +26,6 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; -import baritone.api.utils.RayTraceUtils; -import baritone.api.utils.RotationUtils; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -61,11 +59,11 @@ public class MovementTraverse extends Movement { } public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) { - IBlockState pb0 = BlockStateInterface.get(destX, y + 1, destZ); - IBlockState pb1 = BlockStateInterface.get(destX, y, destZ); - IBlockState destOn = BlockStateInterface.get(destX, y - 1, destZ); - Block srcDown = BlockStateInterface.getBlock(x, y - 1, z); - if (MovementHelper.canWalkOn(destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge + IBlockState pb0 = context.get(destX, y + 1, destZ); + IBlockState pb1 = context.get(destX, y, destZ); + IBlockState destOn = context.get(destX, y - 1, destZ); + Block srcDown = context.getBlock(x, y - 1, z); + if (MovementHelper.canWalkOn(context, destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge double WC = WALK_ONE_BLOCK_COST; boolean water = false; if (MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock())) { @@ -123,7 +121,7 @@ public class MovementTraverse extends Movement { if (againstX == x && againstZ == z) { continue; } - if (MovementHelper.canPlaceAgainst(againstX, y - 1, againstZ)) { + if (MovementHelper.canPlaceAgainst(context, againstX, y - 1, againstZ)) { return WC + context.placeBlockCost() + hardness1 + hardness2; } } diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 241fafa1..0fb2abc0 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -97,6 +97,6 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } private void rescan(List known) { - knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64, world(), known); + knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64, baritone.getWorldProvider(), world(), known); } } \ No newline at end of file diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 27da4496..882456dd 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -22,15 +22,16 @@ import baritone.api.pathing.goals.*; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; +import baritone.api.utils.RotationUtils; import baritone.cache.CachedChunk; import baritone.cache.ChunkPacker; import baritone.cache.WorldProvider; import baritone.cache.WorldScanner; +import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; -import baritone.api.utils.RotationUtils; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; @@ -158,7 +159,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (Baritone.settings().legitMine.get()) { return; } - List locs = searchWorld(mining, ORE_LOCATIONS_COUNT, world(), already); + List locs = searchWorld(mining, ORE_LOCATIONS_COUNT, baritone.getWorldProvider(), world(), already); locs.addAll(droppedItemsScan(mining, world())); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); @@ -216,13 +217,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro /*public static List searchWorld(List mining, int max, World world) { }*/ - public static List searchWorld(List mining, int max, World world, List alreadyKnown) { + public static List searchWorld(List mining, int max, WorldProvider provider, World world, List alreadyKnown) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); //long b = System.currentTimeMillis(); for (Block m : mining) { if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(m)) { - locs.addAll(WorldProvider.INSTANCE.getCurrentWorld().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, 1)); + locs.addAll(provider.getCurrentWorld().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, 1)); } else { uninteresting.add(m); } @@ -279,7 +280,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } public static boolean plausibleToBreak(BlockPos pos) { - if (MovementHelper.avoidBreaking(pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(pos))) { + if (MovementHelper.avoidBreaking(new CalculationContext(), pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(pos))) { return false; } // bedrock above and below makes it implausible, otherwise we're good diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 7133fa12..d944484f 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -20,11 +20,12 @@ package baritone.utils; import baritone.Baritone; import baritone.cache.CachedRegion; import baritone.cache.WorldData; -import baritone.cache.WorldProvider; +import baritone.pathing.movement.CalculationContext; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; /** @@ -43,7 +44,12 @@ public class BlockStateInterface implements Helper { return get(pos.getX(), pos.getY(), pos.getZ()); } + public static IBlockState get(int x, int y, int z) { + return get(Helper.HELPER.world(), x, y, z); + } + + public static IBlockState get(World world, int x, int y, int z) { // Invalid vertical position if (y < 0 || y >= 256) { @@ -61,7 +67,7 @@ public class BlockStateInterface implements Helper { 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); + Chunk chunk = world.getChunk(x >> 4, z >> 4); if (chunk.isLoaded()) { prev = chunk; return chunk.getBlockState(x, y, z); @@ -71,11 +77,11 @@ public class BlockStateInterface implements Helper { // 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) { - WorldData world = WorldProvider.INSTANCE.getCurrentWorld(); - if (world == null) { + WorldData worldData = Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); + if (worldData == null) { return AIR; } - CachedRegion region = world.cache.getRegion(x >> 9, z >> 9); + CachedRegion region = worldData.cache.getRegion(x >> 9, z >> 9); if (region == null) { return AIR; } @@ -89,12 +95,12 @@ public class BlockStateInterface implements Helper { return type; } - public static boolean isLoaded(int x, int z) { + public static boolean isLoaded(CalculationContext context, int x, int z) { Chunk prevChunk = prev; if (prevChunk != null && prevChunk.x == x >> 4 && prevChunk.z == z >> 4) { return true; } - prevChunk = mc.world.getChunk(x >> 4, z >> 4); + prevChunk = context.world().getChunk(x >> 4, z >> 4); if (prevChunk.isLoaded()) { prev = prevChunk; return true; @@ -103,7 +109,7 @@ public class BlockStateInterface implements Helper { if (prevRegion != null && prevRegion.getX() == x >> 9 && prevRegion.getZ() == z >> 9) { return prevRegion.isCached(x & 511, z & 511); } - WorldData world = WorldProvider.INSTANCE.getCurrentWorld(); + WorldData world = Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); if (world == null) { return false; } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 2fbf05f7..2f6bef6c 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -29,7 +29,6 @@ import baritone.behavior.Behavior; import baritone.behavior.PathingBehavior; import baritone.cache.ChunkPacker; import baritone.cache.Waypoint; -import baritone.cache.WorldProvider; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -215,7 +214,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { Chunk chunk = cli.getLoadedChunk(x, z); if (chunk != null) { count++; - WorldProvider.INSTANCE.getCurrentWorld().getCachedWorld().queueForPacking(chunk); + baritone.getWorldProvider().getCurrentWorld().getCachedWorld().queueForPacking(chunk); } } } @@ -291,18 +290,18 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("reloadall")) { - WorldProvider.INSTANCE.getCurrentWorld().getCachedWorld().reloadAllFromDisk(); + baritone.getWorldProvider().getCurrentWorld().getCachedWorld().reloadAllFromDisk(); logDirect("ok"); return true; } if (msg.equals("saveall")) { - WorldProvider.INSTANCE.getCurrentWorld().getCachedWorld().save(); + baritone.getWorldProvider().getCurrentWorld().getCachedWorld().save(); logDirect("ok"); return true; } if (msg.startsWith("find")) { String blockType = msg.substring(4).trim(); - LinkedList locs = WorldProvider.INSTANCE.getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, 4); + LinkedList locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, 4); logDirect("Have " + locs.size() + " locations"); for (BlockPos pos : locs) { Block actually = BlockStateInterface.get(pos).getBlock(); @@ -354,7 +353,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase()); return true; } - Set waypoints = WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().getByTag(tag); + Set waypoints = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getByTag(tag); // might as well show them from oldest to newest List sorted = new ArrayList<>(waypoints); sorted.sort(Comparator.comparingLong(IWaypoint::getCreationTimestamp)); @@ -382,7 +381,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } name = parts[0]; } - WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, Waypoint.Tag.USER, pos)); + baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, Waypoint.Tag.USER, pos)); logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto " + name + "' to set goal, say 'list user' to list custom waypoints."); return true; } @@ -399,7 +398,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { Block block = ChunkPacker.stringToBlock(mining); //logDirect("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase()); if (block == null) { - waypoint = WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null); + waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null); if (waypoint == null) { logDirect("No locations for " + mining + " known, cancelling"); return true; @@ -409,7 +408,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } else { - waypoint = WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().getMostRecentByTag(tag); + waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(tag); if (waypoint == null) { logDirect("None saved for tag " + tag); return true; @@ -420,7 +419,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("spawn") || msg.equals("bed")) { - IWaypoint waypoint = WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().getMostRecentByTag(Waypoint.Tag.BED); + IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(Waypoint.Tag.BED); if (waypoint == null) { BlockPos spawnPoint = player().getBedLocation(); // for some reason the default spawnpoint is underground sometimes @@ -435,12 +434,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("sethome")) { - WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", Waypoint.Tag.HOME, playerFeet())); + baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", Waypoint.Tag.HOME, playerFeet())); logDirect("Saved. Say home to set goal."); return true; } if (msg.equals("home")) { - IWaypoint waypoint = WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().getMostRecentByTag(Waypoint.Tag.HOME); + IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(Waypoint.Tag.HOME); if (waypoint == null) { logDirect("home not saved"); } else { diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index 27aa2bc1..31b3fc10 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -66,6 +66,9 @@ public interface Helper { } default WorldClient world() { + if (!mc.isCallingFromMinecraftThread()) { + throw new IllegalStateException("h00000000"); + } return mc.world; } From 355443e440fe3ca291162130936f67b40f5b982a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 11 Nov 2018 12:48:53 -0800 Subject: [PATCH 293/305] forgot one --- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 93a8c35c..b1d2fc56 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -474,7 +474,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) { BlockPos pos = ((IGoalRenderPos) goal).getGoalPos(); - if (world().getChunk(pos) instanceof EmptyChunk) { + if (context.world().getChunk(pos) instanceof EmptyChunk) { logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance"); goal = new GoalXZ(pos.getX(), pos.getZ()); } From fad5a6deac3aaedde4a6423d5f0351b1f4644c8c Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Nov 2018 15:46:07 -0600 Subject: [PATCH 294/305] lol --- src/main/java/baritone/cache/WorldProvider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index d6f3aab1..ab690a23 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -89,7 +89,7 @@ public class WorldProvider implements IWorldProvider, Helper { } catch (IOException ignored) {} } System.out.println("Baritone world data dir: " + dir); - this.currentWorld = this.worldCache.computeIfAbsent(dir, d -> new WorldData(d, dimensionID)); + this.currentWorld = worldCache.computeIfAbsent(dir, d -> new WorldData(d, dimensionID)); } public final void closeWorld() { From 51243f09818bd9f5937cd5f0cec0fe85e968017f Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Nov 2018 16:22:00 -0600 Subject: [PATCH 295/305] Some comments --- .../java/baritone/cache/WorldProvider.java | 30 +++++++++++-------- .../java/baritone/event/GameEventHandler.java | 2 +- .../utils/accessor/IAnvilChunkLoader.java | 4 +++ .../utils/accessor/IChunkProviderServer.java | 3 ++ .../utils/pathing/BetterWorldBorder.java | 8 +++-- 5 files changed, 32 insertions(+), 15 deletions(-) diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index ab690a23..dd6e3561 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -22,7 +22,6 @@ import baritone.api.cache.IWorldProvider; 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; @@ -50,13 +49,20 @@ public class WorldProvider implements IWorldProvider, Helper { return this.currentWorld; } - public final void initWorld(WorldClient world) { - int dimensionID = world.provider.getDimensionType().getId(); - File directory; - File readme; + /** + * Called when a new world is initialized to discover the + * + * @param dimension The ID of the world's dimension + */ + public final void initWorld(int dimension) { + // Fight me @leijurv + File directory, readme; + IntegratedServer integratedServer = mc.getIntegratedServer(); + + // If there is an integrated server running (Aka Singleplayer) then do magic to find the world save file if (integratedServer != null) { - WorldServer localServerWorld = integratedServer.getWorld(dimensionID); + WorldServer localServerWorld = integratedServer.getWorld(dimension); IChunkProviderServer provider = (IChunkProviderServer) localServerWorld.getChunkProvider(); IAnvilChunkLoader loader = (IAnvilChunkLoader) provider.getChunkLoader(); directory = loader.getChunkSaveLocation(); @@ -69,27 +75,27 @@ public class WorldProvider implements IWorldProvider, Helper { directory = new File(directory, "baritone"); readme = directory; - - } else { - //remote + } else { // Otherwise, the server must be remote... directory = new File(Baritone.getDir(), mc.getCurrentServerData().serverIP); readme = Baritone.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(); + // We will actually store the world data in a subfolder: "DIM" + Path dir = new File(directory, "DIM" + dimension).toPath(); if (!Files.exists(dir)) { try { Files.createDirectories(dir); } catch (IOException ignored) {} } + System.out.println("Baritone world data dir: " + dir); - this.currentWorld = worldCache.computeIfAbsent(dir, d -> new WorldData(d, dimensionID)); + this.currentWorld = worldCache.computeIfAbsent(dir, d -> new WorldData(d, dimension)); } public final void closeWorld() { diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 2859731a..5646a1d4 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -103,7 +103,7 @@ public final class GameEventHandler implements IGameEventListener, Helper { if (event.getState() == EventState.POST) { cache.closeWorld(); if (event.getWorld() != null) { - cache.initWorld(event.getWorld()); + cache.initWorld(event.getWorld().provider.getDimensionType().getId()); } } diff --git a/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java index c243ae0e..8606bc3f 100644 --- a/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java +++ b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java @@ -17,9 +17,13 @@ package baritone.utils.accessor; +import baritone.cache.WorldProvider; + import java.io.File; /** + * @see WorldProvider + * * @author Brady * @since 8/4/2018 11:36 AM */ diff --git a/src/main/java/baritone/utils/accessor/IChunkProviderServer.java b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java index 78a471b2..176f05a3 100644 --- a/src/main/java/baritone/utils/accessor/IChunkProviderServer.java +++ b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java @@ -17,9 +17,12 @@ package baritone.utils.accessor; +import net.minecraft.world.WorldProvider; import net.minecraft.world.chunk.storage.IChunkLoader; /** + * @see WorldProvider + * * @author Brady * @since 8/4/2018 11:33 AM */ diff --git a/src/main/java/baritone/utils/pathing/BetterWorldBorder.java b/src/main/java/baritone/utils/pathing/BetterWorldBorder.java index 8a5c79d5..9d8f3ef8 100644 --- a/src/main/java/baritone/utils/pathing/BetterWorldBorder.java +++ b/src/main/java/baritone/utils/pathing/BetterWorldBorder.java @@ -17,10 +17,14 @@ package baritone.utils.pathing; -import baritone.utils.Helper; import net.minecraft.world.border.WorldBorder; -public class BetterWorldBorder implements Helper { +/** + * Essentially, a "rule" for the path finder, prevents proposed movements from attempting to venture + * into the world border, and prevents actual movements from placing blocks in the world border. + */ +public class BetterWorldBorder { + private final double minX; private final double maxX; private final double minZ; From e81d0a0b1b24265b18fdb0f773f76b7767313cdf Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Nov 2018 17:12:18 -0600 Subject: [PATCH 296/305] Small brain --- .../baritone/utils/pathing/PathingBlockType.java | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/src/main/java/baritone/utils/pathing/PathingBlockType.java b/src/main/java/baritone/utils/pathing/PathingBlockType.java index 80c92dcb..35e21fc3 100644 --- a/src/main/java/baritone/utils/pathing/PathingBlockType.java +++ b/src/main/java/baritone/utils/pathing/PathingBlockType.java @@ -42,18 +42,6 @@ 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; - } - } + return b1 ? b2 ? SOLID : AVOID : b2 ? WATER : AIR; } } From 903b1b16a4aed39889a5833bcb3c36bce852f487 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Nov 2018 17:45:01 -0600 Subject: [PATCH 297/305] static --- src/main/java/baritone/Baritone.java | 53 ++++++++++++---------------- 1 file changed, 22 insertions(+), 31 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 6df47147..f4546012 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -59,15 +59,26 @@ public enum Baritone implements IBaritone { */ INSTANCE; + private static ThreadPoolExecutor threadPool; + private static File dir; + + static { + threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); + + dir = new File(Minecraft.getMinecraft().gameDir, "baritone"); + if (!Files.exists(dir.toPath())) { + try { + Files.createDirectories(dir.toPath()); + } catch (IOException ignored) {} + } + } + /** * Whether or not {@link Baritone#init()} has been called yet */ private boolean initialized; private GameEventHandler gameEventHandler; - private Settings settings; - private File dir; - private List behaviors; private PathingBehavior pathingBehavior; @@ -84,8 +95,6 @@ public enum Baritone implements IBaritone { private WorldProvider worldProvider; - private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); - Baritone() { this.gameEventHandler = new GameEventHandler(this); } @@ -95,10 +104,6 @@ public enum Baritone implements IBaritone { return; } - // Acquire the "singleton" instance of the settings directly from the API - // We might want to change this... - this.settings = BaritoneAPI.getSettings(); - this.behaviors = new ArrayList<>(); { // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist @@ -122,12 +127,6 @@ public enum Baritone implements IBaritone { if (BaritoneAutoTest.ENABLE_AUTO_TEST) { registerEventListener(BaritoneAutoTest.INSTANCE); } - this.dir = new File(Minecraft.getMinecraft().gameDir, "baritone"); - if (!Files.exists(dir.toPath())) { - try { - Files.createDirectories(dir.toPath()); - } catch (IOException ignored) {} - } this.initialized = true; } @@ -136,10 +135,6 @@ public enum Baritone implements IBaritone { return pathingControlManager; } - public boolean isInitialized() { - return this.initialized; - } - public IGameEventListener getGameEventHandler() { return this.gameEventHandler; } @@ -152,22 +147,18 @@ public enum Baritone implements IBaritone { return this.behaviors; } - public static Executor getExecutor() { - return threadPool; - } - public void registerBehavior(Behavior behavior) { this.behaviors.add(behavior); this.registerEventListener(behavior); } @Override - public CustomGoalProcess getCustomGoalProcess() { + public CustomGoalProcess getCustomGoalProcess() { // Iffy return customGoalProcess; } @Override - public GetToBlockProcess getGetToBlockProcess() { // very very high iq + public GetToBlockProcess getGetToBlockProcess() { // Iffy return getToBlockProcess; } @@ -211,15 +202,15 @@ public enum Baritone implements IBaritone { this.gameEventHandler.registerEventListener(listener); } - public Settings getSettings() { - return this.settings; - } - public static Settings settings() { - return Baritone.INSTANCE.settings; // yolo + return BaritoneAPI.getSettings(); } public static File getDir() { - return Baritone.INSTANCE.dir; // should be static I guess + return dir; + } + + public static Executor getExecutor() { + return threadPool; } } From e3cb16472387c9f50c6857014f79920abfdf34a0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 11 Nov 2018 17:36:54 -0800 Subject: [PATCH 298/305] fix blockstateinterface --- .../java/baritone/event/GameEventHandler.java | 3 -- .../pathing/calc/AStarPathFinder.java | 4 +- .../pathing/movement/CalculationContext.java | 13 ++++- .../baritone/utils/BlockStateInterface.java | 52 ++++++++----------- 4 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 5646a1d4..084b5562 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -22,7 +22,6 @@ import baritone.api.event.events.*; import baritone.api.event.events.type.EventState; import baritone.api.event.listener.IGameEventListener; import baritone.cache.WorldProvider; -import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import net.minecraft.world.chunk.Chunk; @@ -98,8 +97,6 @@ public final class GameEventHandler implements IGameEventListener, Helper { public final void onWorldEvent(WorldEvent event) { WorldProvider cache = baritone.getWorldProvider(); - BlockStateInterface.clearCachedChunk(); - if (event.getState() == EventState.POST) { cache.closeWorld(); if (event.getWorld() != null) { diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index 9d69959d..b9babdda 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -25,7 +25,6 @@ import baritone.api.utils.BetterBlockPos; import baritone.pathing.calc.openset.BinaryHeapOpenSet; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Moves; -import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.pathing.BetterWorldBorder; import baritone.utils.pathing.MutableMoveResult; @@ -66,7 +65,6 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel MutableMoveResult res = new MutableMoveResult(); HashSet favored = favoredPositions.orElse(null); BetterWorldBorder worldBorder = new BetterWorldBorder(calcContext.world().getWorldBorder()); - BlockStateInterface.clearCachedChunk(); long startTime = System.nanoTime() / 1000000L; boolean slowPath = Baritone.settings().slowPath.get(); if (slowPath) { @@ -100,7 +98,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel for (Moves moves : Moves.values()) { int newX = currentNode.x + moves.xOffset; int newZ = currentNode.z + moves.zOffset; - if ((newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) && !BlockStateInterface.isLoaded(calcContext, newX, newZ)) { + if ((newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) && !calcContext.isLoaded(newX, newZ)) { // only need to check if the destination is a loaded chunk if it's in a different chunk than the start of the movement if (!moves.dynamicXZ) { // only increment the counter if the movement would have gone out of bounds guaranteed numEmptyChunk++; diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 5f367f00..f2ac133d 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -43,6 +43,7 @@ public class CalculationContext { private final EntityPlayerSP player; private final World world; + private final BlockStateInterface bsi; private final ToolSet toolSet; private final boolean hasWaterBucket; private final boolean hasThrowaway; @@ -58,6 +59,8 @@ public class CalculationContext { public CalculationContext() { this.player = Helper.HELPER.player(); this.world = Helper.HELPER.world(); + this.bsi = new BlockStateInterface(world, Baritone.INSTANCE.getWorldProvider().getCurrentWorld()); // TODO TODO TODO + // new CalculationContext() needs to happen, can't add an argument (i'll beat you), can we get the world provider from currentlyTicking? this.toolSet = new ToolSet(player); this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(false); this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether(); @@ -80,7 +83,15 @@ public class CalculationContext { } public IBlockState get(int x, int y, int z) { - return BlockStateInterface.get(world, x, y, z); + return bsi.get0(x, y, z); // laughs maniacally + } + + public boolean isLoaded(int x, int z) { + return bsi.isLoaded(x, z); + } + + public BlockStateInterface bsi() { + return bsi; } public IBlockState get(BlockPos pos) { diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index d944484f..b3ee52a4 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -20,7 +20,6 @@ package baritone.utils; import baritone.Baritone; import baritone.cache.CachedRegion; import baritone.cache.WorldData; -import baritone.pathing.movement.CalculationContext; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -35,21 +34,31 @@ import net.minecraft.world.chunk.Chunk; */ public class BlockStateInterface implements Helper { - private static Chunk prev = null; - private static CachedRegion prevCached = null; + private final World world; + private final WorldData worldData; + + + private Chunk prev = null; + private CachedRegion prevCached = null; private static final IBlockState AIR = Blocks.AIR.getDefaultState(); + public BlockStateInterface(World world, WorldData worldData) { + this.worldData = worldData; + this.world = world; + } + + public static Block getBlock(BlockPos pos) { // won't be called from the pathing thread because the pathing thread doesn't make a single blockpos pog + return get(pos).getBlock(); + } + public static IBlockState get(BlockPos pos) { - return get(pos.getX(), pos.getY(), pos.getZ()); + // this is the version thats called from updatestate and stuff, not from cost calculation + // doesn't need to be fast or cached actually + return Helper.HELPER.world().getBlockState(pos); } - - public static IBlockState get(int x, int y, int z) { - return get(Helper.HELPER.world(), x, y, z); - } - - public static IBlockState get(World world, int x, int y, int z) { + public IBlockState get0(int x, int y, int z) { // Invalid vertical position if (y < 0 || y >= 256) { @@ -77,7 +86,6 @@ public class BlockStateInterface implements Helper { // 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) { - WorldData worldData = Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); if (worldData == null) { return AIR; } @@ -95,12 +103,12 @@ public class BlockStateInterface implements Helper { return type; } - public static boolean isLoaded(CalculationContext context, int x, int z) { + public boolean isLoaded(int x, int z) { Chunk prevChunk = prev; if (prevChunk != null && prevChunk.x == x >> 4 && prevChunk.z == z >> 4) { return true; } - prevChunk = context.world().getChunk(x >> 4, z >> 4); + prevChunk = world.getChunk(x >> 4, z >> 4); if (prevChunk.isLoaded()) { prev = prevChunk; return true; @@ -109,28 +117,14 @@ public class BlockStateInterface implements Helper { if (prevRegion != null && prevRegion.getX() == x >> 9 && prevRegion.getZ() == z >> 9) { return prevRegion.isCached(x & 511, z & 511); } - WorldData world = Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); - if (world == null) { + if (worldData == null) { return false; } - prevRegion = world.cache.getRegion(x >> 9, z >> 9); + prevRegion = worldData.cache.getRegion(x >> 9, z >> 9); if (prevRegion == null) { return false; } prevCached = prevRegion; return prevRegion.isCached(x & 511, z & 511); } - - public static void clearCachedChunk() { - prev = null; - prevCached = null; - } - - public static Block getBlock(BlockPos pos) { - return get(pos).getBlock(); - } - - public static Block getBlock(int x, int y, int z) { - return get(x, y, z).getBlock(); - } } From 66769365d0a523227c16d3ae26c74c47a35eaea4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 11 Nov 2018 17:59:13 -0800 Subject: [PATCH 299/305] much better --- src/api/java/baritone/api/pathing/goals/GoalRunAway.java | 2 +- src/main/java/baritone/process/MineProcess.java | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index d01f6eee..e55ba561 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -75,7 +75,7 @@ public class GoalRunAway implements Goal { } min = -min; if (maintainY.isPresent()) { - min += GoalYLevel.calculate(maintainY.get(), y); + min = min * 0.6 + GoalYLevel.calculate(maintainY.get(), y); } return min; } diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 882456dd..c3a61426 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -131,13 +131,14 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro // only in non-Xray mode (aka legit mode) do we do this int y = Baritone.settings().legitMineYLevel.get(); if (branchPoint == null) { - if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) { + /*if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) { // cool, path is over and we are at desired y branchPoint = playerFeet(); branchPointRunaway = null; } else { return new GoalYLevel(y); - } + }*/ + branchPoint = playerFeet(); } // TODO shaft mode, mine 1x1 shafts to either side // TODO also, see if the GoalRunAway with maintain Y at 11 works even from the surface From 0ce4107d569d996136b3ceef2cb1108e9a150d03 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 11 Nov 2018 18:23:18 -0800 Subject: [PATCH 300/305] "fix" it --- .../pathing/movement/CalculationContext.java | 16 +++++++++++----- .../java/baritone/utils/BlockStateInterface.java | 7 ++++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index f2ac133d..e419bb72 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -19,6 +19,7 @@ package baritone.pathing.movement; import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; +import baritone.cache.WorldData; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.ToolSet; @@ -43,6 +44,7 @@ public class CalculationContext { private final EntityPlayerSP player; private final World world; + private final WorldData worldData; private final BlockStateInterface bsi; private final ToolSet toolSet; private final boolean hasWaterBucket; @@ -59,7 +61,8 @@ public class CalculationContext { public CalculationContext() { this.player = Helper.HELPER.player(); this.world = Helper.HELPER.world(); - this.bsi = new BlockStateInterface(world, Baritone.INSTANCE.getWorldProvider().getCurrentWorld()); // TODO TODO TODO + this.worldData = Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); + this.bsi = new BlockStateInterface(world, worldData); // TODO TODO TODO // new CalculationContext() needs to happen, can't add an argument (i'll beat you), can we get the world provider from currentlyTicking? this.toolSet = new ToolSet(player); this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(false); @@ -90,10 +93,6 @@ public class CalculationContext { return bsi.isLoaded(x, z); } - public BlockStateInterface bsi() { - return bsi; - } - public IBlockState get(BlockPos pos) { return get(pos.getX(), pos.getY(), pos.getZ()); } @@ -132,6 +131,13 @@ public class CalculationContext { return player; } + public BlockStateInterface bsi() { + return bsi; + } + + public WorldData worldData() { + return worldData; + } public ToolSet getToolSet() { return toolSet; diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index b3ee52a4..547e40c3 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -20,6 +20,7 @@ package baritone.utils; import baritone.Baritone; import baritone.cache.CachedRegion; import baritone.cache.WorldData; +import baritone.pathing.movement.CalculationContext; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -53,9 +54,9 @@ public class BlockStateInterface implements Helper { } public static IBlockState get(BlockPos pos) { - // this is the version thats called from updatestate and stuff, not from cost calculation - // doesn't need to be fast or cached actually - return Helper.HELPER.world().getBlockState(pos); + return new CalculationContext().get(pos); // immense iq + // can't just do world().get because that doesn't work for out of bounds + // and toBreak and stuff fails when the movement is instantiated out of load range but it's not able to BlockStateInterface.get what it's going to walk on } public IBlockState get0(int x, int y, int z) { From 7fecd1a5dd70cc9ea1cf6bab14d6f227d2a78580 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 12 Nov 2018 14:43:39 -0800 Subject: [PATCH 301/305] tweak --- src/api/java/baritone/api/pathing/goals/GoalRunAway.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index e55ba561..bbbe1595 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -75,7 +75,7 @@ public class GoalRunAway implements Goal { } min = -min; if (maintainY.isPresent()) { - min = min * 0.6 + GoalYLevel.calculate(maintainY.get(), y); + min = min * 0.5 + GoalYLevel.calculate(maintainY.get(), y); } return min; } From 83f14b10bb7f122e892ddd60a18356c9af59b49a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 12 Nov 2018 15:45:35 -0800 Subject: [PATCH 302/305] whoa codacy suggested something actually helpful --- src/main/java/baritone/pathing/movement/Movement.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index f11e1955..e492a795 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -56,8 +56,6 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { */ protected final BetterBlockPos positionToPlace; - private boolean didBreakLastTick; - private Double cost; public List toBreakCached = null; From e81b6d4d96e498a5db60820dc332a689a2788cdf Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 12 Nov 2018 16:39:58 -0800 Subject: [PATCH 303/305] fought --- src/main/java/baritone/cache/WorldProvider.java | 4 ++-- src/main/java/baritone/process/FollowProcess.java | 5 +---- src/main/java/baritone/utils/InputOverrideHandler.java | 8 ++++---- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index dd6e3561..1bd27a98 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -55,8 +55,8 @@ public class WorldProvider implements IWorldProvider, Helper { * @param dimension The ID of the world's dimension */ public final void initWorld(int dimension) { - // Fight me @leijurv - File directory, readme; + File directory; + File readme; IntegratedServer integratedServer = mc.getIntegratedServer(); diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 41a59808..959e3a48 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -79,10 +79,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo if (entity.equals(player())) { return false; } - if (!world().loadedEntityList.contains(entity) && !world().playerEntities.contains(entity)) { - return false; - } - return true; + return world().loadedEntityList.contains(entity) || world().playerEntities.contains(entity); } private void scanWorld() { diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 9c3eed7f..fc902cf1 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -37,15 +37,15 @@ import java.util.Map; */ public final class InputOverrideHandler extends Behavior implements Helper { - public InputOverrideHandler(Baritone baritone) { - super(baritone); - } - /** * Maps inputs to whether or not we are forcing their state down. */ private final Map inputForceStateMap = new HashMap<>(); + public InputOverrideHandler(Baritone baritone) { + super(baritone); + } + /** * Returns whether or not we are forcing down the specified {@link KeyBinding}. * From 1ab3e61984dc8ee3886629cbc2624fba922d3ff3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 12 Nov 2018 21:01:40 -0800 Subject: [PATCH 304/305] reformatted --- .../movement/movements/MovementParkour.java | 16 ++++++++-------- .../utils/accessor/IAnvilChunkLoader.java | 3 +-- .../utils/accessor/IChunkProviderServer.java | 3 +-- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 2b255d62..0b0e0e75 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -77,20 +77,20 @@ public class MovementParkour extends Movement { if (MovementHelper.avoidWalkingInto(adj.getBlock()) && adj.getBlock() != Blocks.WATER && adj.getBlock() != Blocks.FLOWING_WATER) { // magma sucks return; } - if (MovementHelper.canWalkOn(context,x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now) + if (MovementHelper.canWalkOn(context, x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now) return; } - if (!MovementHelper.fullyPassable(context,x + xDiff, y, z + zDiff)) { + if (!MovementHelper.fullyPassable(context, x + xDiff, y, z + zDiff)) { return; } - if (!MovementHelper.fullyPassable(context,x + xDiff, y + 1, z + zDiff)) { + if (!MovementHelper.fullyPassable(context, x + xDiff, y + 1, z + zDiff)) { return; } - if (!MovementHelper.fullyPassable(context,x + xDiff, y + 2, z + zDiff)) { + if (!MovementHelper.fullyPassable(context, x + xDiff, y + 2, z + zDiff)) { return; } - if (!MovementHelper.fullyPassable(context,x, y + 2, z)) { + if (!MovementHelper.fullyPassable(context, x, y + 2, z)) { return; } int maxJump; @@ -106,11 +106,11 @@ public class MovementParkour extends Movement { for (int i = 2; i <= maxJump; i++) { // TODO perhaps dest.up(3) doesn't need to be fullyPassable, just canWalkThrough, possibly? for (int y2 = 0; y2 < 4; y2++) { - if (!MovementHelper.fullyPassable(context,x + xDiff * i, y + y2, z + zDiff * i)) { + if (!MovementHelper.fullyPassable(context, x + xDiff * i, y + y2, z + zDiff * i)) { return; } } - if (MovementHelper.canWalkOn(context,x + xDiff * i, y - 1, z + zDiff * i)) { + if (MovementHelper.canWalkOn(context, x + xDiff * i, y - 1, z + zDiff * i)) { res.x = x + xDiff * i; res.y = y; res.z = z + zDiff * i; @@ -143,7 +143,7 @@ public class MovementParkour extends Movement { if (againstX == x + xDiff * 3 && againstZ == z + zDiff * 3) { // we can't turn around that fast continue; } - if (MovementHelper.canPlaceAgainst(context,againstX, y - 1, againstZ)) { + if (MovementHelper.canPlaceAgainst(context, againstX, y - 1, againstZ)) { res.x = destX; res.y = y; res.z = destZ; diff --git a/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java index 8606bc3f..73936deb 100644 --- a/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java +++ b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java @@ -22,9 +22,8 @@ import baritone.cache.WorldProvider; import java.io.File; /** - * @see WorldProvider - * * @author Brady + * @see WorldProvider * @since 8/4/2018 11:36 AM */ public interface IAnvilChunkLoader { diff --git a/src/main/java/baritone/utils/accessor/IChunkProviderServer.java b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java index 176f05a3..b5512a1a 100644 --- a/src/main/java/baritone/utils/accessor/IChunkProviderServer.java +++ b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java @@ -21,9 +21,8 @@ import net.minecraft.world.WorldProvider; import net.minecraft.world.chunk.storage.IChunkLoader; /** - * @see WorldProvider - * * @author Brady + * @see WorldProvider * @since 8/4/2018 11:33 AM */ public interface IChunkProviderServer { From 72058c792a0f7982765c59e741cbd43c78d14554 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 13 Nov 2018 12:20:27 -0800 Subject: [PATCH 305/305] fix toxic clouds in legit mine --- src/api/java/baritone/api/pathing/goals/GoalRunAway.java | 2 +- .../baritone/pathing/movement/movements/MovementFall.java | 7 ++++--- .../pathing/movement/movements/MovementPillar.java | 6 ++++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index bbbe1595..44c5fa80 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -75,7 +75,7 @@ public class GoalRunAway implements Goal { } min = -min; if (maintainY.isPresent()) { - min = min * 0.5 + GoalYLevel.calculate(maintainY.get(), y); + min = min * 0.6 + GoalYLevel.calculate(maintainY.get(), y) * 1.5; } return min; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index ba57eeac..26018d3b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -64,16 +64,17 @@ public class MovementFall extends Movement { } BlockPos playerFeet = playerFeet(); + Rotation toDest = RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.getBlockPosCenter(dest)); Rotation targetRotation = null; if (!MovementHelper.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()) { return state.setStatus(MovementStatus.UNREACHABLE); } - if (player().posY - dest.getY() < playerController().getBlockReachDistance()) { + if (player().posY - dest.getY() < playerController().getBlockReachDistance() && !player().onGround) { player().inventory.currentItem = player().inventory.getSlotFor(STACK_BUCKET_WATER); - targetRotation = new Rotation(player().rotationYaw, 90.0F); + targetRotation = new Rotation(toDest.getYaw(), 90.0F); RayTraceResult trace = mc.objectMouseOver; if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK && player().rotationPitch > 89.0F) { @@ -84,7 +85,7 @@ public class MovementFall extends Movement { if (targetRotation != null) { state.setTarget(new MovementTarget(targetRotation, true)); } else { - state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.getBlockPosCenter(dest)), false)); + state.setTarget(new MovementTarget(toDest, false)); } if (playerFeet.equals(dest) && (player().posY - playerFeet.getY() < 0.094 || MovementHelper.isWater(dest))) { // 0.094 because lilypads if (MovementHelper.isWater(dest)) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 846e4018..f961b043 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -192,8 +192,7 @@ public class MovementPillar extends Movement { return state.setStatus(MovementStatus.UNREACHABLE); } - // If our Y coordinate is above our goal, stop jumping - state.setInput(InputOverrideHandler.Input.JUMP, player().posY < dest.getY()); + state.setInput(InputOverrideHandler.Input.SNEAK, player().posY > dest.getY()); // delay placement by 1 tick for ncp compatibility // since (lower down) we only right click once player.isSneaking, and that happens the tick after we request to sneak @@ -209,6 +208,9 @@ public class MovementPillar extends Movement { // revise our target to both yaw and pitch if we're going to be moving forward state.setTarget(new MovementState.MovementTarget(rotation, true)); + } else { + // If our Y coordinate is above our goal, stop jumping + state.setInput(InputOverrideHandler.Input.JUMP, player().posY < dest.getY()); }