From 1736f2ffc7c92eff5cd117ee7a9c0cb78207dce1 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Fri, 23 Dec 2022 16:34:49 -0700 Subject: [PATCH 001/111] replace the world scanner with a 500x faster one --- .../baritone/launch/mixins/MixinBitArray.java | 10 + .../mixins/MixinBlockStateContainer.java | 10 + src/main/java/baritone/BaritoneProvider.java | 3 +- .../baritone/cache/FasterWorldScanner.java | 270 ++++++++++++++++++ .../command/defaults/MineCommand.java | 3 +- .../command/defaults/PathCommand.java | 3 +- .../command/defaults/RepackCommand.java | 3 +- .../java/baritone/process/FarmProcess.java | 3 +- .../java/baritone/process/MineProcess.java | 3 +- .../baritone/utils/accessor/IBitArray.java | 4 + .../utils/accessor/IBlockStateContainer.java | 6 + 11 files changed, 312 insertions(+), 6 deletions(-) create mode 100644 src/main/java/baritone/cache/FasterWorldScanner.java diff --git a/src/launch/java/baritone/launch/mixins/MixinBitArray.java b/src/launch/java/baritone/launch/mixins/MixinBitArray.java index bece3e3bf..bf7d9e535 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBitArray.java +++ b/src/launch/java/baritone/launch/mixins/MixinBitArray.java @@ -64,4 +64,14 @@ public int[] toArray() { return out; } + + @Override + public long getMaxEntryValue() { + return maxEntryValue; + } + + @Override + public int getBitsPerEntry() { + return bitsPerEntry; + } } diff --git a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java index f1cc28b9f..566c3cf8b 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java @@ -35,6 +35,16 @@ public abstract class MixinBlockStateContainer implements IBlockStateContainer { @Shadow protected IBlockStatePalette palette; + @Override + public IBlockStatePalette getPalette() { + return palette; + } + + @Override + public BitArray getStorage() { + return storage; + } + @Override public IBlockState getAtPalette(int index) { return palette.getBlockState(index); diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index d5457cf85..c49c02e10 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -22,6 +22,7 @@ import baritone.api.cache.IWorldScanner; import baritone.api.command.ICommandSystem; import baritone.api.schematic.ISchematicSystem; +import baritone.cache.FasterWorldScanner; import baritone.cache.WorldScanner; import baritone.command.CommandSystem; import baritone.command.ExampleBaritoneControl; @@ -59,7 +60,7 @@ public List getAllBaritones() { @Override public IWorldScanner getWorldScanner() { - return WorldScanner.INSTANCE; + return FasterWorldScanner.INSTANCE; } @Override diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java new file mode 100644 index 000000000..f1829f9f0 --- /dev/null +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -0,0 +1,270 @@ +/* + * 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.cache; + +import baritone.api.cache.ICachedWorld; +import baritone.api.cache.IWorldScanner; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.BlockOptionalMetaLookup; +import baritone.api.utils.IPlayerContext; +import baritone.utils.accessor.IBitArray; +import baritone.utils.accessor.IBlockStateContainer; +import io.netty.buffer.Unpooled; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.BitArray; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.chunk.*; +import net.minecraft.world.chunk.storage.ExtendedBlockStorage; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; +import java.util.function.IntConsumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public enum FasterWorldScanner implements IWorldScanner { + INSTANCE; + @Override + public List scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLookup filter, int max, int yLevelThreshold, int maxSearchRadius) { + return new WorldScannerContext(filter, ctx).scanAroundPlayerRange(maxSearchRadius); + } + + @Override + public List scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold) { + return new WorldScannerContext(filter, ctx).scanAroundPlayerUntilCount(max); + } + + @Override + public int repack(IPlayerContext ctx) { + return this.repack(ctx, 40); + } + + @Override + public int repack(IPlayerContext ctx, int range) { + IChunkProvider chunkProvider = ctx.world().getChunkProvider(); + ICachedWorld cachedWorld = ctx.worldData().getCachedWorld(); + + BetterBlockPos playerPos = ctx.playerFeet(); + + int playerChunkX = playerPos.getX() >> 4; + int playerChunkZ = playerPos.getZ() >> 4; + + int minX = playerChunkX - range; + int minZ = playerChunkZ - range; + int maxX = playerChunkX + range; + int maxZ = playerChunkZ + range; + + int queued = 0; + for (int x = minX; x <= maxX; x++) { + for (int z = minZ; z <= maxZ; z++) { + Chunk chunk = chunkProvider.getLoadedChunk(x, z); + + if (chunk != null && !chunk.isEmpty()) { + queued++; + cachedWorld.queueForPacking(chunk); + } + } + } + + return queued; + } + + // for porting, see {@link https://github.com/JsMacros/JsMacros/blob/backport-1.12.2/common/src/main/java/xyz/wagyourtail/jsmacros/client/api/classes/worldscanner/WorldScanner.java} + public static class WorldScannerContext { + private final BlockOptionalMetaLookup filter; + private final IPlayerContext ctx; + private final Map cachedFilter = new ConcurrentHashMap<>(); + + public WorldScannerContext(BlockOptionalMetaLookup filter, IPlayerContext ctx) { + this.filter = filter; + this.ctx = ctx; + } + + public List getChunkRange(int centerX, int centerZ, int chunkrange) { + List chunks = new ArrayList<>(); + for (int x = centerX - chunkrange; x <= centerX + chunkrange; x++) { + for (int z = centerZ - chunkrange; z <= centerZ + chunkrange; z++) { + chunks.add(new ChunkPos(x, z)); + } + } + return chunks; + } + + public List scanAroundPlayerRange(int range) { + return scanAroundPlayer(range, -1); + } + + public List scanAroundPlayerUntilCount(int count) { + return scanAroundPlayer(32, count); + } + + public List scanAroundPlayer(int range, int maxCount) { + assert ctx.player() != null; + return scanChunkRange(ctx.playerFeet().x >> 4, ctx.playerFeet().z >> 4, range, maxCount); + } + + public List scanChunkRange(int centerX, int centerZ, int chunkRange, int maxBlocks) { + assert ctx.world() != null; + if (chunkRange < 0) { + throw new IllegalArgumentException("chunkRange must be >= 0"); + } + return scanChunksInternal(getChunkRange(centerX, centerZ, chunkRange), maxBlocks); + } + + private List scanChunksInternal(List chunkPositions, int maxBlocks) { + assert ctx.world() != null; + return chunkPositions.parallelStream().flatMap(this::scanChunkInternal).limit(maxBlocks <= 0 ? Long.MAX_VALUE : maxBlocks).collect(Collectors.toList()); + } + private Stream scanChunkInternal(ChunkPos pos) { + IChunkProvider chunkProvider = ctx.world().getChunkProvider(); + // if chunk is not loaded, return empty stream + if (!chunkProvider.isChunkGeneratedAt(pos.x, pos.z)) { + return Stream.empty(); + } + + long chunkX = (long) pos.x << 4; + long chunkZ = (long) pos.z << 4; + + List blocks = new ArrayList<>(); + + streamChunkSections(chunkProvider.getLoadedChunk(pos.x, pos.z), (section, isInFilter) -> { + int yOffset = section.getYLocation(); + BitArray array = (BitArray) ((IBlockStateContainer) section.getData()).getStorage(); + forEach(array, isInFilter, place -> blocks.add(new BlockPos( + chunkX + ((place & 255) & 15), + yOffset + (place >> 8), + chunkZ + ((place & 255) >> 4) + ))); + }); + return blocks.stream(); + } + + private void streamChunkSections(Chunk chunk, BiConsumer consumer) { + for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) { + if (section == null || section.isEmpty()) { + continue; + } + + BlockStateContainer sectionContainer = section.getData(); + //this won't work if the PaletteStorage is of the type EmptyPaletteStorage + if (((IBlockStateContainer) sectionContainer).getStorage() == null) { + continue; + } + + boolean[] isInFilter = getIncludedFilterIndices(((IBlockStateContainer) sectionContainer).getPalette()); + if (isInFilter.length == 0) { + continue; + } + consumer.accept(section, isInFilter); + } + } + + private boolean getFilterResult(IBlockState state) { + Boolean v; + return (v = cachedFilter.get(state)) == null ? addCachedState(state) : v; + } + + private boolean addCachedState(IBlockState state) { + boolean isInFilter = false; + + if (filter != null) { + isInFilter = filter.has(state); + } + + cachedFilter.put(state, isInFilter); + return isInFilter; + } + + private boolean[] getIncludedFilterIndices(IBlockStatePalette palette) { + boolean commonBlockFound = false; + Int2ObjectOpenHashMap paletteMap = getPalette(palette); + int size = paletteMap.size(); + + boolean[] isInFilter = new boolean[size]; + + for (int i = 0; i < size; i++) { + IBlockState state = paletteMap.get(i); + if (getFilterResult(state)) { + isInFilter[i] = true; + commonBlockFound = true; + } else { + isInFilter[i] = false; + } + } + + if (!commonBlockFound) { + return new boolean[0]; + } + return isInFilter; + } + + private static void forEach(BitArray array, boolean[] isInFilter, IntConsumer action) { + int counter = 0; + long[] storage = array.getBackingLongArray(); + int arraySize = array.size(); + int elementBits = ((IBitArray) array).getBitsPerEntry(); + long maxValue = ((IBitArray) array).getMaxEntryValue(); + int storageLength = storage.length; + + if (storageLength != 0) { + int lastStorageIdx = 0; + long row = storage[0]; + long nextRow = storageLength > 1 ? storage[1] : 0L; + + for (int idx = 0; idx < arraySize; idx++) { + int n = idx * elementBits; + int storageIdx = n >> 6; + int p = (idx + 1) * elementBits - 1 >> 6; + int q = n ^ storageIdx << 6; + if (storageIdx != lastStorageIdx) { + row = nextRow; + nextRow = storageIdx + 1 < storageLength ? storage[storageIdx + 1] : 0L; + lastStorageIdx = storageIdx; + } + if (storageIdx == p) { + if (isInFilter[(int) (row >>> q & maxValue)]) { + action.accept(counter); + } else { + if (isInFilter[(int) ((row >>> q | nextRow << (64 - q)) & maxValue)]) { + action.accept(counter); + } + } + } + } + } + } + + private static Int2ObjectOpenHashMap getPalette(IBlockStatePalette palette) { + PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); + palette.write(buf); + int size = buf.readVarInt(); + Int2ObjectOpenHashMap paletteMap = new Int2ObjectOpenHashMap<>(size); + for (int i = 0; i < size; i++) { + paletteMap.put(i, Block.BLOCK_STATE_IDS.getByValue(buf.readVarInt())); + } + return paletteMap; + } + } +} diff --git a/src/main/java/baritone/command/defaults/MineCommand.java b/src/main/java/baritone/command/defaults/MineCommand.java index 63712fe3e..1ab5c3321 100644 --- a/src/main/java/baritone/command/defaults/MineCommand.java +++ b/src/main/java/baritone/command/defaults/MineCommand.java @@ -17,6 +17,7 @@ package baritone.command.defaults; +import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.command.Command; import baritone.api.command.argument.IArgConsumer; @@ -45,7 +46,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { while (args.hasAny()) { boms.add(args.getDatatypeFor(ForBlockOptionalMeta.INSTANCE)); } - WorldScanner.INSTANCE.repack(ctx); + BaritoneAPI.getProvider().getWorldScanner().repack(ctx); logDirect(String.format("Mining %s", boms.toString())); baritone.getMineProcess().mine(quantity, boms.toArray(new BlockOptionalMeta[0])); } diff --git a/src/main/java/baritone/command/defaults/PathCommand.java b/src/main/java/baritone/command/defaults/PathCommand.java index 182a1e5bc..24f47d625 100644 --- a/src/main/java/baritone/command/defaults/PathCommand.java +++ b/src/main/java/baritone/command/defaults/PathCommand.java @@ -17,6 +17,7 @@ package baritone.command.defaults; +import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.command.Command; import baritone.api.command.argument.IArgConsumer; @@ -38,7 +39,7 @@ public PathCommand(IBaritone baritone) { public void execute(String label, IArgConsumer args) throws CommandException { ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); args.requireMax(0); - WorldScanner.INSTANCE.repack(ctx); + BaritoneAPI.getProvider().getWorldScanner().repack(ctx); customGoalProcess.path(); logDirect("Now pathing"); } diff --git a/src/main/java/baritone/command/defaults/RepackCommand.java b/src/main/java/baritone/command/defaults/RepackCommand.java index cafbea524..cd054b10b 100644 --- a/src/main/java/baritone/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/command/defaults/RepackCommand.java @@ -17,6 +17,7 @@ package baritone.command.defaults; +import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.command.Command; import baritone.api.command.argument.IArgConsumer; @@ -36,7 +37,7 @@ public RepackCommand(IBaritone baritone) { @Override public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); - logDirect(String.format("Queued %d chunks for repacking", WorldScanner.INSTANCE.repack(ctx))); + logDirect(String.format("Queued %d chunks for repacking", BaritoneAPI.getProvider().getWorldScanner().repack(ctx))); } @Override diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index 0ef85f07d..73c575d22 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -18,6 +18,7 @@ package baritone.process; import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalComposite; @@ -189,7 +190,7 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { } if (Baritone.settings().mineGoalUpdateInterval.value != 0 && tickCount++ % Baritone.settings().mineGoalUpdateInterval.value == 0) { - Baritone.getExecutor().execute(() -> locations = WorldScanner.INSTANCE.scanChunkRadius(ctx, scan, 256, 10, 10)); + Baritone.getExecutor().execute(() -> locations = BaritoneAPI.getProvider().getWorldScanner().scanChunkRadius(ctx, scan, 256, 10, 10)); } if (locations == null) { return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 1ec47cd92..a10a569aa 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -18,6 +18,7 @@ package baritone.process; import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.*; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; @@ -355,7 +356,7 @@ public static List searchWorld(CalculationContext ctx, BlockOptionalMe locs = prune(ctx, locs, filter, max, blacklist, dropped); if (!untracked.isEmpty() || (Baritone.settings().extendCacheOnThreshold.value && locs.size() < max)) { - locs.addAll(WorldScanner.INSTANCE.scanChunkRadius( + locs.addAll(BaritoneAPI.getProvider().getWorldScanner().scanChunkRadius( ctx.getBaritone().getPlayerContext(), filter, max, diff --git a/src/main/java/baritone/utils/accessor/IBitArray.java b/src/main/java/baritone/utils/accessor/IBitArray.java index baea5c1da..08f54584c 100644 --- a/src/main/java/baritone/utils/accessor/IBitArray.java +++ b/src/main/java/baritone/utils/accessor/IBitArray.java @@ -3,4 +3,8 @@ public interface IBitArray { int[] toArray(); + + long getMaxEntryValue(); + + int getBitsPerEntry(); } diff --git a/src/main/java/baritone/utils/accessor/IBlockStateContainer.java b/src/main/java/baritone/utils/accessor/IBlockStateContainer.java index 39572fc5d..bd280aeb1 100644 --- a/src/main/java/baritone/utils/accessor/IBlockStateContainer.java +++ b/src/main/java/baritone/utils/accessor/IBlockStateContainer.java @@ -1,9 +1,15 @@ package baritone.utils.accessor; import net.minecraft.block.state.IBlockState; +import net.minecraft.util.BitArray; +import net.minecraft.world.chunk.IBlockStatePalette; public interface IBlockStateContainer { + IBlockStatePalette getPalette(); + + BitArray getStorage(); + IBlockState getAtPalette(int index); int[] storageArray(); From 0b6088cd2df5ee5a099ec7a63fa00ad0378d0c6a Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Fri, 23 Dec 2022 16:58:10 -0700 Subject: [PATCH 002/111] fix getting the block from the pallete, and change the chunk scan order to spiral out --- .../baritone/cache/FasterWorldScanner.java | 66 ++++++++++--------- 1 file changed, 35 insertions(+), 31 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index f1829f9f0..189374dd6 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -102,12 +102,27 @@ public WorldScannerContext(BlockOptionalMetaLookup filter, IPlayerContext ctx) { this.ctx = ctx; } - public List getChunkRange(int centerX, int centerZ, int chunkrange) { + public List getChunkRange(int centerX, int centerZ, int chunkRadius) { List chunks = new ArrayList<>(); - for (int x = centerX - chunkrange; x <= centerX + chunkrange; x++) { - for (int z = centerZ - chunkrange; z <= centerZ + chunkrange; z++) { + // spiral out + int x = centerX; + int z = centerZ; + int dx = 0; + int dz = -1; + int t = Math.max(chunkRadius, 1); + int maxI = t * t; + for (int i = 0; i < maxI; i++) { + if ((-chunkRadius / 2 <= x) && (x <= chunkRadius / 2) && (-chunkRadius / 2 <= z) && (z <= chunkRadius / 2)) { chunks.add(new ChunkPos(x, z)); } + // idk how this works, copilot did it + if ((x == z) || ((x < 0) && (x == -z)) || ((x > 0) && (x == 1 - z))) { + t = dx; + dx = -dz; + dz = t; + } + x += dx; + z += dz; } return chunks; } @@ -221,36 +236,25 @@ private boolean[] getIncludedFilterIndices(IBlockStatePalette palette) { } private static void forEach(BitArray array, boolean[] isInFilter, IntConsumer action) { - int counter = 0; - long[] storage = array.getBackingLongArray(); + long[] longArray = array.getBackingLongArray(); int arraySize = array.size(); - int elementBits = ((IBitArray) array).getBitsPerEntry(); - long maxValue = ((IBitArray) array).getMaxEntryValue(); - int storageLength = storage.length; - - if (storageLength != 0) { - int lastStorageIdx = 0; - long row = storage[0]; - long nextRow = storageLength > 1 ? storage[1] : 0L; - - for (int idx = 0; idx < arraySize; idx++) { - int n = idx * elementBits; - int storageIdx = n >> 6; - int p = (idx + 1) * elementBits - 1 >> 6; - int q = n ^ storageIdx << 6; - if (storageIdx != lastStorageIdx) { - row = nextRow; - nextRow = storageIdx + 1 < storageLength ? storage[storageIdx + 1] : 0L; - lastStorageIdx = storageIdx; + int bitsPerEntry = ((IBitArray) array).getBitsPerEntry(); + long maxEntryValue = ((IBitArray) array).getMaxEntryValue(); + + for (int idx = 0, kl = bitsPerEntry - 1; idx < arraySize; idx++, kl += bitsPerEntry) { + final int i = idx * bitsPerEntry; + final int j = i >> 6; + final int l = i & 63; + final int k = kl >> 6; + final long jl = longArray[j] >>> l; + + if (j == k) { + if (isInFilter[(int) (jl & maxEntryValue)]) { + action.accept(idx); } - if (storageIdx == p) { - if (isInFilter[(int) (row >>> q & maxValue)]) { - action.accept(counter); - } else { - if (isInFilter[(int) ((row >>> q | nextRow << (64 - q)) & maxValue)]) { - action.accept(counter); - } - } + } else { + if (isInFilter[(int) ((jl | longArray[k] << (64 - l)) & maxEntryValue)]) { + action.accept(idx); } } } From 12b596e53696212515087f458167775d45d12a85 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Fri, 23 Dec 2022 17:10:37 -0700 Subject: [PATCH 003/111] fix spiral --- .../baritone/cache/FasterWorldScanner.java | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index 189374dd6..ce4a8cd48 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -105,24 +105,16 @@ public WorldScannerContext(BlockOptionalMetaLookup filter, IPlayerContext ctx) { public List getChunkRange(int centerX, int centerZ, int chunkRadius) { List chunks = new ArrayList<>(); // spiral out - int x = centerX; - int z = centerZ; - int dx = 0; - int dz = -1; - int t = Math.max(chunkRadius, 1); - int maxI = t * t; - for (int i = 0; i < maxI; i++) { - if ((-chunkRadius / 2 <= x) && (x <= chunkRadius / 2) && (-chunkRadius / 2 <= z) && (z <= chunkRadius / 2)) { - chunks.add(new ChunkPos(x, z)); + chunks.add(new ChunkPos(centerX, centerZ)); + for (int i = 1; i < chunkRadius; i++) { + for (int x = centerX - i; x <= centerX + i; x++) { + chunks.add(new ChunkPos(x, centerZ - i)); + chunks.add(new ChunkPos(x, centerZ + i)); } - // idk how this works, copilot did it - if ((x == z) || ((x < 0) && (x == -z)) || ((x > 0) && (x == 1 - z))) { - t = dx; - dx = -dz; - dz = t; + for (int z = centerZ - i + 1; z <= centerZ + i - 1; z++) { + chunks.add(new ChunkPos(centerX - i, z)); + chunks.add(new ChunkPos(centerX + i, z)); } - x += dx; - z += dz; } return chunks; } From 0ae59755e3ade3f576d4e83ae9b4b5abef542b75 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Fri, 23 Dec 2022 17:25:23 -0700 Subject: [PATCH 004/111] make limit not happen if it shouldn't --- .../baritone/cache/FasterWorldScanner.java | 44 ++++++++++++++----- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index ce4a8cd48..535e925e1 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -30,6 +30,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.network.PacketBuffer; import net.minecraft.util.BitArray; +import net.minecraft.util.ObjectIntIdentityMap; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.chunk.*; @@ -142,8 +143,20 @@ public List scanChunkRange(int centerX, int centerZ, int chunkRange, i private List scanChunksInternal(List chunkPositions, int maxBlocks) { assert ctx.world() != null; - return chunkPositions.parallelStream().flatMap(this::scanChunkInternal).limit(maxBlocks <= 0 ? Long.MAX_VALUE : maxBlocks).collect(Collectors.toList()); + try { + Stream posStream = chunkPositions.parallelStream().flatMap(this::scanChunkInternal); + if (maxBlocks >= 0) { + // WARNING: this can be expensive if maxBlocks is large... + // see limit's javadoc + posStream = posStream.limit(maxBlocks); + } + return posStream.collect(Collectors.toList()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } } + private Stream scanChunkInternal(ChunkPos pos) { IChunkProvider chunkProvider = ctx.world().getChunkProvider(); // if chunk is not loaded, return empty stream @@ -206,13 +219,13 @@ private boolean addCachedState(IBlockState state) { private boolean[] getIncludedFilterIndices(IBlockStatePalette palette) { boolean commonBlockFound = false; - Int2ObjectOpenHashMap paletteMap = getPalette(palette); + ObjectIntIdentityMap paletteMap = getPalette(palette); int size = paletteMap.size(); boolean[] isInFilter = new boolean[size]; for (int i = 0; i < size; i++) { - IBlockState state = paletteMap.get(i); + IBlockState state = paletteMap.getByValue(i); if (getFilterResult(state)) { isInFilter[i] = true; commonBlockFound = true; @@ -252,15 +265,24 @@ private static void forEach(BitArray array, boolean[] isInFilter, IntConsumer ac } } - private static Int2ObjectOpenHashMap getPalette(IBlockStatePalette palette) { - PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); - palette.write(buf); - int size = buf.readVarInt(); - Int2ObjectOpenHashMap paletteMap = new Int2ObjectOpenHashMap<>(size); - for (int i = 0; i < size; i++) { - paletteMap.put(i, Block.BLOCK_STATE_IDS.getByValue(buf.readVarInt())); + /** + * cheats to get the actual map of id -> blockstate from the various palette implementations + */ + private static ObjectIntIdentityMap getPalette(IBlockStatePalette palette) { + if (palette instanceof BlockStatePaletteRegistry) { + return Block.BLOCK_STATE_IDS; + } else { + PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); + palette.write(buf); + int size = buf.readVarInt(); + ObjectIntIdentityMap states = new ObjectIntIdentityMap<>(); + for (int i = 0; i < size; i++) { + IBlockState state = Block.BLOCK_STATE_IDS.getByValue(buf.readVarInt()); + assert state != null; + states.put(state, i); + } + return states; } - return paletteMap; } } } From 96f432d2d550ca92a8e96c66981696a62bb628b1 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Fri, 23 Dec 2022 17:26:46 -0700 Subject: [PATCH 005/111] add comment --- src/main/java/baritone/cache/FasterWorldScanner.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index 535e925e1..6c110decb 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -93,6 +93,7 @@ public int repack(IPlayerContext ctx, int range) { } // for porting, see {@link https://github.com/JsMacros/JsMacros/blob/backport-1.12.2/common/src/main/java/xyz/wagyourtail/jsmacros/client/api/classes/worldscanner/WorldScanner.java} + // tho I did change some things... public static class WorldScannerContext { private final BlockOptionalMetaLookup filter; private final IPlayerContext ctx; From ecdec87e7a7a8107eefe20a7797decf4ad1e7972 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Sat, 24 Dec 2022 11:43:54 -0700 Subject: [PATCH 006/111] fix using wrong functions in scan --- src/main/java/baritone/cache/FasterWorldScanner.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index 6c110decb..ace429de9 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -25,7 +25,6 @@ import baritone.utils.accessor.IBitArray; import baritone.utils.accessor.IBlockStateContainer; import io.netty.buffer.Unpooled; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.network.PacketBuffer; @@ -49,12 +48,12 @@ public enum FasterWorldScanner implements IWorldScanner { INSTANCE; @Override public List scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLookup filter, int max, int yLevelThreshold, int maxSearchRadius) { - return new WorldScannerContext(filter, ctx).scanAroundPlayerRange(maxSearchRadius); + return new WorldScannerContext(filter, ctx).scanAroundPlayer(maxSearchRadius, max); } @Override public List scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold) { - return new WorldScannerContext(filter, ctx).scanAroundPlayerUntilCount(max); + return new WorldScannerContext(filter, ctx).scanChunkInternal(pos).collect(Collectors.toList()); } @Override From ce1fb49252e897f0b223e1bbdc18bb096ac56678 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Sat, 24 Dec 2022 11:52:48 -0700 Subject: [PATCH 007/111] spiral always pick closest chunk first now --- .../baritone/cache/FasterWorldScanner.java | 42 ++++++++++--------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index ace429de9..efb80245a 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -91,34 +91,38 @@ public int repack(IPlayerContext ctx, int range) { return queued; } - // for porting, see {@link https://github.com/JsMacros/JsMacros/blob/backport-1.12.2/common/src/main/java/xyz/wagyourtail/jsmacros/client/api/classes/worldscanner/WorldScanner.java} - // tho I did change some things... + // ordered in a way that the closest blocks are generally first + public List getChunkRange(int centerX, int centerZ, int chunkRadius) { + List chunks = new ArrayList<>(); + // spiral out + chunks.add(new ChunkPos(centerX, centerZ)); + for (int i = 1; i < chunkRadius; i++) { + for (int j = 0; j <= i; j++) { + chunks.add(new ChunkPos(centerX - j, centerZ - i)); + chunks.add(new ChunkPos(centerX + j, centerZ - i)); + chunks.add(new ChunkPos(centerX - j, centerZ + i)); + chunks.add(new ChunkPos(centerX + j, centerZ + i)); + if (j != 0 && j != i) { + chunks.add(new ChunkPos(centerX - i, centerZ - j)); + chunks.add(new ChunkPos(centerX + i, centerZ - j)); + chunks.add(new ChunkPos(centerX - i, centerZ + j)); + chunks.add(new ChunkPos(centerX + i, centerZ + j)); + } + } + } + return chunks; + } + public static class WorldScannerContext { private final BlockOptionalMetaLookup filter; private final IPlayerContext ctx; - private final Map cachedFilter = new ConcurrentHashMap<>(); public WorldScannerContext(BlockOptionalMetaLookup filter, IPlayerContext ctx) { this.filter = filter; this.ctx = ctx; } - public List getChunkRange(int centerX, int centerZ, int chunkRadius) { - List chunks = new ArrayList<>(); - // spiral out - chunks.add(new ChunkPos(centerX, centerZ)); - for (int i = 1; i < chunkRadius; i++) { - for (int x = centerX - i; x <= centerX + i; x++) { - chunks.add(new ChunkPos(x, centerZ - i)); - chunks.add(new ChunkPos(x, centerZ + i)); - } - for (int z = centerZ - i + 1; z <= centerZ + i - 1; z++) { - chunks.add(new ChunkPos(centerX - i, z)); - chunks.add(new ChunkPos(centerX + i, z)); - } - } - return chunks; - } + public List scanAroundPlayerRange(int range) { return scanAroundPlayer(range, -1); From 6260c6d3d7edd984a8b2b900770d4d11c60d4dbd Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Sat, 24 Dec 2022 12:11:26 -0700 Subject: [PATCH 008/111] apply suggestions --- .../baritone/api/utils/BlockOptionalMeta.java | 4 + .../api/utils/BlockOptionalMetaLookup.java | 25 +- .../baritone/cache/FasterWorldScanner.java | 261 ++++++++---------- 3 files changed, 123 insertions(+), 167 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index a9a34a4aa..e86341816 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -315,4 +315,8 @@ public IBlockState getAnyBlockState() { return null; } + + public Set getAllBlockStates() { + return blockstates; + } } diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index 041c6162c..8fb52fb52 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -22,15 +22,22 @@ import net.minecraft.item.ItemStack; import java.util.Arrays; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.stream.Stream; public class BlockOptionalMetaLookup { - + private final Set blockSet = new HashSet<>(); + private final Set blockStateSet = new HashSet<>(); private final BlockOptionalMeta[] boms; public BlockOptionalMetaLookup(BlockOptionalMeta... boms) { this.boms = boms; + for (BlockOptionalMeta bom : boms) { + blockSet.add(bom.getBlock()); + blockStateSet.addAll(bom.getAllBlockStates()); + } } public BlockOptionalMetaLookup(Block... blocks) { @@ -52,23 +59,11 @@ public BlockOptionalMetaLookup(String... blocks) { } public boolean has(Block block) { - for (BlockOptionalMeta bom : boms) { - if (bom.getBlock() == block) { - return true; - } - } - - return false; + return blockSet.contains(block); } public boolean has(IBlockState state) { - for (BlockOptionalMeta bom : boms) { - if (bom.matches(state)) { - return true; - } - } - - return false; + return blockStateSet.contains(state); } public boolean has(ItemStack stack) { diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index efb80245a..7a46f04ff 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -37,8 +37,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.IntConsumer; import java.util.stream.Collectors; @@ -48,12 +46,16 @@ public enum FasterWorldScanner implements IWorldScanner { INSTANCE; @Override public List scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLookup filter, int max, int yLevelThreshold, int maxSearchRadius) { - return new WorldScannerContext(filter, ctx).scanAroundPlayer(maxSearchRadius, max); + assert ctx.world() != null; + if (maxSearchRadius < 0) { + throw new IllegalArgumentException("chunkRange must be >= 0"); + } + return scanChunksInternal(ctx, filter, getChunkRange(ctx.playerFeet().x >> 4, ctx.playerFeet().z >> 4, maxSearchRadius), max); } @Override public List scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold) { - return new WorldScannerContext(filter, ctx).scanChunkInternal(pos).collect(Collectors.toList()); + return scanChunkInternal(ctx, filter, pos).limit(max).collect(Collectors.toList()); } @Override @@ -92,15 +94,17 @@ public int repack(IPlayerContext ctx, int range) { } // ordered in a way that the closest blocks are generally first - public List getChunkRange(int centerX, int centerZ, int chunkRadius) { + public static List getChunkRange(int centerX, int centerZ, int chunkRadius) { List chunks = new ArrayList<>(); // spiral out chunks.add(new ChunkPos(centerX, centerZ)); for (int i = 1; i < chunkRadius; i++) { for (int j = 0; j <= i; j++) { chunks.add(new ChunkPos(centerX - j, centerZ - i)); - chunks.add(new ChunkPos(centerX + j, centerZ - i)); - chunks.add(new ChunkPos(centerX - j, centerZ + i)); + if (j != 0) { + chunks.add(new ChunkPos(centerX + j, centerZ - i)); + chunks.add(new ChunkPos(centerX - j, centerZ + i)); + } chunks.add(new ChunkPos(centerX + j, centerZ + i)); if (j != 0 && j != i) { chunks.add(new ChunkPos(centerX - i, centerZ - j)); @@ -113,180 +117,133 @@ public List getChunkRange(int centerX, int centerZ, int chunkRadius) { return chunks; } - public static class WorldScannerContext { - private final BlockOptionalMetaLookup filter; - private final IPlayerContext ctx; - - public WorldScannerContext(BlockOptionalMetaLookup filter, IPlayerContext ctx) { - this.filter = filter; - this.ctx = ctx; - } - - - - public List scanAroundPlayerRange(int range) { - return scanAroundPlayer(range, -1); - } - - public List scanAroundPlayerUntilCount(int count) { - return scanAroundPlayer(32, count); - } - - public List scanAroundPlayer(int range, int maxCount) { - assert ctx.player() != null; - return scanChunkRange(ctx.playerFeet().x >> 4, ctx.playerFeet().z >> 4, range, maxCount); - } - - public List scanChunkRange(int centerX, int centerZ, int chunkRange, int maxBlocks) { - assert ctx.world() != null; - if (chunkRange < 0) { - throw new IllegalArgumentException("chunkRange must be >= 0"); - } - return scanChunksInternal(getChunkRange(centerX, centerZ, chunkRange), maxBlocks); - } - - private List scanChunksInternal(List chunkPositions, int maxBlocks) { - assert ctx.world() != null; - try { - Stream posStream = chunkPositions.parallelStream().flatMap(this::scanChunkInternal); + private List scanChunksInternal(IPlayerContext ctx, BlockOptionalMetaLookup lookup, List chunkPositions, int maxBlocks) { + assert ctx.world() != null; + try { + Stream posStream = chunkPositions.parallelStream().flatMap(p -> scanChunkInternal(ctx, lookup, p)); if (maxBlocks >= 0) { // WARNING: this can be expensive if maxBlocks is large... // see limit's javadoc posStream = posStream.limit(maxBlocks); } return posStream.collect(Collectors.toList()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } + } catch (Exception e) { + e.printStackTrace(); + throw e; } + } - private Stream scanChunkInternal(ChunkPos pos) { - IChunkProvider chunkProvider = ctx.world().getChunkProvider(); - // if chunk is not loaded, return empty stream - if (!chunkProvider.isChunkGeneratedAt(pos.x, pos.z)) { - return Stream.empty(); - } - - long chunkX = (long) pos.x << 4; - long chunkZ = (long) pos.z << 4; - - List blocks = new ArrayList<>(); - - streamChunkSections(chunkProvider.getLoadedChunk(pos.x, pos.z), (section, isInFilter) -> { - int yOffset = section.getYLocation(); - BitArray array = (BitArray) ((IBlockStateContainer) section.getData()).getStorage(); - forEach(array, isInFilter, place -> blocks.add(new BlockPos( - chunkX + ((place & 255) & 15), - yOffset + (place >> 8), - chunkZ + ((place & 255) >> 4) - ))); - }); - return blocks.stream(); + private Stream scanChunkInternal(IPlayerContext ctx, BlockOptionalMetaLookup lookup, ChunkPos pos) { + IChunkProvider chunkProvider = ctx.world().getChunkProvider(); + // if chunk is not loaded, return empty stream + if (!chunkProvider.isChunkGeneratedAt(pos.x, pos.z)) { + return Stream.empty(); } - private void streamChunkSections(Chunk chunk, BiConsumer consumer) { - for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) { - if (section == null || section.isEmpty()) { - continue; - } - - BlockStateContainer sectionContainer = section.getData(); - //this won't work if the PaletteStorage is of the type EmptyPaletteStorage - if (((IBlockStateContainer) sectionContainer).getStorage() == null) { - continue; - } + long chunkX = (long) pos.x << 4; + long chunkZ = (long) pos.z << 4; + + List blocks = new ArrayList<>(); + + collectChunkSections(lookup, chunkProvider.getLoadedChunk(pos.x, pos.z), (section, isInFilter) -> { + int yOffset = section.getYLocation(); + BitArray array = (BitArray) ((IBlockStateContainer) section.getData()).getStorage(); + collectBlockLocations(array, isInFilter, place -> blocks.add(new BlockPos( + chunkX + ((place & 255) & 15), + yOffset + (place >> 8), + chunkZ + ((place & 255) >> 4) + ))); + }); + return blocks.stream(); + } - boolean[] isInFilter = getIncludedFilterIndices(((IBlockStateContainer) sectionContainer).getPalette()); - if (isInFilter.length == 0) { - continue; - } - consumer.accept(section, isInFilter); - } - } - private boolean getFilterResult(IBlockState state) { - Boolean v; - return (v = cachedFilter.get(state)) == null ? addCachedState(state) : v; - } - private boolean addCachedState(IBlockState state) { - boolean isInFilter = false; + private void collectChunkSections(BlockOptionalMetaLookup lookup, Chunk chunk, BiConsumer consumer) { + for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) { + if (section == null || section.isEmpty()) { + continue; + } - if (filter != null) { - isInFilter = filter.has(state); + BlockStateContainer sectionContainer = section.getData(); + //this won't work if the PaletteStorage is of the type EmptyPaletteStorage + if (((IBlockStateContainer) sectionContainer).getStorage() == null) { + continue; } - cachedFilter.put(state, isInFilter); - return isInFilter; + boolean[] isInFilter = getIncludedFilterIndices(lookup, ((IBlockStateContainer) sectionContainer).getPalette()); + if (isInFilter.length == 0) { + continue; + } + consumer.accept(section, isInFilter); } + } - private boolean[] getIncludedFilterIndices(IBlockStatePalette palette) { - boolean commonBlockFound = false; - ObjectIntIdentityMap paletteMap = getPalette(palette); - int size = paletteMap.size(); + private boolean[] getIncludedFilterIndices(BlockOptionalMetaLookup lookup, IBlockStatePalette palette) { + boolean commonBlockFound = false; + ObjectIntIdentityMap paletteMap = getPalette(palette); + int size = paletteMap.size(); - boolean[] isInFilter = new boolean[size]; + boolean[] isInFilter = new boolean[size]; - for (int i = 0; i < size; i++) { - IBlockState state = paletteMap.getByValue(i); - if (getFilterResult(state)) { - isInFilter[i] = true; - commonBlockFound = true; - } else { - isInFilter[i] = false; - } + for (int i = 0; i < size; i++) { + IBlockState state = paletteMap.getByValue(i); + if (lookup.has(state)) { + isInFilter[i] = true; + commonBlockFound = true; + } else { + isInFilter[i] = false; } + } - if (!commonBlockFound) { - return new boolean[0]; - } - return isInFilter; + if (!commonBlockFound) { + return new boolean[0]; } + return isInFilter; + } - private static void forEach(BitArray array, boolean[] isInFilter, IntConsumer action) { - long[] longArray = array.getBackingLongArray(); - int arraySize = array.size(); - int bitsPerEntry = ((IBitArray) array).getBitsPerEntry(); - long maxEntryValue = ((IBitArray) array).getMaxEntryValue(); - - for (int idx = 0, kl = bitsPerEntry - 1; idx < arraySize; idx++, kl += bitsPerEntry) { - final int i = idx * bitsPerEntry; - final int j = i >> 6; - final int l = i & 63; - final int k = kl >> 6; - final long jl = longArray[j] >>> l; - - if (j == k) { - if (isInFilter[(int) (jl & maxEntryValue)]) { - action.accept(idx); - } - } else { - if (isInFilter[(int) ((jl | longArray[k] << (64 - l)) & maxEntryValue)]) { - action.accept(idx); - } + private static void collectBlockLocations(BitArray array, boolean[] isInFilter, IntConsumer action) { + long[] longArray = array.getBackingLongArray(); + int arraySize = array.size(); + int bitsPerEntry = ((IBitArray) array).getBitsPerEntry(); + long maxEntryValue = ((IBitArray) array).getMaxEntryValue(); + + for (int idx = 0, kl = bitsPerEntry - 1; idx < arraySize; idx++, kl += bitsPerEntry) { + final int i = idx * bitsPerEntry; + final int j = i >> 6; + final int l = i & 63; + final int k = kl >> 6; + final long jl = longArray[j] >>> l; + + if (j == k) { + if (isInFilter[(int) (jl & maxEntryValue)]) { + action.accept(idx); + } + } else { + if (isInFilter[(int) ((jl | longArray[k] << (64 - l)) & maxEntryValue)]) { + action.accept(idx); } } } + } - /** - * cheats to get the actual map of id -> blockstate from the various palette implementations - */ - private static ObjectIntIdentityMap getPalette(IBlockStatePalette palette) { - if (palette instanceof BlockStatePaletteRegistry) { - return Block.BLOCK_STATE_IDS; - } else { - PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); - palette.write(buf); - int size = buf.readVarInt(); - ObjectIntIdentityMap states = new ObjectIntIdentityMap<>(); - for (int i = 0; i < size; i++) { - IBlockState state = Block.BLOCK_STATE_IDS.getByValue(buf.readVarInt()); - assert state != null; - states.put(state, i); - } - return states; + /** + * cheats to get the actual map of id -> blockstate from the various palette implementations + */ + private static ObjectIntIdentityMap getPalette(IBlockStatePalette palette) { + if (palette instanceof BlockStatePaletteRegistry) { + return Block.BLOCK_STATE_IDS; + } else { + PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); + palette.write(buf); + int size = buf.readVarInt(); + ObjectIntIdentityMap states = new ObjectIntIdentityMap<>(); + for (int i = 0; i < size; i++) { + IBlockState state = Block.BLOCK_STATE_IDS.getByValue(buf.readVarInt()); + assert state != null; + states.put(state, i); } + return states; } } } From c04eb066cb84e8a4362f913c301fc03da346718c Mon Sep 17 00:00:00 2001 From: William Gray Date: Wed, 28 Dec 2022 01:06:10 +0000 Subject: [PATCH 009/111] Update src/main/java/baritone/cache/FasterWorldScanner.java Co-authored-by: ZacSharp <68165024+ZacSharp@users.noreply.github.com> --- src/main/java/baritone/cache/FasterWorldScanner.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index 7a46f04ff..4dd480f25 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -106,11 +106,13 @@ public static List getChunkRange(int centerX, int centerZ, int chunkRa chunks.add(new ChunkPos(centerX - j, centerZ + i)); } chunks.add(new ChunkPos(centerX + j, centerZ + i)); - if (j != 0 && j != i) { + if (j != i) { chunks.add(new ChunkPos(centerX - i, centerZ - j)); chunks.add(new ChunkPos(centerX + i, centerZ - j)); - chunks.add(new ChunkPos(centerX - i, centerZ + j)); - chunks.add(new ChunkPos(centerX + i, centerZ + j)); + if (j != 0) { + chunks.add(new ChunkPos(centerX - i, centerZ + j)); + chunks.add(new ChunkPos(centerX + i, centerZ + j)); + } } } } From 98a748afb3340ad979a09a62623ddefcdb2d7887 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Tue, 27 Dec 2022 22:42:38 -0700 Subject: [PATCH 010/111] fix stream limit. immutable's in BOML --- .../baritone/api/utils/BlockOptionalMeta.java | 8 ++++-- .../api/utils/BlockOptionalMetaLookup.java | 28 ++++++++++++------- .../baritone/cache/FasterWorldScanner.java | 6 +++- 3 files changed, 29 insertions(+), 13 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index e86341816..e0f491fba 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -41,8 +41,8 @@ public final class BlockOptionalMeta { private final int meta; private final boolean noMeta; private final Set blockstates; - private final ImmutableSet stateHashes; - private final ImmutableSet stackHashes; + private final Set stateHashes; + private final Set stackHashes; private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); private static final Map normalizations; @@ -319,4 +319,8 @@ public IBlockState getAnyBlockState() { public Set getAllBlockStates() { return blockstates; } + + public Set stackHashes() { + return stackHashes; + } } diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index 8fb52fb52..6d236e90e 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -17,6 +17,7 @@ package baritone.api.utils; +import com.google.common.collect.ImmutableSet; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; @@ -28,34 +29,41 @@ import java.util.stream.Stream; public class BlockOptionalMetaLookup { - private final Set blockSet = new HashSet<>(); - private final Set blockStateSet = new HashSet<>(); + private final Set blockSet; + private final Set blockStateSet; private final BlockOptionalMeta[] boms; public BlockOptionalMetaLookup(BlockOptionalMeta... boms) { this.boms = boms; + Set blocks = new HashSet<>(); + Set blockStates = new HashSet<>(); + Set stacks = new HashSet<>(); for (BlockOptionalMeta bom : boms) { - blockSet.add(bom.getBlock()); - blockStateSet.addAll(bom.getAllBlockStates()); + blocks.add(bom.getBlock()); + blockStates.addAll(bom.getAllBlockStates()); + stacks.addAll(bom.stackHashes()); } + this.blockSet = ImmutableSet.copyOf(blocks); + this.blockStateSet = ImmutableSet.copyOf(blockStates); } public BlockOptionalMetaLookup(Block... blocks) { - this.boms = Stream.of(blocks) + this(Stream.of(blocks) .map(BlockOptionalMeta::new) - .toArray(BlockOptionalMeta[]::new); + .toArray(BlockOptionalMeta[]::new)); + } public BlockOptionalMetaLookup(List blocks) { - this.boms = blocks.stream() + this(blocks.stream() .map(BlockOptionalMeta::new) - .toArray(BlockOptionalMeta[]::new); + .toArray(BlockOptionalMeta[]::new)); } public BlockOptionalMetaLookup(String... blocks) { - this.boms = Stream.of(blocks) + this(Stream.of(blocks) .map(BlockOptionalMeta::new) - .toArray(BlockOptionalMeta[]::new); + .toArray(BlockOptionalMeta[]::new)); } public boolean has(Block block) { diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index 4dd480f25..e133f0e49 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -55,7 +55,11 @@ public List scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLooku @Override public List scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold) { - return scanChunkInternal(ctx, filter, pos).limit(max).collect(Collectors.toList()); + Stream stream = scanChunkInternal(ctx, filter, pos); + if (max >= 0) { + stream = stream.limit(max); + } + return stream.collect(Collectors.toList()); } @Override From e55db05f204a8e913ee90b9f3400b40a1abec509 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Tue, 27 Dec 2022 23:30:35 -0700 Subject: [PATCH 011/111] sacrifice a bit of speed for better block ordering --- .../baritone/cache/FasterWorldScanner.java | 57 ++++++++++++++----- 1 file changed, 43 insertions(+), 14 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index e133f0e49..d4c20766e 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -36,10 +36,13 @@ import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; +import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.IntConsumer; import java.util.stream.Collectors; +import java.util.stream.IntStream; import java.util.stream.Stream; public enum FasterWorldScanner implements IWorldScanner { @@ -146,43 +149,59 @@ private Stream scanChunkInternal(IPlayerContext ctx, BlockOptionalMeta return Stream.empty(); } - long chunkX = (long) pos.x << 4; - long chunkZ = (long) pos.z << 4; + long inChunkX = (long) pos.x << 4; + long inChunkZ = (long) pos.z << 4; - List blocks = new ArrayList<>(); + int playerY = ctx.playerFeet().y; + int playerSection = ctx.playerFeet().y >> 4; - collectChunkSections(lookup, chunkProvider.getLoadedChunk(pos.x, pos.z), (section, isInFilter) -> { + + return streamChunkSections(lookup, chunkProvider.getLoadedChunk(pos.x, pos.z), playerSection).flatMap((data) -> { + ExtendedBlockStorage section = data.section; + boolean[] isInFilter = data.isInFilter; + List blocks = new ArrayList<>(); int yOffset = section.getYLocation(); BitArray array = (BitArray) ((IBlockStateContainer) section.getData()).getStorage(); collectBlockLocations(array, isInFilter, place -> blocks.add(new BlockPos( - chunkX + ((place & 255) & 15), + (int) inChunkX + ((place & 255) & 15), yOffset + (place >> 8), - chunkZ + ((place & 255) >> 4) + (int) inChunkZ + ((place & 255) >> 4) ))); + return blocks.stream().sorted((a, b) -> { + int distA = Math.abs(a.getY() - playerY); + int distB = Math.abs(b.getY() - playerY); + return Integer.compare(distA, distB); + }); }); - return blocks.stream(); } - private void collectChunkSections(BlockOptionalMetaLookup lookup, Chunk chunk, BiConsumer consumer) { - for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) { + private Stream streamChunkSections(BlockOptionalMetaLookup lookup, Chunk chunk, int playerSection) { + ExtendedBlockStorage[] sections = chunk.getBlockStorageArray(); + // order sections by distance to player + + return IntStream.range(0, sections.length) + .boxed() + .sorted(Comparator.comparingInt(a -> Math.abs(a - playerSection))) + .map(i -> { + ExtendedBlockStorage section = sections[i]; if (section == null || section.isEmpty()) { - continue; + return null; } BlockStateContainer sectionContainer = section.getData(); //this won't work if the PaletteStorage is of the type EmptyPaletteStorage if (((IBlockStateContainer) sectionContainer).getStorage() == null) { - continue; + return null; } boolean[] isInFilter = getIncludedFilterIndices(lookup, ((IBlockStateContainer) sectionContainer).getPalette()); if (isInFilter.length == 0) { - continue; + return null; } - consumer.accept(section, isInFilter); - } + return new SectionData(section, isInFilter); + }).filter(Objects::nonNull); } private boolean[] getIncludedFilterIndices(BlockOptionalMetaLookup lookup, IBlockStatePalette palette) { @@ -252,4 +271,14 @@ private static ObjectIntIdentityMap getPalette(IBlockStatePalette p return states; } } + + private static class SectionData { + ExtendedBlockStorage section; + boolean[] isInFilter; + + SectionData(ExtendedBlockStorage section, boolean[] isInFilter) { + this.section = section; + this.isInFilter = isInFilter; + } + } } From a367031fe248e01910c00122ab75c91c586ed005 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Tue, 27 Dec 2022 23:30:35 -0700 Subject: [PATCH 012/111] Revert "sacrifice a bit of speed for better block ordering" This reverts commit e55db05f204a8e913ee90b9f3400b40a1abec509. --- .../baritone/cache/FasterWorldScanner.java | 57 +++++-------------- 1 file changed, 14 insertions(+), 43 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index d4c20766e..e133f0e49 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -36,13 +36,10 @@ import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import java.util.ArrayList; -import java.util.Comparator; import java.util.List; -import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.IntConsumer; import java.util.stream.Collectors; -import java.util.stream.IntStream; import java.util.stream.Stream; public enum FasterWorldScanner implements IWorldScanner { @@ -149,59 +146,43 @@ private Stream scanChunkInternal(IPlayerContext ctx, BlockOptionalMeta return Stream.empty(); } - long inChunkX = (long) pos.x << 4; - long inChunkZ = (long) pos.z << 4; + long chunkX = (long) pos.x << 4; + long chunkZ = (long) pos.z << 4; - int playerY = ctx.playerFeet().y; - int playerSection = ctx.playerFeet().y >> 4; + List blocks = new ArrayList<>(); - - return streamChunkSections(lookup, chunkProvider.getLoadedChunk(pos.x, pos.z), playerSection).flatMap((data) -> { - ExtendedBlockStorage section = data.section; - boolean[] isInFilter = data.isInFilter; - List blocks = new ArrayList<>(); + collectChunkSections(lookup, chunkProvider.getLoadedChunk(pos.x, pos.z), (section, isInFilter) -> { int yOffset = section.getYLocation(); BitArray array = (BitArray) ((IBlockStateContainer) section.getData()).getStorage(); collectBlockLocations(array, isInFilter, place -> blocks.add(new BlockPos( - (int) inChunkX + ((place & 255) & 15), + chunkX + ((place & 255) & 15), yOffset + (place >> 8), - (int) inChunkZ + ((place & 255) >> 4) + chunkZ + ((place & 255) >> 4) ))); - return blocks.stream().sorted((a, b) -> { - int distA = Math.abs(a.getY() - playerY); - int distB = Math.abs(b.getY() - playerY); - return Integer.compare(distA, distB); - }); }); + return blocks.stream(); } - private Stream streamChunkSections(BlockOptionalMetaLookup lookup, Chunk chunk, int playerSection) { - ExtendedBlockStorage[] sections = chunk.getBlockStorageArray(); - // order sections by distance to player - - return IntStream.range(0, sections.length) - .boxed() - .sorted(Comparator.comparingInt(a -> Math.abs(a - playerSection))) - .map(i -> { - ExtendedBlockStorage section = sections[i]; + private void collectChunkSections(BlockOptionalMetaLookup lookup, Chunk chunk, BiConsumer consumer) { + for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) { if (section == null || section.isEmpty()) { - return null; + continue; } BlockStateContainer sectionContainer = section.getData(); //this won't work if the PaletteStorage is of the type EmptyPaletteStorage if (((IBlockStateContainer) sectionContainer).getStorage() == null) { - return null; + continue; } boolean[] isInFilter = getIncludedFilterIndices(lookup, ((IBlockStateContainer) sectionContainer).getPalette()); if (isInFilter.length == 0) { - return null; + continue; } - return new SectionData(section, isInFilter); - }).filter(Objects::nonNull); + consumer.accept(section, isInFilter); + } } private boolean[] getIncludedFilterIndices(BlockOptionalMetaLookup lookup, IBlockStatePalette palette) { @@ -271,14 +252,4 @@ private static ObjectIntIdentityMap getPalette(IBlockStatePalette p return states; } } - - private static class SectionData { - ExtendedBlockStorage section; - boolean[] isInFilter; - - SectionData(ExtendedBlockStorage section, boolean[] isInFilter) { - this.section = section; - this.isInFilter = isInFilter; - } - } } From 746faf6df6ea9d615dd2bcd421cef446d1b9f922 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Wed, 28 Dec 2022 01:05:17 -0700 Subject: [PATCH 013/111] faster section reorder --- .../baritone/cache/FasterWorldScanner.java | 46 +++++++++++++------ .../java/baritone/process/MineProcess.java | 2 +- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index e133f0e49..9adbf76b0 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -149,9 +149,11 @@ private Stream scanChunkInternal(IPlayerContext ctx, BlockOptionalMeta long chunkX = (long) pos.x << 4; long chunkZ = (long) pos.z << 4; + int playerSectionY = ctx.playerFeet().y >> 4; + List blocks = new ArrayList<>(); - collectChunkSections(lookup, chunkProvider.getLoadedChunk(pos.x, pos.z), (section, isInFilter) -> { + collectChunkSections(lookup, chunkProvider.getLoadedChunk(pos.x, pos.z), playerSectionY, (section, isInFilter) -> { int yOffset = section.getYLocation(); BitArray array = (BitArray) ((IBlockStateContainer) section.getData()).getStorage(); collectBlockLocations(array, isInFilter, place -> blocks.add(new BlockPos( @@ -165,24 +167,38 @@ private Stream scanChunkInternal(IPlayerContext ctx, BlockOptionalMeta - private void collectChunkSections(BlockOptionalMetaLookup lookup, Chunk chunk, BiConsumer consumer) { - for (ExtendedBlockStorage section : chunk.getBlockStorageArray()) { - if (section == null || section.isEmpty()) { - continue; + private void collectChunkSections(BlockOptionalMetaLookup lookup, Chunk chunk, int playerSection, BiConsumer consumer) { + // iterate over sections relative to player + ExtendedBlockStorage[] sections = chunk.getBlockStorageArray(); + int l = sections.length; + int i = playerSection - 1; + int j = playerSection; + for (; i >= 0 || j < l; ++j, --i) { + if (j < l) { + visitSection(lookup, sections[j], consumer); } - - BlockStateContainer sectionContainer = section.getData(); - //this won't work if the PaletteStorage is of the type EmptyPaletteStorage - if (((IBlockStateContainer) sectionContainer).getStorage() == null) { - continue; + if (i >= 0) { + visitSection(lookup, sections[i], consumer); } + } + } - boolean[] isInFilter = getIncludedFilterIndices(lookup, ((IBlockStateContainer) sectionContainer).getPalette()); - if (isInFilter.length == 0) { - continue; - } - consumer.accept(section, isInFilter); + private void visitSection(BlockOptionalMetaLookup lookup, ExtendedBlockStorage section, BiConsumer consumer) { + if (section == null || section.isEmpty()) { + return; + } + + BlockStateContainer sectionContainer = section.getData(); + //this won't work if the PaletteStorage is of the type EmptyPaletteStorage + if (((IBlockStateContainer) sectionContainer).getStorage() == null) { + return; + } + + boolean[] isInFilter = getIncludedFilterIndices(lookup, ((IBlockStateContainer) sectionContainer).getPalette()); + if (isInFilter.length == 0) { + return; } + consumer.accept(section, isInFilter); } private boolean[] getIncludedFilterIndices(BlockOptionalMetaLookup lookup, IBlockStatePalette palette) { diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 807dbc303..137313de9 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -54,7 +54,7 @@ */ public final class MineProcess extends BaritoneProcessHelper implements IMineProcess { - private static final int ORE_LOCATIONS_COUNT = 64; + private static final int ORE_LOCATIONS_COUNT = 32; private BlockOptionalMetaLookup filter; private List knownOreLocations; From b71c9e776ac62cef47e2ec05f484195e850d5e52 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Wed, 28 Dec 2022 01:09:46 -0700 Subject: [PATCH 014/111] oops didn't mean to commit that --- 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 137313de9..807dbc303 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -54,7 +54,7 @@ */ public final class MineProcess extends BaritoneProcessHelper implements IMineProcess { - private static final int ORE_LOCATIONS_COUNT = 32; + private static final int ORE_LOCATIONS_COUNT = 64; private BlockOptionalMetaLookup filter; private List knownOreLocations; From 26cceede153a290926bc83e286ea874a6c5519a0 Mon Sep 17 00:00:00 2001 From: Entropy5 <44469915+Entropy5@users.noreply.github.com> Date: Tue, 17 Jan 2023 06:33:01 +0100 Subject: [PATCH 015/111] litematica support for buildonlyselection, mostly rycbars --- .../java/baritone/process/BuilderProcess.java | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index f3f138c96..14093dc6a 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -166,17 +166,21 @@ public boolean build(String name, File schematic, Vec3i origin) { return false; } + parsed = applyMapArtAndSelection(origin, parsed); + + build(name, parsed, origin); + return true; + } + + private ISchematic applyMapArtAndSelection(Vec3i origin, ISchematic schematic) { if (Baritone.settings().mapArtMode.value) { - parsed = new MapArtSchematic((IStaticSchematic) parsed); + schematic = new MapArtSchematic((IStaticSchematic) schematic); } if (Baritone.settings().buildOnlySelection.value) { - parsed = new SelectionSchematic(parsed, origin, baritone.getSelectionManager().getSelections()); + schematic = new SelectionSchematic(schematic, origin, baritone.getSelectionManager().getSelections()); } - - - build(name, parsed, origin); - return true; + return schematic; } @Override @@ -217,7 +221,8 @@ public void buildOpenLitematic(int i) { try { LitematicaSchematic schematic1 = new LitematicaSchematic(CompressedStreamTools.readCompressed(Files.newInputStream(LitematicaHelper.getSchematicFile(i).toPath())), false); Vec3i correctedOrigin = LitematicaHelper.getCorrectedOrigin(schematic1, i); - LitematicaSchematic schematic2 = LitematicaHelper.blackMagicFuckery(schematic1, i); + ISchematic schematic2 = LitematicaHelper.blackMagicFuckery(schematic1, i); + schematic2 = applyMapArtAndSelection(origin, schematic2); build(name, schematic2, correctedOrigin); } catch (IOException e) { logDirect("Schematic File could not be loaded."); From 7404414e7a180925502aa6ad1063a321f121cd3a Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Fri, 20 Jan 2023 23:43:00 -0700 Subject: [PATCH 016/111] less impure --- .../baritone/cache/FasterWorldScanner.java | 47 +++++++++++-------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index 9adbf76b0..a813e9119 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -25,6 +25,8 @@ import baritone.utils.accessor.IBitArray; import baritone.utils.accessor.IBlockStateContainer; import io.netty.buffer.Unpooled; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntList; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.network.PacketBuffer; @@ -126,6 +128,7 @@ public static List getChunkRange(int centerX, int centerZ, int chunkRa private List scanChunksInternal(IPlayerContext ctx, BlockOptionalMetaLookup lookup, List chunkPositions, int maxBlocks) { assert ctx.world() != null; try { + // p -> scanChunkInternal(ctx, lookup, p) Stream posStream = chunkPositions.parallelStream().flatMap(p -> scanChunkInternal(ctx, lookup, p)); if (maxBlocks >= 0) { // WARNING: this can be expensive if maxBlocks is large... @@ -151,39 +154,30 @@ private Stream scanChunkInternal(IPlayerContext ctx, BlockOptionalMeta int playerSectionY = ctx.playerFeet().y >> 4; - List blocks = new ArrayList<>(); - - collectChunkSections(lookup, chunkProvider.getLoadedChunk(pos.x, pos.z), playerSectionY, (section, isInFilter) -> { - int yOffset = section.getYLocation(); - BitArray array = (BitArray) ((IBlockStateContainer) section.getData()).getStorage(); - collectBlockLocations(array, isInFilter, place -> blocks.add(new BlockPos( - chunkX + ((place & 255) & 15), - yOffset + (place >> 8), - chunkZ + ((place & 255) >> 4) - ))); - }); - return blocks.stream(); + return collectChunkSections(lookup, chunkProvider.getLoadedChunk(pos.x, pos.z), chunkX, chunkZ, playerSectionY).stream(); } - private void collectChunkSections(BlockOptionalMetaLookup lookup, Chunk chunk, int playerSection, BiConsumer consumer) { + private List collectChunkSections(BlockOptionalMetaLookup lookup, Chunk chunk, long chunkX, long chunkZ, int playerSection) { // iterate over sections relative to player + List blocks = new ArrayList<>(); ExtendedBlockStorage[] sections = chunk.getBlockStorageArray(); int l = sections.length; int i = playerSection - 1; int j = playerSection; for (; i >= 0 || j < l; ++j, --i) { if (j < l) { - visitSection(lookup, sections[j], consumer); + visitSection(lookup, sections[j], blocks, chunkX, chunkZ); } if (i >= 0) { - visitSection(lookup, sections[i], consumer); + visitSection(lookup, sections[i], blocks, chunkX, chunkZ); } } + return blocks; } - private void visitSection(BlockOptionalMetaLookup lookup, ExtendedBlockStorage section, BiConsumer consumer) { + private void visitSection(BlockOptionalMetaLookup lookup, ExtendedBlockStorage section, List blocks, long chunkX, long chunkZ) { if (section == null || section.isEmpty()) { return; } @@ -198,7 +192,17 @@ private void visitSection(BlockOptionalMetaLookup lookup, ExtendedBlockStorage s if (isInFilter.length == 0) { return; } - consumer.accept(section, isInFilter); + + + int yOffset = section.getYLocation(); + BitArray array = ((IBlockStateContainer) section.getData()).getStorage(); + for (int place : collectBlockLocations(array, isInFilter)) { + blocks.add(new BlockPos( + chunkX + ((place & 255) & 15), + yOffset + (place >> 8), + chunkZ + ((place & 255) >> 4) + )); + } } private boolean[] getIncludedFilterIndices(BlockOptionalMetaLookup lookup, IBlockStatePalette palette) { @@ -224,12 +228,14 @@ private boolean[] getIncludedFilterIndices(BlockOptionalMetaLookup lookup, IBloc return isInFilter; } - private static void collectBlockLocations(BitArray array, boolean[] isInFilter, IntConsumer action) { + private static IntList collectBlockLocations(BitArray array, boolean[] isInFilter) { long[] longArray = array.getBackingLongArray(); int arraySize = array.size(); int bitsPerEntry = ((IBitArray) array).getBitsPerEntry(); long maxEntryValue = ((IBitArray) array).getMaxEntryValue(); + IntList positions = new IntArrayList(); + for (int idx = 0, kl = bitsPerEntry - 1; idx < arraySize; idx++, kl += bitsPerEntry) { final int i = idx * bitsPerEntry; final int j = i >> 6; @@ -239,14 +245,15 @@ private static void collectBlockLocations(BitArray array, boolean[] isInFilter, if (j == k) { if (isInFilter[(int) (jl & maxEntryValue)]) { - action.accept(idx); + positions.add(idx); } } else { if (isInFilter[(int) ((jl | longArray[k] << (64 - l)) & maxEntryValue)]) { - action.accept(idx); + positions.add(idx); } } } + return positions; } /** From 413cc1469f0fdcefd84952924fc182ba0e3c390b Mon Sep 17 00:00:00 2001 From: Entropy5 <44469915+Entropy5@users.noreply.github.com> Date: Fri, 27 Jan 2023 14:23:08 +0100 Subject: [PATCH 017/111] zac suggestion (number 2), test ongoing --- src/main/java/baritone/process/BuilderProcess.java | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 14093dc6a..85be6516a 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -157,7 +157,6 @@ public boolean build(String name, File schematic, Vec3i origin) { if (!format.isPresent()) { return false; } - ISchematic parsed; try { parsed = format.get().parse(new FileInputStream(schematic)); @@ -165,18 +164,16 @@ public boolean build(String name, File schematic, Vec3i origin) { e.printStackTrace(); return false; } - - parsed = applyMapArtAndSelection(origin, parsed); - + parsed = applyMapArtAndSelection(origin, (IStaticSchematic) parsed); build(name, parsed, origin); return true; } - private ISchematic applyMapArtAndSelection(Vec3i origin, ISchematic schematic) { + private ISchematic applyMapArtAndSelection(Vec3i origin, IStaticSchematic parsed) { + ISchematic schematic = parsed; if (Baritone.settings().mapArtMode.value) { - schematic = new MapArtSchematic((IStaticSchematic) schematic); + schematic = new MapArtSchematic(parsed); } - if (Baritone.settings().buildOnlySelection.value) { schematic = new SelectionSchematic(schematic, origin, baritone.getSelectionManager().getSelections()); } @@ -222,7 +219,7 @@ public void buildOpenLitematic(int i) { LitematicaSchematic schematic1 = new LitematicaSchematic(CompressedStreamTools.readCompressed(Files.newInputStream(LitematicaHelper.getSchematicFile(i).toPath())), false); Vec3i correctedOrigin = LitematicaHelper.getCorrectedOrigin(schematic1, i); ISchematic schematic2 = LitematicaHelper.blackMagicFuckery(schematic1, i); - schematic2 = applyMapArtAndSelection(origin, schematic2); + schematic2 = applyMapArtAndSelection(origin, (IStaticSchematic) schematic2); build(name, schematic2, correctedOrigin); } catch (IOException e) { logDirect("Schematic File could not be loaded."); From 334d9c119b6269e1896963905a214667eae24dcb Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Sat, 28 Jan 2023 00:44:54 -0700 Subject: [PATCH 018/111] remove the allocation of an intlist per section --- .../baritone/cache/FasterWorldScanner.java | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index a813e9119..4a41eaf10 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -196,13 +196,7 @@ private void visitSection(BlockOptionalMetaLookup lookup, ExtendedBlockStorage s int yOffset = section.getYLocation(); BitArray array = ((IBlockStateContainer) section.getData()).getStorage(); - for (int place : collectBlockLocations(array, isInFilter)) { - blocks.add(new BlockPos( - chunkX + ((place & 255) & 15), - yOffset + (place >> 8), - chunkZ + ((place & 255) >> 4) - )); - } + collectBlockLocations(array, isInFilter, blocks, chunkX, chunkZ, yOffset); } private boolean[] getIncludedFilterIndices(BlockOptionalMetaLookup lookup, IBlockStatePalette palette) { @@ -228,14 +222,12 @@ private boolean[] getIncludedFilterIndices(BlockOptionalMetaLookup lookup, IBloc return isInFilter; } - private static IntList collectBlockLocations(BitArray array, boolean[] isInFilter) { + private static void collectBlockLocations(BitArray array, boolean[] isInFilter, List blocks, long chunkX, long chunkZ, int yOffset) { long[] longArray = array.getBackingLongArray(); int arraySize = array.size(); int bitsPerEntry = ((IBitArray) array).getBitsPerEntry(); long maxEntryValue = ((IBitArray) array).getMaxEntryValue(); - IntList positions = new IntArrayList(); - for (int idx = 0, kl = bitsPerEntry - 1; idx < arraySize; idx++, kl += bitsPerEntry) { final int i = idx * bitsPerEntry; final int j = i >> 6; @@ -245,15 +237,24 @@ private static IntList collectBlockLocations(BitArray array, boolean[] isInFilte if (j == k) { if (isInFilter[(int) (jl & maxEntryValue)]) { - positions.add(idx); + //noinspection DuplicateExpressions + blocks.add(new BlockPos( + chunkX + ((idx & 255) & 15), + yOffset + (idx >> 8), + chunkZ + ((idx & 255) >> 4) + )); } } else { if (isInFilter[(int) ((jl | longArray[k] << (64 - l)) & maxEntryValue)]) { - positions.add(idx); + //noinspection DuplicateExpressions + blocks.add(new BlockPos( + chunkX + ((idx & 255) & 15), + yOffset + (idx >> 8), + chunkZ + ((idx & 255) >> 4) + )); } } } - return positions; } /** From 6de266a106534b06f73550846d51aacd436b6ec7 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Sat, 28 Jan 2023 01:39:58 -0700 Subject: [PATCH 019/111] remove extra method call --- .../baritone/cache/FasterWorldScanner.java | 55 +++++++++---------- 1 file changed, 26 insertions(+), 29 deletions(-) diff --git a/src/main/java/baritone/cache/FasterWorldScanner.java b/src/main/java/baritone/cache/FasterWorldScanner.java index 4a41eaf10..fbdc238ce 100644 --- a/src/main/java/baritone/cache/FasterWorldScanner.java +++ b/src/main/java/baritone/cache/FasterWorldScanner.java @@ -193,41 +193,15 @@ private void visitSection(BlockOptionalMetaLookup lookup, ExtendedBlockStorage s return; } - - int yOffset = section.getYLocation(); BitArray array = ((IBlockStateContainer) section.getData()).getStorage(); - collectBlockLocations(array, isInFilter, blocks, chunkX, chunkZ, yOffset); - } - - private boolean[] getIncludedFilterIndices(BlockOptionalMetaLookup lookup, IBlockStatePalette palette) { - boolean commonBlockFound = false; - ObjectIntIdentityMap paletteMap = getPalette(palette); - int size = paletteMap.size(); - - boolean[] isInFilter = new boolean[size]; - - for (int i = 0; i < size; i++) { - IBlockState state = paletteMap.getByValue(i); - if (lookup.has(state)) { - isInFilter[i] = true; - commonBlockFound = true; - } else { - isInFilter[i] = false; - } - } - - if (!commonBlockFound) { - return new boolean[0]; - } - return isInFilter; - } - - private static void collectBlockLocations(BitArray array, boolean[] isInFilter, List blocks, long chunkX, long chunkZ, int yOffset) { long[] longArray = array.getBackingLongArray(); int arraySize = array.size(); int bitsPerEntry = ((IBitArray) array).getBitsPerEntry(); long maxEntryValue = ((IBitArray) array).getMaxEntryValue(); + + int yOffset = section.getYLocation(); + for (int idx = 0, kl = bitsPerEntry - 1; idx < arraySize; idx++, kl += bitsPerEntry) { final int i = idx * bitsPerEntry; final int j = i >> 6; @@ -257,6 +231,29 @@ private static void collectBlockLocations(BitArray array, boolean[] isInFilter, } } + private boolean[] getIncludedFilterIndices(BlockOptionalMetaLookup lookup, IBlockStatePalette palette) { + boolean commonBlockFound = false; + ObjectIntIdentityMap paletteMap = getPalette(palette); + int size = paletteMap.size(); + + boolean[] isInFilter = new boolean[size]; + + for (int i = 0; i < size; i++) { + IBlockState state = paletteMap.getByValue(i); + if (lookup.has(state)) { + isInFilter[i] = true; + commonBlockFound = true; + } else { + isInFilter[i] = false; + } + } + + if (!commonBlockFound) { + return new boolean[0]; + } + return isInFilter; + } + /** * cheats to get the actual map of id -> blockstate from the various palette implementations */ From c1b58f8a0182ecdf10d5c56a5bec05aabbc119b5 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 18 Feb 2023 15:12:17 -0800 Subject: [PATCH 020/111] link 1.19 --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index e2c83ddec..5a59867d1 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Minecraft Minecraft Minecraft + Minecraft

@@ -64,6 +65,8 @@ If you need Forge or Fabric 1.17.1, look [here](https://github.com/cabaletta/bar If you need Forge or Fabric 1.18.2, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.8.3) and get the `api-forge` or `api-fabric` jar. **For 1.18.2 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.8.3/baritone-api-fabric-1.8.3.jar)**. **For 1.18.2 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.8.3/baritone-api-forge-1.8.3.jar)**. +If you need Forge or Fabric 1.19.3, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.9.1) and get the `api-forge` or `api-fabric` jar. **For 1.19.3 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar)**. **For 1.19.3 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar)**. + This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2 onwards. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). From b622adf3000fe4deba204f052c0ac7c530361f23 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 18 Feb 2023 15:13:15 -0800 Subject: [PATCH 021/111] ugh why was this changed since 1.18 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5a59867d1..d0fd1dc83 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ If you need Forge or Fabric 1.17.1, look [here](https://github.com/cabaletta/bar If you need Forge or Fabric 1.18.2, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.8.3) and get the `api-forge` or `api-fabric` jar. **For 1.18.2 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.8.3/baritone-api-fabric-1.8.3.jar)**. **For 1.18.2 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.8.3/baritone-api-forge-1.8.3.jar)**. -If you need Forge or Fabric 1.19.3, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.9.1) and get the `api-forge` or `api-fabric` jar. **For 1.19.3 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar)**. **For 1.19.3 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar)**. +If you need Forge or Fabric 1.19.3, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.9.1) and get the `api-forge` or `api-fabric` jar. **For 1.19.3 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-fabric-api-1.9.1.jar)**. **For 1.19.3 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-forge-api-1.9.1.jar)**. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2 onwards. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). From 814c17522a1a3dc4db0f465a4c4e3c0603e74527 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 18 Feb 2023 15:20:50 -0800 Subject: [PATCH 022/111] changed it back to the old way by manually renaming the release files --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d0fd1dc83..5a59867d1 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ If you need Forge or Fabric 1.17.1, look [here](https://github.com/cabaletta/bar If you need Forge or Fabric 1.18.2, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.8.3) and get the `api-forge` or `api-fabric` jar. **For 1.18.2 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.8.3/baritone-api-fabric-1.8.3.jar)**. **For 1.18.2 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.8.3/baritone-api-forge-1.8.3.jar)**. -If you need Forge or Fabric 1.19.3, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.9.1) and get the `api-forge` or `api-fabric` jar. **For 1.19.3 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-fabric-api-1.9.1.jar)**. **For 1.19.3 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-forge-api-1.9.1.jar)**. +If you need Forge or Fabric 1.19.3, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.9.1) and get the `api-forge` or `api-fabric` jar. **For 1.19.3 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar)**. **For 1.19.3 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar)**. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2 onwards. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). From 174bdd230742486dd858be2032255f59724a0e6e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 18 Feb 2023 16:42:05 -0800 Subject: [PATCH 023/111] overhaul readme --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 5a59867d1..0a511013b 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Minecraft Minecraft Minecraft - Minecraft + Minecraft Minecraft Minecraft

@@ -49,23 +49,23 @@ A Minecraft pathfinder bot. -[**Baritone Discord Server**](http://discord.gg/s6fRBAUpmr) - Baritone is the pathfinding system used in [Impact](https://impactclient.net/) since 4.4. There's a [showcase video](https://youtu.be/CZkLXWo4Fg4) made by @Adovin#0730 on Baritone which I recommend. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a (very old!) video I made showing off what it can do. -[Tutorial playlist](https://www.youtube.com/playlist?list=PLnwnJ1qsS7CoQl9Si-RTluuzCo_4Oulpa) - -The easiest way to install Baritone is to install [Impact](https://impactclient.net/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to -install the v1.2.* `api-forge` jar from [releases](https://github.com/cabaletta/baritone/releases). **For 1.12.2 Forge, just click -[here](https://github.com/cabaletta/baritone/releases/download/v1.2.17/baritone-api-forge-1.2.17.jar)**. Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. +[**Baritone Discord Server**](http://discord.gg/s6fRBAUpmr) -For 1.16.5, [click here](https://www.youtube.com/watch?v=_4eVJ9Qz2J8) and see description. If you need Forge or Fabric 1.16.5, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.6.3) and get the `api-forge` or `api-fabric` jar. **For 1.16.5 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.6.3/baritone-api-fabric-1.6.3.jar)**. +**Quick download links:** -If you need Forge or Fabric 1.17.1, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.7.2) and get the `api-forge` or `api-fabric` jar. **For 1.17.1 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.7.2/baritone-api-fabric-1.7.2.jar)**. +| Forge | Fabric | +|---------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------| +| [1.12.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.2.17/baritone-api-forge-1.2.17.jar) | | +| [1.16.5 Forge](https://github.com/cabaletta/baritone/releases/download/v1.6.4/baritone-api-forge-1.6.4.jar) | [1.16.5 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.6.4/baritone-api-fabric-1.6.4.jar) | +| [1.17.1 Forge](https://github.com/cabaletta/baritone/releases/download/v1.7.3/baritone-api-forge-1.7.3.jar) | [1.17.1 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.7.3/baritone-api-fabric-1.7.3.jar) | +| [1.18.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.8.4/baritone-api-forge-1.8.4.jar) | [1.18.2 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.8.4/baritone-api-fabric-1.8.4.jar) | +| [1.19.3 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar) | [1.19.3 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar) | -If you need Forge or Fabric 1.18.2, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.8.3) and get the `api-forge` or `api-fabric` jar. **For 1.18.2 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.8.3/baritone-api-fabric-1.8.3.jar)**. **For 1.18.2 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.8.3/baritone-api-forge-1.8.3.jar)**. +**How to immediately get started:** Type `#goto 1000 500` in chat to go to x=1000 z=500. Type `#mine diamond_ore` to mine diamond ore. Type `#stop` to stop. For more, read [the usage page](USAGE.md) and/or watch this [tutorial playlist](https://www.youtube.com/playlist?list=PLnwnJ1qsS7CoQl9Si-RTluuzCo_4Oulpa) -If you need Forge or Fabric 1.19.3, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.9.1) and get the `api-forge` or `api-fabric` jar. **For 1.19.3 Fabric, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar)**. **For 1.19.3 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar)**. +For other versions of Minecraft or more complicated situations or for development, see [Installation & setup](SETUP.md). Also consider just installing [Impact](https://impactclient.net/), which comes with Baritone and is easier to install than wrangling with version JSONs and zips. For 1.16.5, [click here](https://www.youtube.com/watch?v=_4eVJ9Qz2J8) and see description. Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2 onwards. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). From f1ead19b6e0ea41e7a2343d56b4dcab417140725 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 28 Feb 2023 23:44:33 -0800 Subject: [PATCH 024/111] option to only move inventory when stationary --- src/api/java/baritone/api/Settings.java | 10 +++ src/main/java/baritone/Baritone.java | 6 ++ .../baritone/behavior/InventoryBehavior.java | 38 ++++++-- .../java/baritone/process/BuilderProcess.java | 5 +- .../process/InventoryPauserProcess.java | 90 +++++++++++++++++++ 5 files changed, 141 insertions(+), 8 deletions(-) create mode 100644 src/main/java/baritone/process/InventoryPauserProcess.java diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 9e3e6a385..38661d8be 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -69,6 +69,16 @@ public final class Settings { */ public final Setting allowInventory = new Setting<>(false); + /** + * Wait this many ticks between InventoryBehavior moving inventory items + */ + public final Setting ticksBetweenInventoryMoves = new Setting<>(1); + + /** + * Come to a halt before doing any inventory moves. Intended for anticheat such as 2b2t + */ + public final Setting inventoryMoveOnlyIfStationary = new Setting<>(false); + /** * Disable baritone's auto-tool at runtime, but still assume that another mod will provide auto tool functionality *

diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 71c2c455a..61db54211 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -80,6 +80,7 @@ public class Baritone implements IBaritone { private ExploreProcess exploreProcess; private BackfillProcess backfillProcess; private FarmProcess farmProcess; + private InventoryPauserProcess inventoryPauserProcess; private PathingControlManager pathingControlManager; private SelectionManager selectionManager; @@ -115,6 +116,7 @@ public class Baritone implements IBaritone { this.pathingControlManager.registerProcess(exploreProcess = new ExploreProcess(this)); this.pathingControlManager.registerProcess(backfillProcess = new BackfillProcess(this)); this.pathingControlManager.registerProcess(farmProcess = new FarmProcess(this)); + this.pathingControlManager.registerProcess(inventoryPauserProcess = new InventoryPauserProcess(this)); } this.worldProvider = new WorldProvider(); @@ -183,6 +185,10 @@ public FarmProcess getFarmProcess() { return this.farmProcess; } + public InventoryPauserProcess getInventoryPauserProcess() { + return this.inventoryPauserProcess; + } + @Override public PathingBehavior getPathingBehavior() { return this.pathingBehavior; diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 3dce5c0b5..93dc200cc 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -19,6 +19,7 @@ import baritone.Baritone; import baritone.api.event.events.TickEvent; +import baritone.api.utils.Helper; import baritone.utils.ToolSet; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -34,7 +35,10 @@ import java.util.Random; import java.util.function.Predicate; -public final class InventoryBehavior extends Behavior { +public final class InventoryBehavior extends Behavior implements Helper { + + int ticksSinceLastInventoryMove; + int[] lastTickRequestedMove; // not everything asks every tick, so remember the request while coming to a halt public InventoryBehavior(Baritone baritone) { super(baritone); @@ -52,20 +56,28 @@ public void onTick(TickEvent event) { // we have a crafting table or a chest or something open return; } + ticksSinceLastInventoryMove++; if (firstValidThrowaway() >= 9) { // aka there are none on the hotbar, but there are some in main inventory - swapWithHotBar(firstValidThrowaway(), 8); + requestSwapWithHotBar(firstValidThrowaway(), 8); } int pick = bestToolAgainst(Blocks.STONE, ItemPickaxe.class); if (pick >= 9) { - swapWithHotBar(pick, 0); + requestSwapWithHotBar(pick, 0); + } + if (lastTickRequestedMove != null) { + logDebug("Remembering to move " + lastTickRequestedMove[0] + " " + lastTickRequestedMove[1] + " from a previous tick"); + requestSwapWithHotBar(lastTickRequestedMove[0], lastTickRequestedMove[1]); } } - public void attemptToPutOnHotbar(int inMainInvy, Predicate disallowedHotbar) { + public boolean attemptToPutOnHotbar(int inMainInvy, Predicate disallowedHotbar) { OptionalInt destination = getTempHotbarSlot(disallowedHotbar); if (destination.isPresent()) { - swapWithHotBar(inMainInvy, destination.getAsInt()); + if (!requestSwapWithHotBar(inMainInvy, destination.getAsInt())) { + return false; + } } + return true; } public OptionalInt getTempHotbarSlot(Predicate disallowedHotbar) { @@ -89,8 +101,20 @@ public OptionalInt getTempHotbarSlot(Predicate disallowedHotbar) { return OptionalInt.of(candidates.get(new Random().nextInt(candidates.size()))); } - private void swapWithHotBar(int inInventory, int inHotbar) { + private boolean requestSwapWithHotBar(int inInventory, int inHotbar) { + lastTickRequestedMove = new int[]{inInventory, inHotbar}; + if (ticksSinceLastInventoryMove < Baritone.settings().ticksBetweenInventoryMoves.value) { + logDebug("Inventory move requested but delaying " + ticksSinceLastInventoryMove + " " + Baritone.settings().ticksBetweenInventoryMoves.value); + return false; + } + if (Baritone.settings().inventoryMoveOnlyIfStationary.value && !baritone.getInventoryPauserProcess().stationaryForInventoryMove()) { + logDebug("Inventory move requested but delaying until stationary"); + return false; + } ctx.playerController().windowClick(ctx.player().inventoryContainer.windowId, inInventory < 9 ? inInventory + 36 : inInventory, inHotbar, ClickType.SWAP, ctx.player()); + ticksSinceLastInventoryMove = 0; + lastTickRequestedMove = null; + return true; } private int firstValidThrowaway() { // TODO offhand idk @@ -192,8 +216,8 @@ public boolean throwaway(boolean select, Predicate desired, b if (allowInventory) { for (int i = 9; i < 36; i++) { if (desired.test(inv.get(i))) { - swapWithHotBar(i, 7); if (select) { + requestSwapWithHotBar(i, 7); p.inventory.currentItem = 7; } return true; diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 85be6516a..c7868a4a0 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -562,7 +562,10 @@ public int lengthZ() { for (int i = 9; i < 36; i++) { for (IBlockState desired : noValidHotbarOption) { if (valid(approxPlaceable.get(i), desired, true)) { - baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains); + if (!baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains)) { + // awaiting inventory move, so pause + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } break outer; } } diff --git a/src/main/java/baritone/process/InventoryPauserProcess.java b/src/main/java/baritone/process/InventoryPauserProcess.java new file mode 100644 index 000000000..ab210532b --- /dev/null +++ b/src/main/java/baritone/process/InventoryPauserProcess.java @@ -0,0 +1,90 @@ +/* + * 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.process.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.utils.BaritoneProcessHelper; + +public class InventoryPauserProcess extends BaritoneProcessHelper { + + boolean pauseRequestedLastTick; + boolean safeToCancelLastTick; + int ticksOfStationary; + + public InventoryPauserProcess(Baritone baritone) { + super(baritone); + } + + @Override + public boolean isActive() { + if (mc.player == null || mc.world == null) { + return false; + } + return true; + } + + private double motion() { + return Math.sqrt(mc.player.motionX * mc.player.motionX + mc.player.motionZ * mc.player.motionZ); + } + + private boolean stationaryNow() { + return motion() < 0.00001; + } + + public boolean stationaryForInventoryMove() { + pauseRequestedLastTick = true; + return safeToCancelLastTick && ticksOfStationary > 1; + } + + @Override + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + //logDebug(pauseRequestedLastTick + " " + safeToCancelLastTick + " " + ticksOfStationary); + safeToCancelLastTick = isSafeToCancel; + if (pauseRequestedLastTick) { + pauseRequestedLastTick = false; + if (stationaryNow()) { + ticksOfStationary++; + } + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + ticksOfStationary = 0; + return new PathingCommand(null, PathingCommandType.DEFER); + } + + @Override + public void onLostControl() { + + } + + @Override + public String displayName0() { + return "inventory pauser"; + } + + @Override + public double priority() { + return 5.1; // slightly higher than backfill + } + + @Override + public boolean isTemporary() { + return true; + } +} From c9d7a5bea61ae28aeeb5e01e7520217fd487b371 Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 28 Feb 2023 23:56:34 -0800 Subject: [PATCH 025/111] kami blue to lambda --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0a511013b..0aec1468d 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@

Impact integration - KAMI Blue integration + Lambda integration ForgeHax integration Aristois add-on integration rootNET integration From 790a4f6769f462dd1fb92d64b2f5855f10c86dce Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 1 Mar 2023 00:25:30 -0800 Subject: [PATCH 026/111] command to load settings from a specific file --- src/api/java/baritone/api/BaritoneAPI.java | 2 +- .../java/baritone/api/utils/SettingsUtil.java | 22 +++++++++++-------- .../baritone/command/defaults/SetCommand.java | 18 +++++++++++++-- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index 53937bd80..935bf9e4f 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -35,7 +35,7 @@ public final class BaritoneAPI { static { settings = new Settings(); - SettingsUtil.readAndApply(settings); + SettingsUtil.readAndApply(settings, SettingsUtil.SETTINGS_DEFAULT_NAME); ServiceLoader baritoneLoader = ServiceLoader.load(IBaritoneProvider.class); Iterator instances = baritoneLoader.iterator(); diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index f47f515a8..50e2363a6 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -48,7 +48,7 @@ public class SettingsUtil { - private static final Path SETTINGS_PATH = getMinecraft().gameDir.toPath().resolve("baritone").resolve("settings.txt"); + public static final String SETTINGS_DEFAULT_NAME = "settings.txt"; private static final Pattern SETTING_PATTERN = Pattern.compile("^(?[^ ]+) +(?.+)"); // key and value split by the first space private static final String[] JAVA_ONLY_SETTINGS = {"logger", "notifier", "toaster"}; @@ -68,12 +68,12 @@ private static void forEachLine(Path file, Consumer consumer) throws IOE } } - public static void readAndApply(Settings settings) { + public static void readAndApply(Settings settings, String settingsName) { try { - forEachLine(SETTINGS_PATH, line -> { + forEachLine(settingsByName(settingsName), line -> { Matcher matcher = SETTING_PATTERN.matcher(line); if (!matcher.matches()) { - System.out.println("Invalid syntax in setting file: " + line); + Helper.HELPER.logDirect("Invalid syntax in setting file: " + line); return; } @@ -82,29 +82,33 @@ public static void readAndApply(Settings settings) { try { parseAndApply(settings, settingName, settingValue); } catch (Exception ex) { - System.out.println("Unable to parse line " + line); + Helper.HELPER.logDirect("Unable to parse line " + line); ex.printStackTrace(); } }); } catch (NoSuchFileException ignored) { - System.out.println("Baritone settings file not found, resetting."); + Helper.HELPER.logDirect("Baritone settings file not found, resetting."); } catch (Exception ex) { - System.out.println("Exception while reading Baritone settings, some settings may be reset to default values!"); + Helper.HELPER.logDirect("Exception while reading Baritone settings, some settings may be reset to default values!"); ex.printStackTrace(); } } public static synchronized void save(Settings settings) { - try (BufferedWriter out = Files.newBufferedWriter(SETTINGS_PATH)) { + try (BufferedWriter out = Files.newBufferedWriter(settingsByName(SETTINGS_DEFAULT_NAME))) { for (Settings.Setting setting : modifiedSettings(settings)) { out.write(settingToString(setting) + "\n"); } } catch (Exception ex) { - System.out.println("Exception thrown while saving Baritone settings!"); + Helper.HELPER.logDirect("Exception thrown while saving Baritone settings!"); ex.printStackTrace(); } } + private static Path settingsByName(String name) { + return getMinecraft().gameDir.toPath().resolve("baritone").resolve(name); + } + public static List modifiedSettings(Settings settings) { List modified = new ArrayList<>(); for (Settings.Setting setting : settings.allSettings) { diff --git a/src/main/java/baritone/command/defaults/SetCommand.java b/src/main/java/baritone/command/defaults/SetCommand.java index fd9bb0457..255dd6b28 100644 --- a/src/main/java/baritone/command/defaults/SetCommand.java +++ b/src/main/java/baritone/command/defaults/SetCommand.java @@ -57,6 +57,18 @@ public void execute(String label, IArgConsumer args) throws CommandException { logDirect("Settings saved"); return; } + if (Arrays.asList("load", "ld").contains(arg)) { + String file = SETTINGS_DEFAULT_NAME; + if (args.hasAny()) { + file = args.getString(); + } + // reset to defaults + SettingsUtil.modifiedSettings(Baritone.settings()).forEach(Settings.Setting::reset); + // then load from disk + SettingsUtil.readAndApply(Baritone.settings(), file); + logDirect("Settings reloaded from " + file); + return; + } boolean viewModified = Arrays.asList("m", "mod", "modified").contains(arg); boolean viewAll = Arrays.asList("all", "l", "list").contains(arg); boolean paginate = viewModified || viewAll; @@ -228,7 +240,7 @@ public Stream tabComplete(String label, IArgConsumer args) throws Comman return new TabCompleteHelper() .addSettings() .sortAlphabetically() - .prepend("list", "modified", "reset", "toggle", "save") + .prepend("list", "modified", "reset", "toggle", "save", "load") .filterPrefix(arg) .stream(); } @@ -255,7 +267,9 @@ public List getLongDesc() { "> set reset all - Reset ALL SETTINGS to their defaults", "> set reset - Reset a setting to its default", "> set toggle - Toggle a boolean setting", - "> set save - Save all settings (this is automatic tho)" + "> set save - Save all settings (this is automatic tho)", + "> set load - Load settings from settings.txt", + "> set load [filename] - Load settings from another file in your minecraft/baritone" ); } } From 6698505dd83b239f67d5ca459196d011c852ed49 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Mon, 13 Mar 2023 15:31:18 -0700 Subject: [PATCH 027/111] make wp c not throw npe on invalid tag name --- .../java/baritone/command/defaults/WaypointsCommand.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/command/defaults/WaypointsCommand.java b/src/main/java/baritone/command/defaults/WaypointsCommand.java index cf420e90a..3016745e1 100644 --- a/src/main/java/baritone/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/command/defaults/WaypointsCommand.java @@ -149,7 +149,11 @@ public void execute(String label, IArgConsumer args) throws CommandException { logDirect(component); } else if (action == Action.CLEAR) { args.requireMax(1); - IWaypoint.Tag tag = IWaypoint.Tag.getByName(args.getString()); + String name = args.getString(); + IWaypoint.Tag tag = IWaypoint.Tag.getByName(name); + if (tag == null) { + throw new CommandInvalidStateException("Invalid tag, \"" + name + "\""); + } IWaypoint[] waypoints = ForWaypoints.getWaypointsByTag(this.baritone, tag); for (IWaypoint waypoint : waypoints) { ForWaypoints.waypoints(this.baritone).removeWaypoint(waypoint); From 3200d976d732a9920a5c650f450265e95ecc3ef0 Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 14 Mar 2023 18:35:15 -0700 Subject: [PATCH 028/111] 1.19.4 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0aec1468d..3cf5402e9 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ Baritone is the pathfinding system used in [Impact](https://impactclient.net/) s | [1.17.1 Forge](https://github.com/cabaletta/baritone/releases/download/v1.7.3/baritone-api-forge-1.7.3.jar) | [1.17.1 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.7.3/baritone-api-fabric-1.7.3.jar) | | [1.18.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.8.4/baritone-api-forge-1.8.4.jar) | [1.18.2 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.8.4/baritone-api-fabric-1.8.4.jar) | | [1.19.3 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar) | [1.19.3 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar) | +| | [1.19.4 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.2/baritone-api-fabric-1.9.2.jar) | **How to immediately get started:** Type `#goto 1000 500` in chat to go to x=1000 z=500. Type `#mine diamond_ore` to mine diamond ore. Type `#stop` to stop. For more, read [the usage page](USAGE.md) and/or watch this [tutorial playlist](https://www.youtube.com/playlist?list=PLnwnJ1qsS7CoQl9Si-RTluuzCo_4Oulpa) From ff1732011ed8cc9642a3d92bfe62e31d10a51708 Mon Sep 17 00:00:00 2001 From: leijurv Date: Mon, 20 Mar 2023 22:07:51 -0700 Subject: [PATCH 029/111] vid is outdated and doesn't get to the point fast enough, so let's move it lower down --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3cf5402e9..7a35e1199 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ A Minecraft pathfinder bot. -Baritone is the pathfinding system used in [Impact](https://impactclient.net/) since 4.4. There's a [showcase video](https://youtu.be/CZkLXWo4Fg4) made by @Adovin#0730 on Baritone which I recommend. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a (very old!) video I made showing off what it can do. +Baritone is the pathfinding system used in [Impact](https://impactclient.net/) since 4.4. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a (very old!) video I made showing off what it can do. [**Baritone Discord Server**](http://discord.gg/s6fRBAUpmr) @@ -66,7 +66,7 @@ Baritone is the pathfinding system used in [Impact](https://impactclient.net/) s **How to immediately get started:** Type `#goto 1000 500` in chat to go to x=1000 z=500. Type `#mine diamond_ore` to mine diamond ore. Type `#stop` to stop. For more, read [the usage page](USAGE.md) and/or watch this [tutorial playlist](https://www.youtube.com/playlist?list=PLnwnJ1qsS7CoQl9Si-RTluuzCo_4Oulpa) -For other versions of Minecraft or more complicated situations or for development, see [Installation & setup](SETUP.md). Also consider just installing [Impact](https://impactclient.net/), which comes with Baritone and is easier to install than wrangling with version JSONs and zips. For 1.16.5, [click here](https://www.youtube.com/watch?v=_4eVJ9Qz2J8) and see description. Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. +For other versions of Minecraft or more complicated situations or for development, see [Installation & setup](SETUP.md). Also consider just installing [Impact](https://impactclient.net/), which comes with Baritone and is easier to install than wrangling with version JSONs and zips. For 1.16.5, [click here](https://www.youtube.com/watch?v=_4eVJ9Qz2J8) and see description. Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. There's a [showcase video](https://youtu.be/CZkLXWo4Fg4) made by @Adovin#6313 on Baritone which I recommend. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2 onwards. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). From f334b3b76572d6aa2bfdf643c0c957103441b201 Mon Sep 17 00:00:00 2001 From: Wagyourtail Date: Mon, 10 Apr 2023 18:40:48 -0700 Subject: [PATCH 030/111] update setup.md --- SETUP.md | 67 +++++--------------------------------------------------- 1 file changed, 6 insertions(+), 61 deletions(-) diff --git a/SETUP.md b/SETUP.md index 57866b192..1daeb9f89 100644 --- a/SETUP.md +++ b/SETUP.md @@ -43,13 +43,13 @@ If another one of your Forge mods has a Baritone integration, you want `baritone ## Command Line On Mac OSX and Linux, use `./gradlew` instead of `gradlew`. -If you have errors with a package missing please make sure you have setup your environment, and are using Oracle JDK 8 for 1.12.2-1.16.5, JDK 16 for 1.17.1, and JDK 17 for 1.18.1. +If you have errors with a package missing please make sure you have setup your environment, and are using Oracle JDK 8 for 1.12.2-1.16.5, JDK 16+ for 1.17.1, and JDK 17+ for 1.18.1. To check which java you are using do `java -version` in a command prompt or terminal. If you are using anything above OpenJDK 8 for 1.12.2-1.16.5, it might not work because the Java distributions above JDK 8 using may not have the needed javax classes. -Open JDK download: https://openjdk.java.net/install/ +Download java: https://adoptium.net/ #### macOS guide In order to get JDK 8, Try running the following command: `% /usr/libexec/java_home -V` @@ -66,68 +66,13 @@ In order to get JDK 8 running in the **current terminal window** you will have t To add OpenJDK 8 to your PATH add the export line to the end of your `.zshrc / .bashrc` if you want it to apply to each new terminal. If you're using bash change the .bachrc and if you're using zsh change the .zshrc -Setting up the Environment: +### Building Baritone -``` -$ gradlew setupDecompWorkspace -$ gradlew --refresh-dependencies -``` +These tasks depend on the minecraft version, but are (for the most part) standard for building mods. -Building Baritone: - -``` -$ gradlew build -``` - -For minecraft 1.15.2+, run the following instead to include the Forge jars: - -``` -$ gradlew build -Pbaritone.forge_build -``` - -Do this instead for Fabric jars: - -``` -$ gradlew build -Pbaritone.fabric_build -``` - -Running Baritone: - -``` -$ gradlew runClient -``` - -For information on how to build baritone, see [Building Baritone](#building-baritone) +for more details, see [the build ci action](/.github/workflows/gradle_build.yml) ## IntelliJ - Open the project in IntelliJ as a Gradle project - - ![Image](https://i.imgur.com/jw7Q6vY.png) - -- Run the Gradle tasks `setupDecompWorkspace` then `genIntellijRuns` - - ![Image](https://i.imgur.com/QEfVvWP.png) - - Refresh the Gradle project (or, to be safe, just restart IntelliJ) - - ![Image](https://i.imgur.com/3V7EdWr.png) - -- Select the "Minecraft Client" launch config - - ![Image](https://i.imgur.com/1qz2QGV.png) - -- Click on ``Edit Configurations...`` from the same dropdown and select the "Minecraft Client" config - - ![Image](https://i.imgur.com/s4ly0ZF.png) - -- In `Edit Configurations...` you need to select `baritone_launch` for `Use classpath of module:`. - - ![Image](https://i.imgur.com/hrLhG9u.png) - -## IntelliJ - -- Navigate to the gradle tasks on the right tab as follows - - ![Image](https://i.imgur.com/PE6r9iN.png) - -- Double click on **build** to run it +- depending on the minecraft version, you may need to run `setupDecompWorkspace` or `genIntellijRuns` in order to get everything working \ No newline at end of file From 35ab687d5e7ba76128571a24f985c90e7849a6ab Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 11 Apr 2023 16:00:22 -0700 Subject: [PATCH 031/111] 1.9.3 download links --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7a35e1199..f54584118 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ Baritone is the pathfinding system used in [Impact](https://impactclient.net/) s | [1.17.1 Forge](https://github.com/cabaletta/baritone/releases/download/v1.7.3/baritone-api-forge-1.7.3.jar) | [1.17.1 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.7.3/baritone-api-fabric-1.7.3.jar) | | [1.18.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.8.4/baritone-api-forge-1.8.4.jar) | [1.18.2 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.8.4/baritone-api-fabric-1.8.4.jar) | | [1.19.3 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar) | [1.19.3 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar) | -| | [1.19.4 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.2/baritone-api-fabric-1.9.2.jar) | +| [1.19.4 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-forge-1.9.3.jar) | [1.19.4 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-fabric-1.9.3.jar) | **How to immediately get started:** Type `#goto 1000 500` in chat to go to x=1000 z=500. Type `#mine diamond_ore` to mine diamond ore. Type `#stop` to stop. For more, read [the usage page](USAGE.md) and/or watch this [tutorial playlist](https://www.youtube.com/playlist?list=PLnwnJ1qsS7CoQl9Si-RTluuzCo_4Oulpa) From 5f2eadbfa663909ceb41073c021f2934c56ceb56 Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 11 Apr 2023 20:36:29 -0700 Subject: [PATCH 032/111] download links for 1.19.2 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f54584118..8ae8090d7 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ Baritone is the pathfinding system used in [Impact](https://impactclient.net/) s | [1.16.5 Forge](https://github.com/cabaletta/baritone/releases/download/v1.6.4/baritone-api-forge-1.6.4.jar) | [1.16.5 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.6.4/baritone-api-fabric-1.6.4.jar) | | [1.17.1 Forge](https://github.com/cabaletta/baritone/releases/download/v1.7.3/baritone-api-forge-1.7.3.jar) | [1.17.1 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.7.3/baritone-api-fabric-1.7.3.jar) | | [1.18.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.8.4/baritone-api-forge-1.8.4.jar) | [1.18.2 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.8.4/baritone-api-fabric-1.8.4.jar) | +| [1.19.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.4/baritone-api-forge-1.9.4.jar) | [1.19.2 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.4/baritone-api-fabric-1.9.4.jar) | | [1.19.3 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar) | [1.19.3 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar) | | [1.19.4 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-forge-1.9.3.jar) | [1.19.4 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-fabric-1.9.3.jar) | From e8a4a9fdac983a5270595a6e89dc9cad480cd988 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Mon, 24 Apr 2023 16:23:38 +0200 Subject: [PATCH 033/111] Make cocoa farmable --- .../java/baritone/process/FarmProcess.java | 51 ++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index 73c575d22..a9188299c 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -21,6 +21,7 @@ import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; +import baritone.api.pathing.goals.GoalGetToBlock; import baritone.api.pathing.goals.GoalComposite; import baritone.api.process.IFarmProcess; import baritone.api.process.PathingCommand; @@ -119,6 +120,7 @@ private enum Harvest { PUMPKIN(Blocks.PUMPKIN, state -> true), MELON(Blocks.MELON_BLOCK, state -> true), NETHERWART(Blocks.NETHER_WART, state -> state.getValue(BlockNetherWart.AGE) >= 3), + COCOA(Blocks.COCOA, state -> state.getValue(BlockCocoa.AGE) >= 2), SUGARCANE(Blocks.REEDS, null) { @Override public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { @@ -176,6 +178,10 @@ private boolean isNetherWart(ItemStack stack) { return !stack.isEmpty() && stack.getItem().equals(Items.NETHER_WART); } + private boolean isCocoa(ItemStack stack) { + return !stack.isEmpty() && stack.getItem() instanceof ItemDye && EnumDyeColor.byDyeDamage(stack.getMetadata()) == EnumDyeColor.BROWN; + } + @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { ArrayList scan = new ArrayList<>(); @@ -184,6 +190,7 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { } if (Baritone.settings().replantCrops.value) { scan.add(Blocks.FARMLAND); + scan.add(Blocks.LOG); if (Baritone.settings().replantNetherWart.value) { scan.add(Blocks.SOUL_SAND); } @@ -199,6 +206,7 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { List openFarmland = new ArrayList<>(); List bonemealable = new ArrayList<>(); List openSoulsand = new ArrayList<>(); + List openLog = new ArrayList<>(); for (BlockPos pos : locations) { //check if the target block is out of range. if (range != 0 && pos.getDistance(center.getX(), center.getY(), center.getZ()) > range) { @@ -219,6 +227,19 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { } continue; } + if (state.getBlock() == Blocks.LOG) { + // yes, both log blocks and the planks block define separate properties but share the enum + if (state.getValue(BlockOldLog.VARIANT) != BlockPlanks.EnumType.JUNGLE) { + continue; + } + for (EnumFacing direction : EnumFacing.Plane.HORIZONTAL) { + if (ctx.world().getBlockState(pos.offset(direction)).getBlock() instanceof BlockAir) { + openLog.add(pos); + break; + } + } + continue; + } if (readyForHarvest(ctx.world(), pos, state)) { toBreak.add(pos); continue; @@ -259,6 +280,25 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { } } } + for (BlockPos pos : openLog) { + for (EnumFacing dir : EnumFacing.Plane.HORIZONTAL) { + if (!(ctx.world().getBlockState(pos.offset(dir)).getBlock() instanceof BlockAir)) { + continue; + } + Vec3d faceCenter = new Vec3d(pos).add(0.5, 0.5, 0.5).add(new Vec3d(dir.getDirectionVec()).scale(0.5)); + Optional rot = RotationUtils.reachableOffset(ctx.player(), pos, faceCenter, ctx.playerController().getBlockReachDistance(), false); + if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, this::isCocoa)) { + RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance()); + if (result.typeOfHit == RayTraceResult.Type.BLOCK && result.sideHit == dir) { + baritone.getLookBehavior().updateTarget(rot.get(), true); + if (ctx.isLookingAt(pos)) { + baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); + } + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + } + } + } for (BlockPos pos : bonemealable) { Optional rot = RotationUtils.reachable(ctx, pos); if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, this::isBoneMeal)) { @@ -293,6 +333,15 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { goalz.add(new GoalBlock(pos.up())); } } + if (baritone.getInventoryBehavior().throwaway(false, this::isCocoa)) { + for (BlockPos pos : openLog) { + for (EnumFacing direction : EnumFacing.Plane.HORIZONTAL) { + if (ctx.world().getBlockState(pos.offset(direction)).getBlock() instanceof BlockAir) { + goalz.add(new GoalGetToBlock(pos.offset(direction))); + } + } + } + } if (baritone.getInventoryBehavior().throwaway(false, this::isBoneMeal)) { for (BlockPos pos : bonemealable) { goalz.add(new GoalBlock(pos)); @@ -301,7 +350,7 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { for (Entity entity : ctx.world().loadedEntityList) { if (entity instanceof EntityItem && entity.onGround) { EntityItem ei = (EntityItem) entity; - if (PICKUP_DROPPED.contains(ei.getItem().getItem())) { + if (PICKUP_DROPPED.contains(ei.getItem().getItem()) || isCocoa(ei.getItem())) { // +0.1 because of farmland's 0.9375 dummy height lol goalz.add(new GoalBlock(new BlockPos(entity.posX, entity.posY + 0.1, entity.posZ))); } From e4cd35ac3391ca6b0e9993e4cd0dd1d34ffc9a12 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Mon, 24 Apr 2023 13:15:06 +0200 Subject: [PATCH 034/111] =?UTF-8?q?=E2=9C=A8=20Add=20maxYLevelWhileMining?= =?UTF-8?q?=20setting?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/java/baritone/api/Settings.java | 5 +++++ src/main/java/baritone/process/MineProcess.java | 2 ++ 2 files changed, 7 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 38661d8be..c13cde2f7 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -853,6 +853,11 @@ public final class Settings { */ public final Setting minYLevelWhileMining = new Setting<>(0); + /** + * Sets the maximum y level to mine ores at. + */ + public final Setting maxYLevelWhileMining = new Setting<>(255); // 1.17+ defaults to maximum possible world height + /** * This will only allow baritone to mine exposed ores, can be used to stop ore obfuscators on servers that use them. */ diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 9af09a819..6880dd86c 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -437,6 +437,8 @@ private static List prune(CalculationContext ctx, List locs2 .filter(pos -> pos.getY() >= Baritone.settings().minYLevelWhileMining.value) + .filter(pos -> pos.getY() <= Baritone.settings().maxYLevelWhileMining.value) + .filter(pos -> !blacklist.contains(pos)) .sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().player()::getDistanceSq)) From 271c2ff636ce1e6504cff363589008f9802a9633 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Mon, 24 Apr 2023 22:38:12 +0200 Subject: [PATCH 035/111] Extend BlockOptionalMeta parsing to parse block properties --- .../baritone/api/utils/BlockOptionalMeta.java | 57 +++++++++++++++---- 1 file changed, 46 insertions(+), 11 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index e0f491fba..9864d5144 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -19,6 +19,7 @@ import baritone.api.utils.accessor.IItemStack; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableMap; import net.minecraft.block.*; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; @@ -36,21 +37,24 @@ import java.util.stream.Collectors; public final class BlockOptionalMeta { + // id:meta or id[] or id[properties] where id and properties are any text with at least one character and meta is a one or two digit number + private static final Pattern PATTERN = Pattern.compile("^(?.+?)(?::(?\\d\\d?)|\\[(?.+?)?\\])?$"); private final Block block; private final int meta; private final boolean noMeta; + private final String propertiesDescription; // exists so toString() can return something more useful than a list of all blockstates private final Set blockstates; private final Set stateHashes; private final Set stackHashes; - private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); private static final Map normalizations; public BlockOptionalMeta(@Nonnull Block block, @Nullable Integer meta) { this.block = block; this.noMeta = meta == null; this.meta = noMeta ? 0 : meta; - this.blockstates = getStates(block, meta); + this.propertiesDescription = "{}"; + this.blockstates = getStates(block, meta, Collections.emptyMap()); this.stateHashes = getStateHashes(blockstates); this.stackHashes = getStackHashes(blockstates); } @@ -60,24 +64,27 @@ public BlockOptionalMeta(@Nonnull Block block) { } public BlockOptionalMeta(@Nonnull String selector) { - Matcher matcher = pattern.matcher(selector); + Matcher matcher = PATTERN.matcher(selector); if (!matcher.find()) { throw new IllegalArgumentException("invalid block selector"); } - MatchResult matchResult = matcher.toMatchResult(); - noMeta = matchResult.group(2) == null; + noMeta = matcher.group("meta") == null; - ResourceLocation id = new ResourceLocation(matchResult.group(1)); + ResourceLocation id = new ResourceLocation(matcher.group("id")); if (!Block.REGISTRY.containsKey(id)) { throw new IllegalArgumentException("Invalid block ID"); } - block = Block.REGISTRY.getObject(id); - meta = noMeta ? 0 : Integer.parseInt(matchResult.group(2)); - blockstates = getStates(block, getMeta()); + + String props = matcher.group("properties"); + Map, ?> properties = props == null || props.equals("") ? Collections.emptyMap() : parseProperties(block, props); + + propertiesDescription = props == null ? "{}" : "{" + props.replace("=", ":") + "}"; + meta = noMeta ? 0 : Integer.parseInt(matcher.group("meta")); + blockstates = getStates(block, getMeta(), properties); stateHashes = getStateHashes(blockstates); stackHashes = getStackHashes(blockstates); } @@ -243,9 +250,32 @@ public static int stateMeta(IBlockState state) { return state.getBlock().getMetaFromState(normalize(state)); } - private static Set getStates(@Nonnull Block block, @Nullable Integer meta) { + private static Map, ?> parseProperties(Block block, String raw) { + ImmutableMap.Builder, Object> builder = ImmutableMap.builder(); + for (String pair : raw.split(",")) { + String[] parts = pair.split("="); + if (parts.length != 2) { + throw new IllegalArgumentException(String.format("\"%s\" is not a valid property-value pair", pair)); + } + String rawKey = parts[0]; + String rawValue = parts[1]; + IProperty key = block.getBlockState().getProperty(rawKey); + Comparable value = castToIProperty(key).parseValue(rawValue) + .toJavaUtil().orElseThrow(() -> new IllegalArgumentException(String.format( + "\"%s\" is not a valid value for %s on %s", + rawValue, key, block + ))); + builder.put(key, value); + } + return builder.build(); + } + + private static Set getStates(@Nonnull Block block, @Nullable Integer meta, @Nonnull Map, ?> properties) { return block.getBlockState().getValidStates().stream() .filter(blockstate -> meta == null || stateMeta(blockstate) == meta) + .filter(blockstate -> properties.entrySet().stream().allMatch(entry -> + blockstate.getValue(entry.getKey()) == entry.getValue() + )) .collect(Collectors.toSet()); } @@ -274,6 +304,7 @@ public Block getBlock() { return block; } + @Deprecated // deprecated because getMeta() == null no longer implies that this BOM only cares about the block public Integer getMeta() { return noMeta ? null : meta; } @@ -300,7 +331,11 @@ public boolean matches(ItemStack stack) { @Override public String toString() { - return String.format("BlockOptionalMeta{block=%s,meta=%s}", block, getMeta()); + if (noMeta) { + return String.format("BlockOptionalMeta{block=%s,properties=%s}", block, propertiesDescription); + } else { + return String.format("BlockOptionalMeta{block=%s,meta=%s}", block, getMeta()); + } } public static IBlockState blockStateFromStack(ItemStack stack) { From c45a714b77b2e22b15108be5dfa822ffbd7a90dd Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Mon, 8 May 2023 03:51:38 +0200 Subject: [PATCH 036/111] Fix considering states unplaceable even if buildIgnoreProperties allows it --- src/main/java/baritone/process/BuilderProcess.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index c7868a4a0..a10085afe 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -691,7 +691,7 @@ private Goal assemble(BuilderCalculationContext bcc, List approxPla incorrectPositions.forEach(pos -> { IBlockState state = bcc.bsi.get0(pos); if (state.getBlock() instanceof BlockAir) { - if (approxPlaceable.contains(bcc.getSchematic(pos.x, pos.y, pos.z, state))) { + if (containsBlockState(approxPlaceable, bcc.getSchematic(pos.x, pos.y, pos.z, state))) { placeable.add(pos); } else { IBlockState desired = bcc.getSchematic(pos.x, pos.y, pos.z, state); @@ -922,6 +922,15 @@ private boolean sameBlockstate(IBlockState first, IBlockState second) { return true; } + private boolean containsBlockState(Collection states, IBlockState state) { + for (IBlockState testee : states) { + if (sameBlockstate(testee, state)) { + return true; + } + } + return false; + } + private boolean valid(IBlockState current, IBlockState desired, boolean itemVerify) { if (desired == null) { return true; From 80ec9023ce221dc147b4d12ad85f85abea965574 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 4 Jun 2023 12:31:34 -0500 Subject: [PATCH 037/111] Replace `JAVA_ONLY_SETTINGS` array with `@JavaOnly` annotation --- src/api/java/baritone/api/Settings.java | 27 +++++++++++++++++++ .../command/helpers/TabCompleteHelper.java | 2 +- .../java/baritone/api/utils/SettingsUtil.java | 15 ++++------- .../command/ExampleBaritoneControl.java | 4 +-- .../baritone/command/defaults/SetCommand.java | 4 +-- 5 files changed, 37 insertions(+), 15 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index c13cde2f7..b7a4e41a4 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -29,6 +29,10 @@ import net.minecraft.util.text.ITextComponent; import java.awt.*; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; @@ -1154,6 +1158,7 @@ public final class Settings { * via {@link Consumer#andThen(Consumer)} or it can completely be overriden via setting * {@link Setting#value}; */ + @JavaOnly public final Setting> logger = new Setting<>(msg -> Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage(msg)); /** @@ -1161,6 +1166,7 @@ public final class Settings { * via {@link Consumer#andThen(Consumer)} or it can completely be overriden via setting * {@link Setting#value}; */ + @JavaOnly public final Setting> notifier = new Setting<>(NotificationHelper::notify); /** @@ -1168,6 +1174,7 @@ public final class Settings { * via {@link Consumer#andThen(Consumer)} or it can completely be overriden via setting * {@link Setting#value}; */ + @JavaOnly public final Setting> toaster = new Setting<>(BaritoneToast::addOrUpdate); /** @@ -1312,6 +1319,7 @@ public final class Setting { public T value; public final T defaultValue; private String name; + private boolean javaOnly; @SuppressWarnings("unchecked") private Setting(T value) { @@ -1320,6 +1328,7 @@ private Setting(T value) { } this.value = value; this.defaultValue = value; + this.javaOnly = false; } /** @@ -1356,8 +1365,25 @@ public void reset() { public final Type getType() { return settingTypes.get(this); } + + /** + * This should always be the same as whether the setting can be parsed from or serialized to a string; in other + * words, the only way to modify it is by writing to {@link #value} programatically. + * + * @return {@code true} if the setting can not be set or read by the user + */ + public boolean isJavaOnly() { + return javaOnly; + } } + /** + * Marks a {@link Setting} field as being {@link Setting#isJavaOnly() Java-only} + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + private @interface JavaOnly {} + // here be dragons Settings() { @@ -1373,6 +1399,7 @@ public final Type getType() { Setting setting = (Setting) field.get(this); String name = field.getName(); setting.name = name; + setting.javaOnly = field.isAnnotationPresent(JavaOnly.class); name = name.toLowerCase(); if (tmpByName.containsKey(name)) { throw new IllegalStateException("Duplicate setting name"); diff --git a/src/api/java/baritone/api/command/helpers/TabCompleteHelper.java b/src/api/java/baritone/api/command/helpers/TabCompleteHelper.java index e438da308..96706d08b 100644 --- a/src/api/java/baritone/api/command/helpers/TabCompleteHelper.java +++ b/src/api/java/baritone/api/command/helpers/TabCompleteHelper.java @@ -253,7 +253,7 @@ public TabCompleteHelper addCommands(ICommandManager manager) { public TabCompleteHelper addSettings() { return append( BaritoneAPI.getSettings().allSettings.stream() - .filter(s -> !SettingsUtil.javaOnlySetting(s)) + .filter(s -> !s.isJavaOnly()) .map(Settings.Setting::getName) .sorted(String.CASE_INSENSITIVE_ORDER) ); diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 50e2363a6..0b9c64737 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -50,7 +50,6 @@ public class SettingsUtil { public static final String SETTINGS_DEFAULT_NAME = "settings.txt"; private static final Pattern SETTING_PATTERN = Pattern.compile("^(?[^ ]+) +(?.+)"); // key and value split by the first space - private static final String[] JAVA_ONLY_SETTINGS = {"logger", "notifier", "toaster"}; private static boolean isComment(String line) { return line.startsWith("#") || line.startsWith("//"); @@ -116,7 +115,7 @@ public static List modifiedSettings(Settings settings) { System.out.println("NULL SETTING?" + setting.getName()); continue; } - if (javaOnlySetting(setting)) { + if (setting.isJavaOnly()) { continue; // NO } if (setting.value == setting.defaultValue) { @@ -170,7 +169,7 @@ public static String maybeCensor(int coord) { } public static String settingToString(Settings.Setting setting) throws IllegalStateException { - if (javaOnlySetting(setting)) { + if (setting.isJavaOnly()) { return setting.getName(); } @@ -178,18 +177,14 @@ public static String settingToString(Settings.Setting setting) throws IllegalSta } /** - * This should always be the same as whether the setting can be parsed from or serialized to a string + * Deprecated. Use {@link Settings.Setting#isJavaOnly()} instead. * * @param setting The Setting * @return true if the setting can not be set or read by the user */ + @Deprecated public static boolean javaOnlySetting(Settings.Setting setting) { - for (String name : JAVA_ONLY_SETTINGS) { // no JAVA_ONLY_SETTINGS.contains(...) because that would be case sensitive - if (setting.getName().equalsIgnoreCase(name)) { - return true; - } - } - return false; + return setting.isJavaOnly(); } public static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException { diff --git a/src/main/java/baritone/command/ExampleBaritoneControl.java b/src/main/java/baritone/command/ExampleBaritoneControl.java index 7050bf302..28ced07f4 100644 --- a/src/main/java/baritone/command/ExampleBaritoneControl.java +++ b/src/main/java/baritone/command/ExampleBaritoneControl.java @@ -124,7 +124,7 @@ public boolean runCommand(String msg) { } } else if (argc.hasExactlyOne()) { for (Settings.Setting setting : settings.allSettings) { - if (SettingsUtil.javaOnlySetting(setting)) { + if (setting.isJavaOnly()) { continue; } if (setting.getName().equalsIgnoreCase(pair.getFirst())) { @@ -177,7 +177,7 @@ public Stream tabComplete(String msg) { .stream(); } Settings.Setting setting = settings.byLowerName.get(argc.getString().toLowerCase(Locale.US)); - if (setting != null && !SettingsUtil.javaOnlySetting(setting)) { + if (setting != null && !setting.isJavaOnly()) { if (setting.getValueClass() == Boolean.class) { TabCompleteHelper helper = new TabCompleteHelper(); if ((Boolean) setting.value) { diff --git a/src/main/java/baritone/command/defaults/SetCommand.java b/src/main/java/baritone/command/defaults/SetCommand.java index 255dd6b28..dd6f1204b 100644 --- a/src/main/java/baritone/command/defaults/SetCommand.java +++ b/src/main/java/baritone/command/defaults/SetCommand.java @@ -77,7 +77,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(1); List toPaginate = (viewModified ? SettingsUtil.modifiedSettings(Baritone.settings()) : Baritone.settings().allSettings).stream() - .filter(s -> !javaOnlySetting(s)) + .filter(s -> !s.isJavaOnly()) .filter(s -> s.getName().toLowerCase(Locale.US).contains(search.toLowerCase(Locale.US))) .sorted((s1, s2) -> String.CASE_INSENSITIVE_ORDER.compare(s1.getName(), s2.getName())) .collect(Collectors.toList()); @@ -141,7 +141,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { if (setting == null) { throw new CommandInvalidTypeException(args.consumed(), "a valid setting"); } - if (javaOnlySetting(setting)) { + if (setting.isJavaOnly()) { // ideally it would act as if the setting didn't exist // but users will see it in Settings.java or its javadoc // so at some point we have to tell them or they will see it as a bug From 0d14bde5839887990236966bd5f09d46841c373f Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 7 Jun 2023 16:31:52 -0500 Subject: [PATCH 038/111] Working sphere/cylinder build commands for `#sel` --- .../api/schematic/CylinderSchematic.java | 50 ++++++++++++++++ .../api/schematic/SphereSchematic.java | 54 ++++++++++++++++++ .../baritone/command/defaults/SelCommand.java | 57 +++++++++++++++---- 3 files changed, 151 insertions(+), 10 deletions(-) create mode 100644 src/api/java/baritone/api/schematic/CylinderSchematic.java create mode 100644 src/api/java/baritone/api/schematic/SphereSchematic.java diff --git a/src/api/java/baritone/api/schematic/CylinderSchematic.java b/src/api/java/baritone/api/schematic/CylinderSchematic.java new file mode 100644 index 000000000..3ba8bc9b8 --- /dev/null +++ b/src/api/java/baritone/api/schematic/CylinderSchematic.java @@ -0,0 +1,50 @@ +/* + * 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.schematic; + +import net.minecraft.block.state.IBlockState; + +/** + * @author Brady + */ +public class CylinderSchematic extends MaskSchematic { + + private final double cx, cz, rx, rz; + private final boolean filled; + + public CylinderSchematic(ISchematic schematic, boolean filled) { + super(schematic); + this.cx = schematic.widthX() / 2.0; + this.cz = schematic.lengthZ() / 2.0; + this.rx = this.cx * this.cx; + this.rz = this.cz * this.cz; + this.filled = filled; + } + + @Override + protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { + double dx = Math.abs((x + 0.5) - this.cx); + double dz = Math.abs((z + 0.5) - this.cz); + return !this.outside(dx, dz) + && (this.filled || outside(dx + 1, dz) || outside(dx, dz + 1)); + } + + private boolean outside(double dx, double dz) { + return dx * dx / this.rx + dz * dz / this.rz > 1; + } +} diff --git a/src/api/java/baritone/api/schematic/SphereSchematic.java b/src/api/java/baritone/api/schematic/SphereSchematic.java new file mode 100644 index 000000000..0ca987760 --- /dev/null +++ b/src/api/java/baritone/api/schematic/SphereSchematic.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.api.schematic; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.util.math.Vec3d; + +/** + * @author Brady + */ +public class SphereSchematic extends MaskSchematic { + + private final double cx, cy, cz, rx, ry, rz; + private final boolean filled; + + public SphereSchematic(ISchematic schematic, boolean filled) { + super(schematic); + this.cx = schematic.widthX() / 2.0; + this.cy = schematic.heightY() / 2.0; + this.cz = schematic.lengthZ() / 2.0; + this.rx = this.cx * this.cx; + this.ry = this.cy * this.cy; + this.rz = this.cz * this.cz; + this.filled = filled; + } + + @Override + protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { + double dx = Math.abs((x + 0.5) - this.cx); + double dy = Math.abs((y + 0.5) - this.cy); + double dz = Math.abs((z + 0.5) - this.cz); + return !this.outside(dx, dy, dz) + && (this.filled || outside(dx + 1, dy, dz) || outside(dx, dy + 1, dz) || outside(dx, dy, dz + 1)); + } + + private boolean outside(double dx,double dy, double dz) { + return dx * dx / this.rx + dy * dy / this.ry + dz * dz / this.rz > 1; + } +} diff --git a/src/main/java/baritone/command/defaults/SelCommand.java b/src/main/java/baritone/command/defaults/SelCommand.java index 5677eec3c..dcdd05b74 100644 --- a/src/main/java/baritone/command/defaults/SelCommand.java +++ b/src/main/java/baritone/command/defaults/SelCommand.java @@ -117,7 +117,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { logDirect("Undid pos2"); } } - } else if (action == Action.SET || action == Action.WALLS || action == Action.SHELL || action == Action.CLEARAREA || action == Action.REPLACE) { + } else if (action.isFillAction()) { BlockOptionalMeta type = action == Action.CLEARAREA ? new BlockOptionalMeta(Blocks.AIR) : args.getDatatypeFor(ForBlockOptionalMeta.INSTANCE); @@ -151,14 +151,10 @@ public void execute(String label, IArgConsumer args) throws CommandException { for (ISelection selection : selections) { Vec3i size = selection.size(); BetterBlockPos min = selection.min(); - ISchematic schematic = new FillSchematic(size.getX(), size.getY(), size.getZ(), type); - if (action == Action.WALLS) { - schematic = new WallsSchematic(schematic); - } else if (action == Action.SHELL) { - schematic = new ShellSchematic(schematic); - } else if (action == Action.REPLACE) { - schematic = new ReplaceSchematic(schematic, replaces); - } + ISchematic schematic = action.createFillMask( + new FillSchematic(size.getX(), size.getY(), size.getZ(), type), + replaces + ); composite.put(schematic, min.x - origin.x, min.y - origin.y, min.z - origin.z); } baritone.getBuilderProcess().build("Fill", composite, origin); @@ -254,7 +250,7 @@ public Stream tabComplete(String label, IArgConsumer args) throws Comman if (args.hasAtMost(3)) { return args.tabCompleteDatatype(RelativeBlockPos.INSTANCE); } - } else if (action == Action.SET || action == Action.WALLS || action == Action.CLEARAREA || action == Action.REPLACE) { + } else if (action.isFillAction()) { if (args.hasExactlyOne() || action == Action.REPLACE) { while (args.has(2)) { args.get(); @@ -305,6 +301,10 @@ public List getLongDesc() { "> sel set/fill/s/f [block] - Completely fill all selections with a block.", "> sel walls/w [block] - Fill in the walls of the selection with a specified block.", "> sel shell/shl [block] - The same as walls, but fills in a ceiling and floor too.", + "> sel sphere/sph [block] - Fills the selection with a sphere bounded by the sides.", + "> sel hsphere/hsph [block] - The same as sphere, but hollow.", + "> sel cylinder/cyl [block] - Fills the selection with a cylinder bounded by the sides.", + "> sel hcylinder/hcyl [block] - The same as cylinder, but hollow.", "> sel cleararea/ca - Basically 'set air'.", "> sel replace/r - Replaces blocks with another block.", "> sel copy/cp - Copy the selected area relative to the specified or your position.", @@ -324,6 +324,10 @@ enum Action { SET("set", "fill", "s", "f"), WALLS("walls", "w"), SHELL("shell", "shl"), + SPHERE("sphere", "sph"), + HSPHERE("hsphere", "hsph"), + CYLINDER("cylinder", "cyl"), + HCYLINDER("hcylinder", "hcyl"), CLEARAREA("cleararea", "ca"), REPLACE("replace", "r"), EXPAND("expand", "ex"), @@ -355,6 +359,39 @@ public static String[] getAllNames() { } return names.toArray(new String[0]); } + + public final boolean isFillAction() { + return this == SET + || this == WALLS + || this == SHELL + || this == SPHERE + || this == HSPHERE + || this == CYLINDER + || this == HCYLINDER + || this == CLEARAREA + || this == REPLACE; + } + + public final ISchematic createFillMask(ISchematic fill, BlockOptionalMetaLookup replaces) { + switch (this) { + case WALLS: + return new WallsSchematic(fill); + case SHELL: + return new ShellSchematic(fill); + case REPLACE: + return new ReplaceSchematic(fill, replaces); + case SPHERE: + return new SphereSchematic(fill, true); + case HSPHERE: + return new SphereSchematic(fill, false); + case CYLINDER: + return new CylinderSchematic(fill, true); + case HCYLINDER: + return new CylinderSchematic(fill, false); + } + // Silent fail + return fill; + } } enum TransformTarget { From 34abbfb5daced3623e9a2a17da8018042980d758 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 7 Jun 2023 17:38:26 -0500 Subject: [PATCH 039/111] appease codacy --- .../api/schematic/CylinderSchematic.java | 19 +++++++------ .../api/schematic/SphereSchematic.java | 28 +++++++++++-------- .../baritone/command/defaults/SelCommand.java | 5 ++-- 3 files changed, 30 insertions(+), 22 deletions(-) diff --git a/src/api/java/baritone/api/schematic/CylinderSchematic.java b/src/api/java/baritone/api/schematic/CylinderSchematic.java index 3ba8bc9b8..75726348d 100644 --- a/src/api/java/baritone/api/schematic/CylinderSchematic.java +++ b/src/api/java/baritone/api/schematic/CylinderSchematic.java @@ -24,27 +24,30 @@ */ public class CylinderSchematic extends MaskSchematic { - private final double cx, cz, rx, rz; + private final double centerX; + private final double centerZ; + private final double radiusSqX; + private final double radiusSqZ; private final boolean filled; public CylinderSchematic(ISchematic schematic, boolean filled) { super(schematic); - this.cx = schematic.widthX() / 2.0; - this.cz = schematic.lengthZ() / 2.0; - this.rx = this.cx * this.cx; - this.rz = this.cz * this.cz; + this.centerX = schematic.widthX() / 2.0; + this.centerZ = schematic.lengthZ() / 2.0; + this.radiusSqX = this.centerX * this.centerX; + this.radiusSqZ = this.centerZ * this.centerZ; this.filled = filled; } @Override protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { - double dx = Math.abs((x + 0.5) - this.cx); - double dz = Math.abs((z + 0.5) - this.cz); + double dx = Math.abs((x + 0.5) - this.centerX); + double dz = Math.abs((z + 0.5) - this.centerZ); return !this.outside(dx, dz) && (this.filled || outside(dx + 1, dz) || outside(dx, dz + 1)); } private boolean outside(double dx, double dz) { - return dx * dx / this.rx + dz * dz / this.rz > 1; + return dx * dx / this.radiusSqX + dz * dz / this.radiusSqZ > 1; } } diff --git a/src/api/java/baritone/api/schematic/SphereSchematic.java b/src/api/java/baritone/api/schematic/SphereSchematic.java index 0ca987760..1cf0a579f 100644 --- a/src/api/java/baritone/api/schematic/SphereSchematic.java +++ b/src/api/java/baritone/api/schematic/SphereSchematic.java @@ -18,37 +18,41 @@ package baritone.api.schematic; import net.minecraft.block.state.IBlockState; -import net.minecraft.util.math.Vec3d; /** * @author Brady */ public class SphereSchematic extends MaskSchematic { - private final double cx, cy, cz, rx, ry, rz; + private final double centerX; + private final double centerY; + private final double centerZ; + private final double radiusSqX; + private final double radiusSqY; + private final double radiusSqZ; private final boolean filled; public SphereSchematic(ISchematic schematic, boolean filled) { super(schematic); - this.cx = schematic.widthX() / 2.0; - this.cy = schematic.heightY() / 2.0; - this.cz = schematic.lengthZ() / 2.0; - this.rx = this.cx * this.cx; - this.ry = this.cy * this.cy; - this.rz = this.cz * this.cz; + this.centerX = schematic.widthX() / 2.0; + this.centerY = schematic.heightY() / 2.0; + this.centerZ = schematic.lengthZ() / 2.0; + this.radiusSqX = this.centerX * this.centerX; + this.radiusSqY = this.centerY * this.centerY; + this.radiusSqZ = this.centerZ * this.centerZ; this.filled = filled; } @Override protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { - double dx = Math.abs((x + 0.5) - this.cx); - double dy = Math.abs((y + 0.5) - this.cy); - double dz = Math.abs((z + 0.5) - this.cz); + double dx = Math.abs((x + 0.5) - this.centerX); + double dy = Math.abs((y + 0.5) - this.centerY); + double dz = Math.abs((z + 0.5) - this.centerZ); return !this.outside(dx, dy, dz) && (this.filled || outside(dx + 1, dy, dz) || outside(dx, dy + 1, dz) || outside(dx, dy, dz + 1)); } private boolean outside(double dx,double dy, double dz) { - return dx * dx / this.rx + dy * dy / this.ry + dz * dz / this.rz > 1; + return dx * dx / this.radiusSqX + dy * dy / this.radiusSqY + dz * dz / this.radiusSqZ > 1; } } diff --git a/src/main/java/baritone/command/defaults/SelCommand.java b/src/main/java/baritone/command/defaults/SelCommand.java index dcdd05b74..40df5c294 100644 --- a/src/main/java/baritone/command/defaults/SelCommand.java +++ b/src/main/java/baritone/command/defaults/SelCommand.java @@ -388,9 +388,10 @@ public final ISchematic createFillMask(ISchematic fill, BlockOptionalMetaLookup return new CylinderSchematic(fill, true); case HCYLINDER: return new CylinderSchematic(fill, false); + default: + // Silent fail + return fill; } - // Silent fail - return fill; } } From b6c52cd8e1fd567afdefe428876f7ed0c2a7a4e4 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 8 Jun 2023 11:52:13 -0500 Subject: [PATCH 040/111] Cache mask in a `boolean[][][]` --- .../api/schematic/CachedMaskSchematic.java | 53 +++++++++++++++++++ .../api/schematic/CylinderSchematic.java | 43 +++++++-------- .../api/schematic/SphereSchematic.java | 51 ++++++++---------- 3 files changed, 92 insertions(+), 55 deletions(-) create mode 100644 src/api/java/baritone/api/schematic/CachedMaskSchematic.java diff --git a/src/api/java/baritone/api/schematic/CachedMaskSchematic.java b/src/api/java/baritone/api/schematic/CachedMaskSchematic.java new file mode 100644 index 000000000..19bcf4e3a --- /dev/null +++ b/src/api/java/baritone/api/schematic/CachedMaskSchematic.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.api.schematic; + +import net.minecraft.block.state.IBlockState; + +/** + * @author Brady + */ +public abstract class CachedMaskSchematic extends MaskSchematic { + + /** + * Mask array with {@code y,z,x} indexing + */ + private final boolean[][][] mask; + + public CachedMaskSchematic(ISchematic schematic, StaticMaskFunction maskFunction) { + super(schematic); + this.mask = new boolean[schematic.heightY()][schematic.lengthZ()][schematic.widthX()]; + for (int y = 0; y < schematic.heightY(); y++) { + for (int z = 0; z < schematic.lengthZ(); z++) { + for (int x = 0; x < schematic.widthX(); x++) { + this.mask[y][z][x] = maskFunction.partOfMask(x, y, z); + } + } + } + } + + @Override + protected final boolean partOfMask(int x, int y, int z, IBlockState currentState) { + return this.mask[y][z][x]; + } + + @FunctionalInterface + public interface StaticMaskFunction { + boolean partOfMask(int x, int y, int z); + } +} diff --git a/src/api/java/baritone/api/schematic/CylinderSchematic.java b/src/api/java/baritone/api/schematic/CylinderSchematic.java index 75726348d..055f12875 100644 --- a/src/api/java/baritone/api/schematic/CylinderSchematic.java +++ b/src/api/java/baritone/api/schematic/CylinderSchematic.java @@ -17,37 +17,30 @@ package baritone.api.schematic; -import net.minecraft.block.state.IBlockState; - /** * @author Brady */ -public class CylinderSchematic extends MaskSchematic { - - private final double centerX; - private final double centerZ; - private final double radiusSqX; - private final double radiusSqZ; - private final boolean filled; +public final class CylinderSchematic extends CachedMaskSchematic { public CylinderSchematic(ISchematic schematic, boolean filled) { - super(schematic); - this.centerX = schematic.widthX() / 2.0; - this.centerZ = schematic.lengthZ() / 2.0; - this.radiusSqX = this.centerX * this.centerX; - this.radiusSqZ = this.centerZ * this.centerZ; - this.filled = filled; - } + super(schematic, new StaticMaskFunction() { - @Override - protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { - double dx = Math.abs((x + 0.5) - this.centerX); - double dz = Math.abs((z + 0.5) - this.centerZ); - return !this.outside(dx, dz) - && (this.filled || outside(dx + 1, dz) || outside(dx, dz + 1)); - } + private final double centerX = schematic.widthX() / 2.0; + private final double centerZ = schematic.lengthZ() / 2.0; + private final double radiusSqX = this.centerX * this.centerX; + private final double radiusSqZ = this.centerZ * this.centerZ; + + @Override + public boolean partOfMask(int x, int y, int z) { + double dx = Math.abs((x + 0.5) - this.centerX); + double dz = Math.abs((z + 0.5) - this.centerZ); + return !this.outside(dx, dz) + && (filled || outside(dx + 1, dz) || outside(dx, dz + 1)); + } - private boolean outside(double dx, double dz) { - return dx * dx / this.radiusSqX + dz * dz / this.radiusSqZ > 1; + private boolean outside(double dx, double dz) { + return dx * dx / this.radiusSqX + dz * dz / this.radiusSqZ > 1; + } + }); } } diff --git a/src/api/java/baritone/api/schematic/SphereSchematic.java b/src/api/java/baritone/api/schematic/SphereSchematic.java index 1cf0a579f..987b87198 100644 --- a/src/api/java/baritone/api/schematic/SphereSchematic.java +++ b/src/api/java/baritone/api/schematic/SphereSchematic.java @@ -17,42 +17,33 @@ package baritone.api.schematic; -import net.minecraft.block.state.IBlockState; - /** * @author Brady */ -public class SphereSchematic extends MaskSchematic { - - private final double centerX; - private final double centerY; - private final double centerZ; - private final double radiusSqX; - private final double radiusSqY; - private final double radiusSqZ; - private final boolean filled; +public final class SphereSchematic extends CachedMaskSchematic { public SphereSchematic(ISchematic schematic, boolean filled) { - super(schematic); - this.centerX = schematic.widthX() / 2.0; - this.centerY = schematic.heightY() / 2.0; - this.centerZ = schematic.lengthZ() / 2.0; - this.radiusSqX = this.centerX * this.centerX; - this.radiusSqY = this.centerY * this.centerY; - this.radiusSqZ = this.centerZ * this.centerZ; - this.filled = filled; - } + super(schematic, new StaticMaskFunction() { - @Override - protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { - double dx = Math.abs((x + 0.5) - this.centerX); - double dy = Math.abs((y + 0.5) - this.centerY); - double dz = Math.abs((z + 0.5) - this.centerZ); - return !this.outside(dx, dy, dz) - && (this.filled || outside(dx + 1, dy, dz) || outside(dx, dy + 1, dz) || outside(dx, dy, dz + 1)); - } + private final double centerX = schematic.widthX() / 2.0; + private final double centerY = schematic.heightY() / 2.0; + private final double centerZ = schematic.lengthZ() / 2.0; + private final double radiusSqX = this.centerX * this.centerX; + private final double radiusSqY = this.centerY * this.centerY; + private final double radiusSqZ = this.centerZ * this.centerZ; + + @Override + public boolean partOfMask(int x, int y, int z) { + double dx = Math.abs((x + 0.5) - this.centerX); + double dy = Math.abs((y + 0.5) - this.centerY); + double dz = Math.abs((z + 0.5) - this.centerZ); + return !this.outside(dx, dy, dz) + && (filled || outside(dx + 1, dy, dz) || outside(dx, dy + 1, dz) || outside(dx, dy, dz + 1)); + } - private boolean outside(double dx,double dy, double dz) { - return dx * dx / this.radiusSqX + dy * dy / this.radiusSqY + dz * dz / this.radiusSqZ > 1; + private boolean outside(double dx,double dy, double dz) { + return dx * dx / this.radiusSqX + dy * dy / this.radiusSqY + dz * dz / this.radiusSqZ > 1; + } + }); } } From a1b1ef88cf4d83ca027e05e589fc46ff148be634 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 8 Jun 2023 15:46:32 -0500 Subject: [PATCH 041/111] Use a Supplier to mimic a switch expression --- .../baritone/command/defaults/SelCommand.java | 55 ++++++++++--------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/src/main/java/baritone/command/defaults/SelCommand.java b/src/main/java/baritone/command/defaults/SelCommand.java index 40df5c294..85b3e4307 100644 --- a/src/main/java/baritone/command/defaults/SelCommand.java +++ b/src/main/java/baritone/command/defaults/SelCommand.java @@ -50,6 +50,7 @@ import java.util.List; import java.util.*; import java.util.function.Function; +import java.util.function.UnaryOperator; import java.util.stream.Stream; public class SelCommand extends Command { @@ -121,7 +122,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { BlockOptionalMeta type = action == Action.CLEARAREA ? new BlockOptionalMeta(Blocks.AIR) : args.getDatatypeFor(ForBlockOptionalMeta.INSTANCE); - BlockOptionalMetaLookup replaces = null; + BlockOptionalMetaLookup replaces; if (action == Action.REPLACE) { args.requireMin(1); List replacesList = new ArrayList<>(); @@ -133,6 +134,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { replaces = new BlockOptionalMetaLookup(replacesList.toArray(new BlockOptionalMeta[0])); } else { args.requireMax(0); + replaces = null; } ISelection[] selections = manager.getSelections(); if (selections.length == 0) { @@ -151,10 +153,31 @@ public void execute(String label, IArgConsumer args) throws CommandException { for (ISelection selection : selections) { Vec3i size = selection.size(); BetterBlockPos min = selection.min(); - ISchematic schematic = action.createFillMask( - new FillSchematic(size.getX(), size.getY(), size.getZ(), type), - replaces - ); + + // Java 8 so no switch expressions 😿 + UnaryOperator create = fill -> { + switch (action) { + case WALLS: + return new WallsSchematic(fill); + case SHELL: + return new ShellSchematic(fill); + case REPLACE: + return new ReplaceSchematic(fill, replaces); + case SPHERE: + return new SphereSchematic(fill, true); + case HSPHERE: + return new SphereSchematic(fill, false); + case CYLINDER: + return new CylinderSchematic(fill, true); + case HCYLINDER: + return new CylinderSchematic(fill, false); + default: + // Silent fail + return fill; + } + }; + + ISchematic schematic = create.apply(new FillSchematic(size.getX(), size.getY(), size.getZ(), type)); composite.put(schematic, min.x - origin.x, min.y - origin.y, min.z - origin.z); } baritone.getBuilderProcess().build("Fill", composite, origin); @@ -371,28 +394,6 @@ public final boolean isFillAction() { || this == CLEARAREA || this == REPLACE; } - - public final ISchematic createFillMask(ISchematic fill, BlockOptionalMetaLookup replaces) { - switch (this) { - case WALLS: - return new WallsSchematic(fill); - case SHELL: - return new ShellSchematic(fill); - case REPLACE: - return new ReplaceSchematic(fill, replaces); - case SPHERE: - return new SphereSchematic(fill, true); - case HSPHERE: - return new SphereSchematic(fill, false); - case CYLINDER: - return new CylinderSchematic(fill, true); - case HCYLINDER: - return new CylinderSchematic(fill, false); - default: - // Silent fail - return fill; - } - } } enum TransformTarget { From 26574b4a9b23a67d1555b8717a084bcca51503b8 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 8 Jun 2023 16:32:33 -0500 Subject: [PATCH 042/111] Add optional axis parameter for `#sel cyl` --- .../api/command/datatypes/ForAxis.java | 43 +++++++++++++++++++ .../api/schematic/CylinderSchematic.java | 32 +++++++++----- .../baritone/command/defaults/SelCommand.java | 25 ++++++++--- 3 files changed, 84 insertions(+), 16 deletions(-) create mode 100644 src/api/java/baritone/api/command/datatypes/ForAxis.java diff --git a/src/api/java/baritone/api/command/datatypes/ForAxis.java b/src/api/java/baritone/api/command/datatypes/ForAxis.java new file mode 100644 index 000000000..48efb39b7 --- /dev/null +++ b/src/api/java/baritone/api/command/datatypes/ForAxis.java @@ -0,0 +1,43 @@ +/* + * 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.command.datatypes; + +import baritone.api.command.exception.CommandException; +import baritone.api.command.helpers.TabCompleteHelper; +import net.minecraft.util.EnumFacing; + +import java.util.Locale; +import java.util.stream.Stream; + +public enum ForAxis implements IDatatypeFor { + INSTANCE; + + @Override + public EnumFacing.Axis get(IDatatypeContext ctx) throws CommandException { + return EnumFacing.Axis.valueOf(ctx.getConsumer().getString().toUpperCase(Locale.US)); + } + + @Override + public Stream tabComplete(IDatatypeContext ctx) throws CommandException { + return new TabCompleteHelper() + .append(Stream.of(EnumFacing.Axis.values()) + .map(EnumFacing.Axis::getName).map(String::toLowerCase)) + .filterPrefix(ctx.getConsumer().getString()) + .stream(); + } +} diff --git a/src/api/java/baritone/api/schematic/CylinderSchematic.java b/src/api/java/baritone/api/schematic/CylinderSchematic.java index 055f12875..342c6e373 100644 --- a/src/api/java/baritone/api/schematic/CylinderSchematic.java +++ b/src/api/java/baritone/api/schematic/CylinderSchematic.java @@ -17,29 +17,39 @@ package baritone.api.schematic; +import net.minecraft.util.EnumFacing; + /** * @author Brady */ public final class CylinderSchematic extends CachedMaskSchematic { - public CylinderSchematic(ISchematic schematic, boolean filled) { + public CylinderSchematic(ISchematic schematic, boolean filled, EnumFacing.Axis alignment) { super(schematic, new StaticMaskFunction() { - private final double centerX = schematic.widthX() / 2.0; - private final double centerZ = schematic.lengthZ() / 2.0; - private final double radiusSqX = this.centerX * this.centerX; - private final double radiusSqZ = this.centerZ * this.centerZ; + private final double centerA = this.getA(schematic.widthX(), schematic.heightY()) / 2.0; + private final double centerB = this.getB(schematic.heightY(), schematic.lengthZ()) / 2.0; + private final double radiusSqA = this.centerA * this.centerA; + private final double radiusSqB = this.centerB * this.centerB; @Override public boolean partOfMask(int x, int y, int z) { - double dx = Math.abs((x + 0.5) - this.centerX); - double dz = Math.abs((z + 0.5) - this.centerZ); - return !this.outside(dx, dz) - && (filled || outside(dx + 1, dz) || outside(dx, dz + 1)); + double da = Math.abs((this.getA(x, y) + 0.5) - this.centerA); + double db = Math.abs((this.getB(y, z) + 0.5) - this.centerB); + return !this.outside(da, db) + && (filled || outside(da + 1, db) || outside(da, db + 1)); + } + + private boolean outside(double da, double db) { + return da * da / this.radiusSqA + db * db / this.radiusSqB > 1; + } + + private int getA(int x, int y) { + return alignment == EnumFacing.Axis.X ? y : x; } - private boolean outside(double dx, double dz) { - return dx * dx / this.radiusSqX + dz * dz / this.radiusSqZ > 1; + private int getB(int y, int z) { + return alignment == EnumFacing.Axis.Z ? y : z; } }); } diff --git a/src/main/java/baritone/command/defaults/SelCommand.java b/src/main/java/baritone/command/defaults/SelCommand.java index 85b3e4307..72c5cd1c0 100644 --- a/src/main/java/baritone/command/defaults/SelCommand.java +++ b/src/main/java/baritone/command/defaults/SelCommand.java @@ -21,6 +21,7 @@ import baritone.api.IBaritone; import baritone.api.command.Command; import baritone.api.command.argument.IArgConsumer; +import baritone.api.command.datatypes.ForAxis; import baritone.api.command.datatypes.ForBlockOptionalMeta; import baritone.api.command.datatypes.ForEnumFacing; import baritone.api.command.datatypes.RelativeBlockPos; @@ -122,7 +123,9 @@ public void execute(String label, IArgConsumer args) throws CommandException { BlockOptionalMeta type = action == Action.CLEARAREA ? new BlockOptionalMeta(Blocks.AIR) : args.getDatatypeFor(ForBlockOptionalMeta.INSTANCE); - BlockOptionalMetaLookup replaces; + + final BlockOptionalMetaLookup replaces; // Action.REPLACE + final EnumFacing.Axis alignment; // Action.(H)CYLINDER if (action == Action.REPLACE) { args.requireMin(1); List replacesList = new ArrayList<>(); @@ -132,9 +135,15 @@ public void execute(String label, IArgConsumer args) throws CommandException { } type = args.getDatatypeFor(ForBlockOptionalMeta.INSTANCE); replaces = new BlockOptionalMetaLookup(replacesList.toArray(new BlockOptionalMeta[0])); + alignment = null; + } else if (action == Action.CYLINDER || action == Action.HCYLINDER) { + args.requireMax(1); + alignment = args.hasAny() ? args.getDatatypeFor(ForAxis.INSTANCE) : EnumFacing.Axis.Y; + replaces = null; } else { args.requireMax(0); replaces = null; + alignment = null; } ISelection[] selections = manager.getSelections(); if (selections.length == 0) { @@ -168,9 +177,9 @@ public void execute(String label, IArgConsumer args) throws CommandException { case HSPHERE: return new SphereSchematic(fill, false); case CYLINDER: - return new CylinderSchematic(fill, true); + return new CylinderSchematic(fill, true, alignment); case HCYLINDER: - return new CylinderSchematic(fill, false); + return new CylinderSchematic(fill, false, alignment); default: // Silent fail return fill; @@ -279,6 +288,12 @@ public Stream tabComplete(String label, IArgConsumer args) throws Comman args.get(); } return args.tabCompleteDatatype(ForBlockOptionalMeta.INSTANCE); + } else if (action == Action.CYLINDER || action == Action.HCYLINDER) { + if (args.hasExactly(2)) { + if (args.getDatatypeForOrNull(ForBlockOptionalMeta.INSTANCE) != null) { + return args.tabCompleteDatatype(ForAxis.INSTANCE); + } + } } } else if (action == Action.EXPAND || action == Action.CONTRACT || action == Action.SHIFT) { if (args.hasExactlyOne()) { @@ -326,8 +341,8 @@ public List getLongDesc() { "> sel shell/shl [block] - The same as walls, but fills in a ceiling and floor too.", "> sel sphere/sph [block] - Fills the selection with a sphere bounded by the sides.", "> sel hsphere/hsph [block] - The same as sphere, but hollow.", - "> sel cylinder/cyl [block] - Fills the selection with a cylinder bounded by the sides.", - "> sel hcylinder/hcyl [block] - The same as cylinder, but hollow.", + "> sel cylinder/cyl [block] - Fills the selection with a cylinder bounded by the sides, oriented about the given axis. (default=y)", + "> sel hcylinder/hcyl [block] - The same as cylinder, but hollow.", "> sel cleararea/ca - Basically 'set air'.", "> sel replace/r - Replaces blocks with another block.", "> sel copy/cp - Copy the selected area relative to the specified or your position.", From f232bbdb15cb6a07296b1a093a1213794e051e25 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 8 Jun 2023 16:36:32 -0500 Subject: [PATCH 043/111] Clean up formatting --- .../baritone/api/schematic/CylinderSchematic.java | 8 ++++++-- .../java/baritone/api/schematic/SphereSchematic.java | 11 ++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/schematic/CylinderSchematic.java b/src/api/java/baritone/api/schematic/CylinderSchematic.java index 342c6e373..29b5aa5b3 100644 --- a/src/api/java/baritone/api/schematic/CylinderSchematic.java +++ b/src/api/java/baritone/api/schematic/CylinderSchematic.java @@ -36,8 +36,12 @@ public CylinderSchematic(ISchematic schematic, boolean filled, EnumFacing.Axis a public boolean partOfMask(int x, int y, int z) { double da = Math.abs((this.getA(x, y) + 0.5) - this.centerA); double db = Math.abs((this.getB(y, z) + 0.5) - this.centerB); - return !this.outside(da, db) - && (filled || outside(da + 1, db) || outside(da, db + 1)); + if (this.outside(da, db)) { + return false; + } + return filled + || this.outside(da + 1, db) + || this.outside(da, db + 1); } private boolean outside(double da, double db) { diff --git a/src/api/java/baritone/api/schematic/SphereSchematic.java b/src/api/java/baritone/api/schematic/SphereSchematic.java index 987b87198..074e6ec51 100644 --- a/src/api/java/baritone/api/schematic/SphereSchematic.java +++ b/src/api/java/baritone/api/schematic/SphereSchematic.java @@ -37,11 +37,16 @@ public boolean partOfMask(int x, int y, int z) { double dx = Math.abs((x + 0.5) - this.centerX); double dy = Math.abs((y + 0.5) - this.centerY); double dz = Math.abs((z + 0.5) - this.centerZ); - return !this.outside(dx, dy, dz) - && (filled || outside(dx + 1, dy, dz) || outside(dx, dy + 1, dz) || outside(dx, dy, dz + 1)); + if (this.outside(dx, dy, dz)) { + return false; + } + return filled + || this.outside(dx + 1, dy, dz) + || this.outside(dx, dy + 1, dz) + || this.outside(dx, dy, dz + 1); } - private boolean outside(double dx,double dy, double dz) { + private boolean outside(double dx, double dy, double dz) { return dx * dx / this.radiusSqX + dy * dy / this.radiusSqY + dz * dz / this.radiusSqZ > 1; } }); From 9729e63d980ace7038f2a79f78805b1fa21cc6c9 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 9 Jun 2023 17:25:29 -0500 Subject: [PATCH 044/111] Create and utilize new `Mask` type Added factory method to `MaskSchematic` for creation using a `Mask` Sort-of mocks the schematic structure, without the block states ofc --- .../api/schematic/CachedMaskSchematic.java | 53 -------------- .../api/schematic/CylinderSchematic.java | 60 ---------------- .../baritone/api/schematic/MaskSchematic.java | 11 +++ .../api/schematic/SphereSchematic.java | 54 --------------- .../api/schematic/mask/AbstractMask.java | 49 +++++++++++++ .../baritone/api/schematic/mask/Mask.java | 41 +++++++++++ .../api/schematic/mask/PreComputedMask.java | 44 ++++++++++++ .../api/schematic/mask/StaticMask.java | 62 +++++++++++++++++ .../schematic/mask/shape/CylinderMask.java | 69 +++++++++++++++++++ .../api/schematic/mask/shape/SphereMask.java | 64 +++++++++++++++++ .../baritone/command/defaults/SelCommand.java | 10 +-- 11 files changed, 346 insertions(+), 171 deletions(-) delete mode 100644 src/api/java/baritone/api/schematic/CachedMaskSchematic.java delete mode 100644 src/api/java/baritone/api/schematic/CylinderSchematic.java delete mode 100644 src/api/java/baritone/api/schematic/SphereSchematic.java create mode 100644 src/api/java/baritone/api/schematic/mask/AbstractMask.java create mode 100644 src/api/java/baritone/api/schematic/mask/Mask.java create mode 100644 src/api/java/baritone/api/schematic/mask/PreComputedMask.java create mode 100644 src/api/java/baritone/api/schematic/mask/StaticMask.java create mode 100644 src/api/java/baritone/api/schematic/mask/shape/CylinderMask.java create mode 100644 src/api/java/baritone/api/schematic/mask/shape/SphereMask.java diff --git a/src/api/java/baritone/api/schematic/CachedMaskSchematic.java b/src/api/java/baritone/api/schematic/CachedMaskSchematic.java deleted file mode 100644 index 19bcf4e3a..000000000 --- a/src/api/java/baritone/api/schematic/CachedMaskSchematic.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.api.schematic; - -import net.minecraft.block.state.IBlockState; - -/** - * @author Brady - */ -public abstract class CachedMaskSchematic extends MaskSchematic { - - /** - * Mask array with {@code y,z,x} indexing - */ - private final boolean[][][] mask; - - public CachedMaskSchematic(ISchematic schematic, StaticMaskFunction maskFunction) { - super(schematic); - this.mask = new boolean[schematic.heightY()][schematic.lengthZ()][schematic.widthX()]; - for (int y = 0; y < schematic.heightY(); y++) { - for (int z = 0; z < schematic.lengthZ(); z++) { - for (int x = 0; x < schematic.widthX(); x++) { - this.mask[y][z][x] = maskFunction.partOfMask(x, y, z); - } - } - } - } - - @Override - protected final boolean partOfMask(int x, int y, int z, IBlockState currentState) { - return this.mask[y][z][x]; - } - - @FunctionalInterface - public interface StaticMaskFunction { - boolean partOfMask(int x, int y, int z); - } -} diff --git a/src/api/java/baritone/api/schematic/CylinderSchematic.java b/src/api/java/baritone/api/schematic/CylinderSchematic.java deleted file mode 100644 index 29b5aa5b3..000000000 --- a/src/api/java/baritone/api/schematic/CylinderSchematic.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU 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.schematic; - -import net.minecraft.util.EnumFacing; - -/** - * @author Brady - */ -public final class CylinderSchematic extends CachedMaskSchematic { - - public CylinderSchematic(ISchematic schematic, boolean filled, EnumFacing.Axis alignment) { - super(schematic, new StaticMaskFunction() { - - private final double centerA = this.getA(schematic.widthX(), schematic.heightY()) / 2.0; - private final double centerB = this.getB(schematic.heightY(), schematic.lengthZ()) / 2.0; - private final double radiusSqA = this.centerA * this.centerA; - private final double radiusSqB = this.centerB * this.centerB; - - @Override - public boolean partOfMask(int x, int y, int z) { - double da = Math.abs((this.getA(x, y) + 0.5) - this.centerA); - double db = Math.abs((this.getB(y, z) + 0.5) - this.centerB); - if (this.outside(da, db)) { - return false; - } - return filled - || this.outside(da + 1, db) - || this.outside(da, db + 1); - } - - private boolean outside(double da, double db) { - return da * da / this.radiusSqA + db * db / this.radiusSqB > 1; - } - - private int getA(int x, int y) { - return alignment == EnumFacing.Axis.X ? y : x; - } - - private int getB(int y, int z) { - return alignment == EnumFacing.Axis.Z ? y : z; - } - }); - } -} diff --git a/src/api/java/baritone/api/schematic/MaskSchematic.java b/src/api/java/baritone/api/schematic/MaskSchematic.java index 229f58d5b..2853c6e58 100644 --- a/src/api/java/baritone/api/schematic/MaskSchematic.java +++ b/src/api/java/baritone/api/schematic/MaskSchematic.java @@ -17,6 +17,7 @@ package baritone.api.schematic; +import baritone.api.schematic.mask.Mask; import net.minecraft.block.state.IBlockState; import java.util.List; @@ -41,4 +42,14 @@ public boolean inSchematic(int x, int y, int z, IBlockState currentState) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List approxPlaceable) { return schematic.desiredState(x, y, z, current, approxPlaceable); } + + public static MaskSchematic create(ISchematic schematic, Mask function) { + return new MaskSchematic(schematic) { + + @Override + protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { + return function.partOfMask(x, y, z, currentState); + } + }; + } } diff --git a/src/api/java/baritone/api/schematic/SphereSchematic.java b/src/api/java/baritone/api/schematic/SphereSchematic.java deleted file mode 100644 index 074e6ec51..000000000 --- a/src/api/java/baritone/api/schematic/SphereSchematic.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.schematic; - -/** - * @author Brady - */ -public final class SphereSchematic extends CachedMaskSchematic { - - public SphereSchematic(ISchematic schematic, boolean filled) { - super(schematic, new StaticMaskFunction() { - - private final double centerX = schematic.widthX() / 2.0; - private final double centerY = schematic.heightY() / 2.0; - private final double centerZ = schematic.lengthZ() / 2.0; - private final double radiusSqX = this.centerX * this.centerX; - private final double radiusSqY = this.centerY * this.centerY; - private final double radiusSqZ = this.centerZ * this.centerZ; - - @Override - public boolean partOfMask(int x, int y, int z) { - double dx = Math.abs((x + 0.5) - this.centerX); - double dy = Math.abs((y + 0.5) - this.centerY); - double dz = Math.abs((z + 0.5) - this.centerZ); - if (this.outside(dx, dy, dz)) { - return false; - } - return filled - || this.outside(dx + 1, dy, dz) - || this.outside(dx, dy + 1, dz) - || this.outside(dx, dy, dz + 1); - } - - private boolean outside(double dx, double dy, double dz) { - return dx * dx / this.radiusSqX + dy * dy / this.radiusSqY + dz * dz / this.radiusSqZ > 1; - } - }); - } -} diff --git a/src/api/java/baritone/api/schematic/mask/AbstractMask.java b/src/api/java/baritone/api/schematic/mask/AbstractMask.java new file mode 100644 index 000000000..ce92af0ec --- /dev/null +++ b/src/api/java/baritone/api/schematic/mask/AbstractMask.java @@ -0,0 +1,49 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.schematic.mask; + +/** + * @author Brady + */ +public abstract class AbstractMask implements Mask { + + private final int widthX; + private final int heightY; + private final int lengthZ; + + public AbstractMask(int widthX, int heightY, int lengthZ) { + this.widthX = widthX; + this.heightY = heightY; + this.lengthZ = lengthZ; + } + + @Override + public int widthX() { + return this.widthX; + } + + @Override + public int heightY() { + return this.heightY; + } + + @Override + public int lengthZ() { + return this.lengthZ; + } +} diff --git a/src/api/java/baritone/api/schematic/mask/Mask.java b/src/api/java/baritone/api/schematic/mask/Mask.java new file mode 100644 index 000000000..540c2cee1 --- /dev/null +++ b/src/api/java/baritone/api/schematic/mask/Mask.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.schematic.mask; + +import net.minecraft.block.state.IBlockState; + +/** + * @author Brady + */ +public interface Mask { + + /** + * @param x The relative x position of the block + * @param y The relative y position of the block + * @param z The relative z position of the block + * @param currentState The current state of that block in the world, may be {@code null} + * @return Whether the given position is included in this mask + */ + boolean partOfMask(int x, int y, int z, IBlockState currentState); + + int widthX(); + + int heightY(); + + int lengthZ(); +} diff --git a/src/api/java/baritone/api/schematic/mask/PreComputedMask.java b/src/api/java/baritone/api/schematic/mask/PreComputedMask.java new file mode 100644 index 000000000..aed26cc94 --- /dev/null +++ b/src/api/java/baritone/api/schematic/mask/PreComputedMask.java @@ -0,0 +1,44 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.schematic.mask; + +/** + * @author Brady + */ +final class PreComputedMask extends AbstractMask implements StaticMask { + + private final boolean[][][] mask; + + public PreComputedMask(StaticMask mask) { + super(mask.widthX(), mask.heightY(), mask.lengthZ()); + + this.mask = new boolean[this.heightY()][this.lengthZ()][this.widthX()]; + for (int y = 0; y < this.heightY(); y++) { + for (int z = 0; z < this.lengthZ(); z++) { + for (int x = 0; x < this.widthX(); x++) { + this.mask[y][z][x] = mask.partOfMask(x, y, z); + } + } + } + } + + @Override + public boolean partOfMask(int x, int y, int z) { + return this.mask[y][z][x]; + } +} diff --git a/src/api/java/baritone/api/schematic/mask/StaticMask.java b/src/api/java/baritone/api/schematic/mask/StaticMask.java new file mode 100644 index 000000000..ef50a65cc --- /dev/null +++ b/src/api/java/baritone/api/schematic/mask/StaticMask.java @@ -0,0 +1,62 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.schematic.mask; + +import net.minecraft.block.state.IBlockState; + +/** + * A mask that is context-free. In other words, it doesn't require the current block state to determine if a relative + * position is a part of the mask. + * + * @author Brady + */ +public interface StaticMask extends Mask { + + /** + * Determines if a given relative coordinate is included in this mask, without the need for the current block state. + * + * @param x The relative x position of the block + * @param y The relative y position of the block + * @param z The relative z position of the block + * @return Whether the given position is included in this mask + */ + boolean partOfMask(int x, int y, int z); + + /** + * Implements the parent {@link Mask#partOfMask partOfMask function} by calling the static function + * provided in this functional interface without needing the {@link IBlockState} argument. This {@code default} + * implementation should NOT be overriden. + * + * @param x The relative x position of the block + * @param y The relative y position of the block + * @param z The relative z position of the block + * @param currentState The current state of that block in the world, may be {@code null} + * @return Whether the given position is included in this mask + */ + @Override + default boolean partOfMask(int x, int y, int z, IBlockState currentState) { + return this.partOfMask(x, y, z); + } + + /** + * Returns a pre-computed mask using {@code this} function, with the specified size parameters. + */ + default StaticMask compute() { + return new PreComputedMask(this); + } +} diff --git a/src/api/java/baritone/api/schematic/mask/shape/CylinderMask.java b/src/api/java/baritone/api/schematic/mask/shape/CylinderMask.java new file mode 100644 index 000000000..71b0d43c9 --- /dev/null +++ b/src/api/java/baritone/api/schematic/mask/shape/CylinderMask.java @@ -0,0 +1,69 @@ +/* + * 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.schematic.mask.shape; + +import baritone.api.schematic.mask.AbstractMask; +import baritone.api.schematic.mask.StaticMask; +import net.minecraft.util.EnumFacing; + +/** + * @author Brady + */ +public final class CylinderMask extends AbstractMask implements StaticMask { + + private final double centerA; + private final double centerB; + private final double radiusSqA; + private final double radiusSqB; + private final boolean filled; + private final EnumFacing.Axis alignment; + + public CylinderMask(int widthX, int heightY, int lengthZ, boolean filled, EnumFacing.Axis alignment) { + super(widthX, heightY, lengthZ); + this.centerA = this.getA(widthX, heightY) / 2.0; + this.centerB = this.getB(heightY, lengthZ) / 2.0; + this.radiusSqA = (this.centerA - 1) * (this.centerA - 1); + this.radiusSqB = (this.centerB - 1) * (this.centerB - 1); + this.filled = filled; + this.alignment = alignment; + } + + @Override + public boolean partOfMask(int x, int y, int z) { + double da = Math.abs((this.getA(x, y) + 0.5) - this.centerA); + double db = Math.abs((this.getB(y, z) + 0.5) - this.centerB); + if (this.outside(da, db)) { + return false; + } + return this.filled + || this.outside(da + 1, db) + || this.outside(da, db + 1); + } + + private boolean outside(double da, double db) { + return da * da / this.radiusSqA + db * db / this.radiusSqB > 1; + } + + private int getA(int x, int y) { + return this.alignment == EnumFacing.Axis.X ? y : x; + } + + private int getB(int y, int z) { + return this.alignment == EnumFacing.Axis.Z ? y : z; + } +} diff --git a/src/api/java/baritone/api/schematic/mask/shape/SphereMask.java b/src/api/java/baritone/api/schematic/mask/shape/SphereMask.java new file mode 100644 index 000000000..d805c98a8 --- /dev/null +++ b/src/api/java/baritone/api/schematic/mask/shape/SphereMask.java @@ -0,0 +1,64 @@ +/* + * 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.schematic.mask.shape; + +import baritone.api.schematic.mask.AbstractMask; +import baritone.api.schematic.mask.StaticMask; + +/** + * @author Brady + */ +public final class SphereMask extends AbstractMask implements StaticMask { + + private final double centerX; + private final double centerY; + private final double centerZ; + private final double radiusSqX; + private final double radiusSqY; + private final double radiusSqZ; + private final boolean filled; + + public SphereMask(int widthX, int heightY, int lengthZ, boolean filled) { + super(widthX, heightY, lengthZ); + this.centerX = widthX / 2.0; + this.centerY = heightY / 2.0; + this.centerZ = lengthZ / 2.0; + this.radiusSqX = this.centerX * this.centerX; + this.radiusSqY = this.centerY * this.centerY; + this.radiusSqZ = this.centerZ * this.centerZ; + this.filled = filled; + } + + @Override + public boolean partOfMask(int x, int y, int z) { + double dx = Math.abs((x + 0.5) - this.centerX); + double dy = Math.abs((y + 0.5) - this.centerY); + double dz = Math.abs((z + 0.5) - this.centerZ); + if (this.outside(dx, dy, dz)) { + return false; + } + return this.filled + || this.outside(dx + 1, dy, dz) + || this.outside(dx, dy + 1, dz) + || this.outside(dx, dy, dz + 1); + } + + private boolean outside(double dx, double dy, double dz) { + return dx * dx / this.radiusSqX + dy * dy / this.radiusSqY + dz * dz / this.radiusSqZ > 1; + } +} diff --git a/src/main/java/baritone/command/defaults/SelCommand.java b/src/main/java/baritone/command/defaults/SelCommand.java index 72c5cd1c0..e1d2082ff 100644 --- a/src/main/java/baritone/command/defaults/SelCommand.java +++ b/src/main/java/baritone/command/defaults/SelCommand.java @@ -32,6 +32,8 @@ import baritone.api.event.events.RenderEvent; import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.schematic.*; +import baritone.api.schematic.mask.shape.CylinderMask; +import baritone.api.schematic.mask.shape.SphereMask; import baritone.api.selection.ISelection; import baritone.api.selection.ISelectionManager; import baritone.api.utils.BetterBlockPos; @@ -173,13 +175,13 @@ public void execute(String label, IArgConsumer args) throws CommandException { case REPLACE: return new ReplaceSchematic(fill, replaces); case SPHERE: - return new SphereSchematic(fill, true); + return MaskSchematic.create(fill, new SphereMask(size.getX(), size.getY(), size.getZ(), true).compute()); case HSPHERE: - return new SphereSchematic(fill, false); + return MaskSchematic.create(fill, new SphereMask(size.getX(), size.getY(), size.getZ(), false).compute()); case CYLINDER: - return new CylinderSchematic(fill, true, alignment); + return MaskSchematic.create(fill, new CylinderMask(size.getX(), size.getY(), size.getZ(), true, alignment).compute()); case HCYLINDER: - return new CylinderSchematic(fill, false, alignment); + return MaskSchematic.create(fill, new CylinderMask(size.getX(), size.getY(), size.getZ(), false, alignment).compute()); default: // Silent fail return fill; From 94d757104b027c121ca2bc39f658b09e10ea28a5 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Jun 2023 11:24:31 -0500 Subject: [PATCH 045/111] Clean ups --- .../java/baritone/command/defaults/SelCommand.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/command/defaults/SelCommand.java b/src/main/java/baritone/command/defaults/SelCommand.java index e1d2082ff..0a11c86a8 100644 --- a/src/main/java/baritone/command/defaults/SelCommand.java +++ b/src/main/java/baritone/command/defaults/SelCommand.java @@ -167,6 +167,10 @@ public void execute(String label, IArgConsumer args) throws CommandException { // Java 8 so no switch expressions 😿 UnaryOperator create = fill -> { + final int w = fill.widthX(); + final int h = fill.heightY(); + final int l = fill.lengthZ(); + switch (action) { case WALLS: return new WallsSchematic(fill); @@ -175,13 +179,13 @@ public void execute(String label, IArgConsumer args) throws CommandException { case REPLACE: return new ReplaceSchematic(fill, replaces); case SPHERE: - return MaskSchematic.create(fill, new SphereMask(size.getX(), size.getY(), size.getZ(), true).compute()); + return MaskSchematic.create(fill, new SphereMask(w, h, l, true).compute()); case HSPHERE: - return MaskSchematic.create(fill, new SphereMask(size.getX(), size.getY(), size.getZ(), false).compute()); + return MaskSchematic.create(fill, new SphereMask(w, h, l, false).compute()); case CYLINDER: - return MaskSchematic.create(fill, new CylinderMask(size.getX(), size.getY(), size.getZ(), true, alignment).compute()); + return MaskSchematic.create(fill, new CylinderMask(w, h, l, true, alignment).compute()); case HCYLINDER: - return MaskSchematic.create(fill, new CylinderMask(size.getX(), size.getY(), size.getZ(), false, alignment).compute()); + return MaskSchematic.create(fill, new CylinderMask(w, h, l, false, alignment).compute()); default: // Silent fail return fill; From ffd00080f256e216238c7887c8549fd8bd8ae40f Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Jun 2023 11:27:51 -0500 Subject: [PATCH 046/111] Mask binary operators --- .../baritone/api/schematic/mask/Mask.java | 19 +++++ .../api/schematic/mask/StaticMask.java | 20 ++++++ .../mask/operator/BinaryOperatorMask.java | 71 +++++++++++++++++++ .../api/schematic/mask/operator/NotMask.java | 56 +++++++++++++++ .../api/utils/BooleanBinaryOperator.java | 27 +++++++ .../api/utils/BooleanBinaryOperators.java | 38 ++++++++++ 6 files changed, 231 insertions(+) create mode 100644 src/api/java/baritone/api/schematic/mask/operator/BinaryOperatorMask.java create mode 100644 src/api/java/baritone/api/schematic/mask/operator/NotMask.java create mode 100644 src/api/java/baritone/api/utils/BooleanBinaryOperator.java create mode 100644 src/api/java/baritone/api/utils/BooleanBinaryOperators.java diff --git a/src/api/java/baritone/api/schematic/mask/Mask.java b/src/api/java/baritone/api/schematic/mask/Mask.java index 540c2cee1..7df6f8f04 100644 --- a/src/api/java/baritone/api/schematic/mask/Mask.java +++ b/src/api/java/baritone/api/schematic/mask/Mask.java @@ -17,6 +17,9 @@ package baritone.api.schematic.mask; +import baritone.api.schematic.mask.operator.BinaryOperatorMask; +import baritone.api.schematic.mask.operator.NotMask; +import baritone.api.utils.BooleanBinaryOperators; import net.minecraft.block.state.IBlockState; /** @@ -38,4 +41,20 @@ public interface Mask { int heightY(); int lengthZ(); + + default Mask not() { + return new NotMask(this); + } + + default Mask union(Mask other) { + return new BinaryOperatorMask(this, other, BooleanBinaryOperators.OR); + } + + default Mask intersection(Mask other) { + return new BinaryOperatorMask(this, other, BooleanBinaryOperators.AND); + } + + default Mask xor(Mask other) { + return new BinaryOperatorMask(this, other, BooleanBinaryOperators.XOR); + } } diff --git a/src/api/java/baritone/api/schematic/mask/StaticMask.java b/src/api/java/baritone/api/schematic/mask/StaticMask.java index ef50a65cc..220a94828 100644 --- a/src/api/java/baritone/api/schematic/mask/StaticMask.java +++ b/src/api/java/baritone/api/schematic/mask/StaticMask.java @@ -17,6 +17,9 @@ package baritone.api.schematic.mask; +import baritone.api.schematic.mask.operator.BinaryOperatorMask; +import baritone.api.schematic.mask.operator.NotMask; +import baritone.api.utils.BooleanBinaryOperators; import net.minecraft.block.state.IBlockState; /** @@ -53,6 +56,23 @@ default boolean partOfMask(int x, int y, int z, IBlockState currentState) { return this.partOfMask(x, y, z); } + @Override + default StaticMask not() { + return new NotMask.Static(this); + } + + default StaticMask union(StaticMask other) { + return new BinaryOperatorMask.Static(this, other, BooleanBinaryOperators.OR); + } + + default StaticMask intersection(StaticMask other) { + return new BinaryOperatorMask.Static(this, other, BooleanBinaryOperators.AND); + } + + default StaticMask xor(StaticMask other) { + return new BinaryOperatorMask.Static(this, other, BooleanBinaryOperators.XOR); + } + /** * Returns a pre-computed mask using {@code this} function, with the specified size parameters. */ diff --git a/src/api/java/baritone/api/schematic/mask/operator/BinaryOperatorMask.java b/src/api/java/baritone/api/schematic/mask/operator/BinaryOperatorMask.java new file mode 100644 index 000000000..e591c7873 --- /dev/null +++ b/src/api/java/baritone/api/schematic/mask/operator/BinaryOperatorMask.java @@ -0,0 +1,71 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.schematic.mask.operator; + +import baritone.api.schematic.mask.AbstractMask; +import baritone.api.schematic.mask.Mask; +import baritone.api.schematic.mask.StaticMask; +import baritone.api.utils.BooleanBinaryOperator; +import net.minecraft.block.state.IBlockState; + +/** + * @author Brady + */ +public final class BinaryOperatorMask extends AbstractMask { + + private final Mask a; + private final Mask b; + private final BooleanBinaryOperator operator; + + public BinaryOperatorMask(Mask a, Mask b, BooleanBinaryOperator operator) { + super(a.widthX(), a.heightY(), a.lengthZ()); + this.a = a; + this.b = b; + this.operator = operator; + } + + @Override + public boolean partOfMask(int x, int y, int z, IBlockState currentState) { + return this.operator.applyAsBoolean( + this.a.partOfMask(x, y, z, currentState), + this.b.partOfMask(x, y, z, currentState) + ); + } + + public static final class Static extends AbstractMask implements StaticMask { + + private final StaticMask a; + private final StaticMask b; + private final BooleanBinaryOperator operator; + + public Static(StaticMask a, StaticMask b, BooleanBinaryOperator operator) { + super(a.widthX(), a.heightY(), a.lengthZ()); + this.a = a; + this.b = b; + this.operator = operator; + } + + @Override + public boolean partOfMask(int x, int y, int z) { + return this.operator.applyAsBoolean( + this.a.partOfMask(x, y, z), + this.b.partOfMask(x, y, z) + ); + } + } +} diff --git a/src/api/java/baritone/api/schematic/mask/operator/NotMask.java b/src/api/java/baritone/api/schematic/mask/operator/NotMask.java new file mode 100644 index 000000000..f9f770b82 --- /dev/null +++ b/src/api/java/baritone/api/schematic/mask/operator/NotMask.java @@ -0,0 +1,56 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.schematic.mask.operator; + +import baritone.api.schematic.mask.AbstractMask; +import baritone.api.schematic.mask.Mask; +import baritone.api.schematic.mask.StaticMask; +import net.minecraft.block.state.IBlockState; + +/** + * @author Brady + */ +public final class NotMask extends AbstractMask { + + private final Mask source; + + public NotMask(Mask source) { + super(source.widthX(), source.heightY(), source.lengthZ()); + this.source = source; + } + + @Override + public boolean partOfMask(int x, int y, int z, IBlockState currentState) { + return !this.source.partOfMask(x, y, z, currentState); + } + + public static final class Static extends AbstractMask implements StaticMask { + + private final StaticMask source; + + public Static(StaticMask source) { + super(source.widthX(), source.heightY(), source.lengthZ()); + this.source = source; + } + + @Override + public boolean partOfMask(int x, int y, int z) { + return !this.source.partOfMask(x, y, z); + } + } +} diff --git a/src/api/java/baritone/api/utils/BooleanBinaryOperator.java b/src/api/java/baritone/api/utils/BooleanBinaryOperator.java new file mode 100644 index 000000000..cfb85e644 --- /dev/null +++ b/src/api/java/baritone/api/utils/BooleanBinaryOperator.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.utils; + +/** + * @author Brady + */ +@FunctionalInterface +public interface BooleanBinaryOperator { + + boolean applyAsBoolean(boolean a, boolean b); +} diff --git a/src/api/java/baritone/api/utils/BooleanBinaryOperators.java b/src/api/java/baritone/api/utils/BooleanBinaryOperators.java new file mode 100644 index 000000000..11605c965 --- /dev/null +++ b/src/api/java/baritone/api/utils/BooleanBinaryOperators.java @@ -0,0 +1,38 @@ +/* + * 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; + +/** + * @author Brady + */ +public enum BooleanBinaryOperators implements BooleanBinaryOperator { + OR((a, b) -> a || b), + AND((a, b) -> a && b), + XOR((a, b) -> a ^ b); + + private final BooleanBinaryOperator op; + + BooleanBinaryOperators(BooleanBinaryOperator op) { + this.op = op; + } + + @Override + public boolean applyAsBoolean(boolean a, boolean b) { + return this.op.applyAsBoolean(a, b); + } +} From 364ae87ef861dd12570a0db6081ad1d4f5d4a399 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Jun 2023 12:36:53 -0500 Subject: [PATCH 047/111] Add `blockFreeLook` setting --- src/api/java/baritone/api/Settings.java | 5 +++++ src/api/java/baritone/api/utils/Rotation.java | 8 +++++-- .../baritone/api/utils/RotationUtils.java | 6 +++-- .../java/baritone/behavior/LookBehavior.java | 22 ++++++++++++++----- .../pathing/movement/MovementHelper.java | 4 ++-- .../movement/movements/MovementDescend.java | 5 ++--- .../movement/movements/MovementPillar.java | 4 ++-- .../utils/player/PrimaryPlayerContext.java | 16 ++++++++++---- 8 files changed, 50 insertions(+), 20 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index b7a4e41a4..b49fce01b 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -723,6 +723,11 @@ public final class Settings { */ public final Setting freeLook = new Setting<>(true); + /** + * Break and place blocks without having to force the client-sided rotations + */ + public final Setting blockFreeLook = new Setting<>(true); + /** * Will cause some minor behavioral differences to ensure that Baritone works on anticheats. *

diff --git a/src/api/java/baritone/api/utils/Rotation.java b/src/api/java/baritone/api/utils/Rotation.java index 54f63ebfa..8dab287de 100644 --- a/src/api/java/baritone/api/utils/Rotation.java +++ b/src/api/java/baritone/api/utils/Rotation.java @@ -26,12 +26,12 @@ public class Rotation { /** * The yaw angle of this Rotation */ - private float yaw; + private final float yaw; /** * The pitch angle of this Rotation */ - private float pitch; + private final float pitch; public Rotation(float yaw, float pitch) { this.yaw = yaw; @@ -110,6 +110,10 @@ public Rotation normalizeAndClamp() { ); } + public Rotation withPitch(float pitch) { + return new Rotation(this.yaw, pitch); + } + /** * Is really close to * diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index 39e68fd4f..7b30f4abb 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -162,7 +162,8 @@ public static Optional reachable(EntityPlayerSP entity, BlockPos pos, public static Optional reachable(EntityPlayerSP entity, BlockPos pos, double blockReachDistance, boolean wouldSneak) { IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(entity); - if (baritone.getPlayerContext().isLookingAt(pos)) { + IPlayerContext ctx = baritone.getPlayerContext(); + if (ctx.isLookingAt(pos)) { /* * why add 0.0001? * to indicate that we actually have a desired pitch @@ -173,7 +174,7 @@ public static Optional reachable(EntityPlayerSP entity, BlockPos pos, * * or if you're a normal person literally all this does it ensure that we don't nudge the pitch to a normal level */ - Rotation hypothetical = new Rotation(entity.rotationYaw, entity.rotationPitch + 0.0001F); + Rotation hypothetical = ctx.playerRotations().add(new Rotation(0, 0.0001F)); if (wouldSneak) { // the concern here is: what if we're looking at it now, but as soon as we start sneaking we no longer are RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, hypothetical, blockReachDistance, true); @@ -217,6 +218,7 @@ public static Optional reachable(EntityPlayerSP entity, BlockPos pos, */ public static Optional reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance, boolean wouldSneak) { Vec3d eyes = wouldSneak ? RayTraceUtils.inferSneakingEyePosition(entity) : entity.getPositionEyes(1.0F); + // TODO: pr/feature/blockFreeLook - Use playerRotations() here? Rotation rotation = calcRotationFromVec3d(eyes, offsetPos, new Rotation(entity.rotationYaw, entity.rotationPitch)); RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance, wouldSneak); //System.out.println(result); diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 32e5c22f5..7db3da562 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -22,6 +22,7 @@ import baritone.api.behavior.ILookBehavior; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.RotationMoveEvent; +import baritone.api.event.events.type.EventState; import baritone.api.utils.Rotation; public final class LookBehavior extends Behavior implements ILookBehavior { @@ -34,17 +35,19 @@ public final class LookBehavior extends Behavior implements ILookBehavior { */ private Rotation target; + private Rotation serverAngles; + /** * Whether or not rotations are currently being forced */ private boolean force; /** - * The last player yaw angle. Used when free looking + * The last player angles. Used when free looking * * @see Settings#freeLook */ - private float lastYaw; + private Rotation prevAngles; public LookBehavior(Baritone baritone) { super(baritone); @@ -53,11 +56,14 @@ public LookBehavior(Baritone baritone) { @Override public void updateTarget(Rotation target, boolean force) { this.target = target; - this.force = force || !Baritone.settings().freeLook.value; + this.force = !Baritone.settings().blockFreeLook.value && (force || !Baritone.settings().freeLook.value); } @Override public void onPlayerUpdate(PlayerUpdateEvent event) { + if (event.getState() == EventState.POST) { + this.serverAngles = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); + } if (this.target == null) { return; } @@ -80,14 +86,16 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { this.target = null; } if (silent) { - this.lastYaw = ctx.player().rotationYaw; + this.prevAngles = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); ctx.player().rotationYaw = this.target.getYaw(); + ctx.player().rotationPitch = this.target.getPitch(); } break; } case POST: { if (silent) { - ctx.player().rotationYaw = this.lastYaw; + ctx.player().rotationYaw = this.prevAngles.getYaw(); + ctx.player().rotationPitch = this.prevAngles.getPitch(); this.target = null; } break; @@ -103,6 +111,10 @@ public void pig() { } } + public Rotation getEffectiveAngles() { + return this.serverAngles; + } + @Override public void onPlayerRotationMove(RotationMoveEvent event) { if (this.target != null) { diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 575815ea2..b14b2d69c 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -599,9 +599,9 @@ static void switchToBestToolFor(IPlayerContext ctx, IBlockState b, ToolSet ts, b static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) { state.setTarget(new MovementTarget( - new Rotation(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), + RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(pos), - ctx.playerRotations()).getYaw(), ctx.player().rotationPitch), + ctx.playerRotations()).withPitch(ctx.playerRotations().getPitch()), false )).setInput(Input.MOVE_FORWARD, true); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index d36843cdd..2d8180356 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -234,11 +234,10 @@ public MovementState updateState(MovementState state) { if (safeMode()) { double destX = (src.getX() + 0.5) * 0.17 + (dest.getX() + 0.5) * 0.83; double destZ = (src.getZ() + 0.5) * 0.17 + (dest.getZ() + 0.5) * 0.83; - EntityPlayerSP player = ctx.player(); state.setTarget(new MovementState.MovementTarget( - new Rotation(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), + RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(destX, dest.getY(), destZ), - new Rotation(player.rotationYaw, player.rotationPitch)).getYaw(), player.rotationPitch), + ctx.playerRotations()).withPitch(ctx.playerRotations().getPitch()), false )).setInput(Input.MOVE_FORWARD, true); return state; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index cfa9d9260..88f1e26ff 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -190,9 +190,9 @@ public MovementState updateState(MovementState state) { boolean vine = fromDown.getBlock() == Blocks.VINE; Rotation rotation = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(positionToPlace), - new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch)); + ctx.playerRotations()); if (!ladder) { - state.setTarget(new MovementState.MovementTarget(new Rotation(ctx.player().rotationYaw, rotation.getPitch()), true)); + state.setTarget(new MovementState.MovementTarget(ctx.playerRotations().withPitch(rotation.getPitch()), true)); } boolean blockIsThere = MovementHelper.canWalkOn(ctx, src) || ladder; diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java index 3cb498acd..cc35c156c 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java @@ -17,12 +17,11 @@ package baritone.utils.player; +import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.cache.IWorldData; -import baritone.api.utils.Helper; -import baritone.api.utils.IPlayerContext; -import baritone.api.utils.IPlayerController; -import baritone.api.utils.RayTraceUtils; +import baritone.api.utils.*; +import baritone.behavior.LookBehavior; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; @@ -57,6 +56,15 @@ public IWorldData worldData() { return BaritoneAPI.getProvider().getPrimaryBaritone().getWorldProvider().getCurrentWorld(); } + @Override + public Rotation playerRotations() { + final Rotation lbTarget = ((LookBehavior) BaritoneAPI.getProvider().getPrimaryBaritone().getLookBehavior()).getEffectiveAngles(); + if (lbTarget == null || !Baritone.settings().blockFreeLook.value) { + return IPlayerContext.super.playerRotations(); + } + return lbTarget; + } + @Override public RayTraceResult objectMouseOver() { return RayTraceUtils.rayTraceTowards(player(), playerRotations(), playerController().getBlockReachDistance()); From fbe28e397e880e022c43af81c59dc8f088cd42b6 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Jun 2023 12:38:13 -0500 Subject: [PATCH 048/111] Make setting disabled by default --- 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 b49fce01b..bf3cb1bdd 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -726,7 +726,7 @@ public final class Settings { /** * Break and place blocks without having to force the client-sided rotations */ - public final Setting blockFreeLook = new Setting<>(true); + public final Setting blockFreeLook = new Setting<>(false); /** * Will cause some minor behavioral differences to ensure that Baritone works on anticheats. From a09e63d6aa654b85b3dbc75ad1044e1e4d031b45 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Jun 2023 13:14:52 -0500 Subject: [PATCH 049/111] appease codacy --- src/main/java/baritone/command/defaults/SelCommand.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/command/defaults/SelCommand.java b/src/main/java/baritone/command/defaults/SelCommand.java index 0a11c86a8..fb3608e75 100644 --- a/src/main/java/baritone/command/defaults/SelCommand.java +++ b/src/main/java/baritone/command/defaults/SelCommand.java @@ -294,12 +294,9 @@ public Stream tabComplete(String label, IArgConsumer args) throws Comman args.get(); } return args.tabCompleteDatatype(ForBlockOptionalMeta.INSTANCE); - } else if (action == Action.CYLINDER || action == Action.HCYLINDER) { - if (args.hasExactly(2)) { - if (args.getDatatypeForOrNull(ForBlockOptionalMeta.INSTANCE) != null) { - return args.tabCompleteDatatype(ForAxis.INSTANCE); - } - } + } else if (args.hasExactly(2) && (action == Action.CYLINDER || action == Action.HCYLINDER)) { + args.get(); + return args.tabCompleteDatatype(ForAxis.INSTANCE); } } else if (action == Action.EXPAND || action == Action.CONTRACT || action == Action.SHIFT) { if (args.hasExactlyOne()) { From 77ca36c7947541faef6e1519823c4b06c913bc88 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Jun 2023 15:49:04 -0500 Subject: [PATCH 050/111] Use `playerRotations` in `reachableOffset` --- src/api/java/baritone/api/utils/RotationUtils.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index 7b30f4abb..0d5a3ad1f 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -216,10 +216,10 @@ public static Optional reachable(EntityPlayerSP entity, BlockPos pos, * @param blockReachDistance The block reach distance of the entity * @return The optional rotation */ - public static Optional reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance, boolean wouldSneak) { + public static Optional reachableOffset(EntityPlayerSP entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance, boolean wouldSneak) { + IPlayerContext ctx = BaritoneAPI.getProvider().getBaritoneForPlayer(entity).getPlayerContext(); Vec3d eyes = wouldSneak ? RayTraceUtils.inferSneakingEyePosition(entity) : entity.getPositionEyes(1.0F); - // TODO: pr/feature/blockFreeLook - Use playerRotations() here? - Rotation rotation = calcRotationFromVec3d(eyes, offsetPos, new Rotation(entity.rotationYaw, entity.rotationPitch)); + Rotation rotation = calcRotationFromVec3d(eyes, offsetPos, ctx.playerRotations()); RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance, wouldSneak); //System.out.println(result); if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { @@ -242,7 +242,7 @@ public static Optional reachableOffset(Entity entity, BlockPos pos, Ve * @param blockReachDistance The block reach distance of the entity * @return The optional rotation */ - public static Optional reachableCenter(Entity entity, BlockPos pos, double blockReachDistance, boolean wouldSneak) { + public static Optional reachableCenter(EntityPlayerSP entity, BlockPos pos, double blockReachDistance, boolean wouldSneak) { return reachableOffset(entity, pos, VecUtils.calculateBlockCenter(entity.world, pos), blockReachDistance, wouldSneak); } } From 4317dca024ec0d68b3d402b82777a453f7c121b1 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Jun 2023 18:35:34 -0500 Subject: [PATCH 051/111] Determine target mode (client/server) in `updateTarget` --- src/api/java/baritone/api/Settings.java | 3 +- .../baritone/api/behavior/ILookBehavior.java | 13 +- .../java/baritone/behavior/LookBehavior.java | 125 +++++++++++------- 3 files changed, 87 insertions(+), 54 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index bf3cb1bdd..bcd3eaa63 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -724,7 +724,8 @@ public final class Settings { public final Setting freeLook = new Setting<>(true); /** - * Break and place blocks without having to force the client-sided rotations + * Break and place blocks without having to force the client-sided rotations. Having this setting enabled implies + * {@link #freeLook}. */ public final Setting blockFreeLook = new Setting<>(false); diff --git a/src/api/java/baritone/api/behavior/ILookBehavior.java b/src/api/java/baritone/api/behavior/ILookBehavior.java index 058a5dd88..218e8b59a 100644 --- a/src/api/java/baritone/api/behavior/ILookBehavior.java +++ b/src/api/java/baritone/api/behavior/ILookBehavior.java @@ -26,14 +26,11 @@ public interface ILookBehavior extends IBehavior { /** - * Updates the current {@link ILookBehavior} target to target - * the specified rotations on the next tick. If force is {@code true}, - * then freeLook will be overriden and angles will be set regardless. - * If any sort of block interaction is required, force should be {@code true}, - * otherwise, it should be {@code false}; + * Updates the current {@link ILookBehavior} target to target the specified rotations on the next tick. If any sort + * of block interaction is required, {@code blockInteract} should be {@code true}. * - * @param rotation The target rotations - * @param force Whether or not to "force" the rotations + * @param rotation The target rotations + * @param blockInteract Whether the target rotations are needed for a block interaction */ - void updateTarget(Rotation rotation, boolean force); + void updateTarget(Rotation rotation, boolean blockInteract); } diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 7db3da562..93e0af3bf 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -28,19 +28,11 @@ public final class LookBehavior extends Behavior implements ILookBehavior { /** - * Target's values are as follows: - *

- * getFirst() -> yaw - * getSecond() -> pitch + * The current look target, may be {@code null}. */ - private Rotation target; + private Target target; - private Rotation serverAngles; - - /** - * Whether or not rotations are currently being forced - */ - private boolean force; + private Rotation serverRotation; /** * The last player angles. Used when free looking @@ -54,50 +46,60 @@ public LookBehavior(Baritone baritone) { } @Override - public void updateTarget(Rotation target, boolean force) { - this.target = target; - this.force = !Baritone.settings().blockFreeLook.value && (force || !Baritone.settings().freeLook.value); + public void updateTarget(Rotation rotation, boolean blockInteract) { + this.target = new Target(rotation, blockInteract); } @Override public void onPlayerUpdate(PlayerUpdateEvent event) { + // Capture the player rotation before it's reset to determine the rotation the server knows + // Alternatively, this could be done with a packet event... Maybe that's a better idea. if (event.getState() == EventState.POST) { - this.serverAngles = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); + this.serverRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); } + + // There's nothing left to be done if there isn't a set target if (this.target == null) { return; } - // Whether or not we're going to silently set our angles - boolean silent = Baritone.settings().antiCheatCompatibility.value && !this.force; - switch (event.getState()) { case PRE: { - if (this.force) { - ctx.player().rotationYaw = this.target.getYaw(); - float oldPitch = ctx.player().rotationPitch; - float desiredPitch = this.target.getPitch(); - ctx.player().rotationPitch = desiredPitch; - ctx.player().rotationYaw += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; - ctx.player().rotationPitch += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; - if (desiredPitch == oldPitch && !Baritone.settings().freeLook.value) { - nudgeToLevel(); + switch (this.target.mode) { + case CLIENT: { + ctx.player().rotationYaw = this.target.rotation.getYaw(); + float oldPitch = ctx.player().rotationPitch; + float desiredPitch = this.target.rotation.getPitch(); + ctx.player().rotationPitch = desiredPitch; + ctx.player().rotationYaw += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; + ctx.player().rotationPitch += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; + if (desiredPitch == oldPitch && !Baritone.settings().freeLook.value) { + nudgeToLevel(); + } + // The target can be invalidated now since it won't be needed for RotationMoveEvent + this.target = null; + break; } - this.target = null; - } - if (silent) { - this.prevAngles = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); - ctx.player().rotationYaw = this.target.getYaw(); - ctx.player().rotationPitch = this.target.getPitch(); + case SERVER: { + // Copy the player's actual angles + this.prevAngles = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); + ctx.player().rotationYaw = this.target.rotation.getYaw(); + ctx.player().rotationPitch = this.target.rotation.getPitch(); + break; + } + default: + break; } break; } case POST: { - if (silent) { + // Reset the player's rotations back to their original values + if (this.target.mode == Target.Mode.SERVER) { ctx.player().rotationYaw = this.prevAngles.getYaw(); ctx.player().rotationPitch = this.prevAngles.getPitch(); - this.target = null; } + // The target is done being used for this game tick, so it can be invalidated + this.target = null; break; } default: @@ -107,25 +109,18 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { public void pig() { if (this.target != null) { - ctx.player().rotationYaw = this.target.getYaw(); + ctx.player().rotationYaw = this.target.rotation.getYaw(); } } public Rotation getEffectiveAngles() { - return this.serverAngles; + return this.serverRotation; } @Override public void onPlayerRotationMove(RotationMoveEvent event) { if (this.target != null) { - - 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.value && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE && !this.force) { - this.target = null; - } + event.setYaw(this.target.rotation.getYaw()); } } @@ -139,4 +134,44 @@ private void nudgeToLevel() { ctx.player().rotationPitch--; } } + + private static class Target { + + public final Rotation rotation; + public final Mode mode; + + public Target(Rotation rotation, boolean blockInteract) { + this.rotation = rotation; + this.mode = Mode.resolve(blockInteract); + } + + enum Mode { + /** + * Angles will be set client-side and are visual to the player + */ + CLIENT, + + /** + * Angles will be set server-side and are silent to the player + */ + SERVER, + + /** + * Angles will remain unaffected on both the client and server + */ + NONE; + + static Mode resolve(boolean blockInteract) { + final Settings settings = Baritone.settings(); + final boolean antiCheat = settings.antiCheatCompatibility.value; + final boolean blockFreeLook = settings.blockFreeLook.value; + final boolean freeLook = settings.freeLook.value; + + if (!freeLook && !blockFreeLook) return CLIENT; + if (!blockFreeLook && blockInteract) return CLIENT; + if (antiCheat || blockInteract) return SERVER; + return NONE; + } + } + } } From a7d15d1e32a1438bce8223a3483a76dcd5d14444 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Jun 2023 18:43:48 -0500 Subject: [PATCH 052/111] Consistent naming and comments for clarification --- .../java/baritone/behavior/LookBehavior.java | 30 ++++++++++++------- .../utils/player/PrimaryPlayerContext.java | 2 +- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 93e0af3bf..c38cee6f9 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -23,6 +23,7 @@ import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.RotationMoveEvent; import baritone.api.event.events.type.EventState; +import baritone.api.utils.IPlayerContext; import baritone.api.utils.Rotation; public final class LookBehavior extends Behavior implements ILookBehavior { @@ -32,14 +33,17 @@ public final class LookBehavior extends Behavior implements ILookBehavior { */ private Target target; + /** + * The rotation known to the server. Returned by {@link #getEffectiveRotation()} for use in {@link IPlayerContext}. + */ private Rotation serverRotation; /** - * The last player angles. Used when free looking + * The last player rotation. Used when free looking * * @see Settings#freeLook */ - private Rotation prevAngles; + private Rotation prevRotation; public LookBehavior(Baritone baritone) { super(baritone); @@ -81,8 +85,8 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { break; } case SERVER: { - // Copy the player's actual angles - this.prevAngles = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); + // Copy the player's actual rotation + this.prevRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); ctx.player().rotationYaw = this.target.rotation.getYaw(); ctx.player().rotationPitch = this.target.rotation.getPitch(); break; @@ -95,8 +99,8 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { case POST: { // Reset the player's rotations back to their original values if (this.target.mode == Target.Mode.SERVER) { - ctx.player().rotationYaw = this.prevAngles.getYaw(); - ctx.player().rotationPitch = this.prevAngles.getPitch(); + ctx.player().rotationYaw = this.prevRotation.getYaw(); + ctx.player().rotationPitch = this.prevRotation.getPitch(); } // The target is done being used for this game tick, so it can be invalidated this.target = null; @@ -113,7 +117,7 @@ public void pig() { } } - public Rotation getEffectiveAngles() { + public Rotation getEffectiveRotation() { return this.serverRotation; } @@ -147,17 +151,17 @@ public Target(Rotation rotation, boolean blockInteract) { enum Mode { /** - * Angles will be set client-side and are visual to the player + * Rotation will be set client-side and is visual to the player */ CLIENT, /** - * Angles will be set server-side and are silent to the player + * Rotation will be set server-side and is silent to the player */ SERVER, /** - * Angles will remain unaffected on both the client and server + * Rotation will remain unaffected on both the client and server */ NONE; @@ -169,7 +173,13 @@ static Mode resolve(boolean blockInteract) { if (!freeLook && !blockFreeLook) return CLIENT; if (!blockFreeLook && blockInteract) return CLIENT; + + // Regardless of if antiCheatCompatibility is enabled, if a blockInteract is requested then the player + // rotation needs to be set somehow, otherwise Baritone will halt since objectMouseOver() will just be + // whatever the player is mousing over visually. Let's just settle for setting it silently. if (antiCheat || blockInteract) return SERVER; + + // Pathing regularly without antiCheatCompatibility, don't set the player rotation return NONE; } } diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java index cc35c156c..e4484f0be 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java @@ -58,7 +58,7 @@ public IWorldData worldData() { @Override public Rotation playerRotations() { - final Rotation lbTarget = ((LookBehavior) BaritoneAPI.getProvider().getPrimaryBaritone().getLookBehavior()).getEffectiveAngles(); + final Rotation lbTarget = ((LookBehavior) BaritoneAPI.getProvider().getPrimaryBaritone().getLookBehavior()).getEffectiveRotation(); if (lbTarget == null || !Baritone.settings().blockFreeLook.value) { return IPlayerContext.super.playerRotations(); } From bb36ebfc0c7cb39ac24852fef1b28c25c995975d Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 11 Jun 2023 20:09:37 -0500 Subject: [PATCH 053/111] Use `IPlayerContext` for all `RotationUtils` methods Deprecates all old overloads --- .../baritone/api/utils/RotationUtils.java | 75 +++++++++++++------ .../baritone/pathing/movement/Movement.java | 2 +- .../movement/movements/MovementPillar.java | 2 +- .../java/baritone/process/BuilderProcess.java | 2 +- .../java/baritone/process/FarmProcess.java | 4 +- .../baritone/process/GetToBlockProcess.java | 2 +- .../java/baritone/process/MineProcess.java | 2 +- 7 files changed, 60 insertions(+), 29 deletions(-) diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index 0d5a3ad1f..1991ab878 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -134,14 +134,14 @@ public static Vec3d calcVec3dFromRotation(Rotation rotation) { * @param ctx Context for the viewing entity * @param pos The target block position * @return The optional rotation - * @see #reachable(EntityPlayerSP, BlockPos, double) + * @see #reachable(IPlayerContext, BlockPos, double) */ public static Optional reachable(IPlayerContext ctx, BlockPos pos) { - return reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()); + return reachable(ctx, pos, false); } public static Optional reachable(IPlayerContext ctx, BlockPos pos, boolean wouldSneak) { - return reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance(), wouldSneak); + return reachable(ctx, pos, ctx.playerController().getBlockReachDistance(), wouldSneak); } /** @@ -151,18 +151,16 @@ public static Optional reachable(IPlayerContext ctx, BlockPos pos, boo * 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 ctx Context for the viewing entity * @param pos The target block position * @param blockReachDistance The block reach distance of the entity * @return The optional rotation */ - public static Optional reachable(EntityPlayerSP entity, BlockPos pos, double blockReachDistance) { - return reachable(entity, pos, blockReachDistance, false); + public static Optional reachable(IPlayerContext ctx, BlockPos pos, double blockReachDistance) { + return reachable(ctx, pos, blockReachDistance, false); } - public static Optional reachable(EntityPlayerSP entity, BlockPos pos, double blockReachDistance, boolean wouldSneak) { - IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(entity); - IPlayerContext ctx = baritone.getPlayerContext(); + public static Optional reachable(IPlayerContext ctx, BlockPos pos, double blockReachDistance, boolean wouldSneak) { if (ctx.isLookingAt(pos)) { /* * why add 0.0001? @@ -177,7 +175,7 @@ public static Optional reachable(EntityPlayerSP entity, BlockPos pos, Rotation hypothetical = ctx.playerRotations().add(new Rotation(0, 0.0001F)); if (wouldSneak) { // the concern here is: what if we're looking at it now, but as soon as we start sneaking we no longer are - RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, hypothetical, blockReachDistance, true); + RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), hypothetical, blockReachDistance, true); if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK && result.getBlockPos().equals(pos)) { return Optional.of(hypothetical); // yes, if we sneaked we would still be looking at the block } @@ -185,19 +183,19 @@ public static Optional reachable(EntityPlayerSP entity, BlockPos pos, return Optional.of(hypothetical); } } - Optional possibleRotation = reachableCenter(entity, pos, blockReachDistance, wouldSneak); + Optional possibleRotation = reachableCenter(ctx, pos, blockReachDistance, wouldSneak); //System.out.println("center: " + possibleRotation); if (possibleRotation.isPresent()) { return possibleRotation; } - IBlockState state = entity.world.getBlockState(pos); - AxisAlignedBB aabb = state.getBoundingBox(entity.world, pos); + IBlockState state = ctx.world().getBlockState(pos); + AxisAlignedBB aabb = state.getBoundingBox(ctx.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), blockReachDistance, wouldSneak); + possibleRotation = reachableOffset(ctx, pos, new Vec3d(pos).add(xDiff, yDiff, zDiff), blockReachDistance, wouldSneak); if (possibleRotation.isPresent()) { return possibleRotation; } @@ -210,23 +208,22 @@ public static Optional reachable(EntityPlayerSP entity, BlockPos pos, * 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 ctx Context for the viewing entity * @param pos The target block position * @param offsetPos The position of the block with the offset applied. * @param blockReachDistance The block reach distance of the entity * @return The optional rotation */ - public static Optional reachableOffset(EntityPlayerSP entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance, boolean wouldSneak) { - IPlayerContext ctx = BaritoneAPI.getProvider().getBaritoneForPlayer(entity).getPlayerContext(); - Vec3d eyes = wouldSneak ? RayTraceUtils.inferSneakingEyePosition(entity) : entity.getPositionEyes(1.0F); + public static Optional reachableOffset(IPlayerContext ctx, BlockPos pos, Vec3d offsetPos, double blockReachDistance, boolean wouldSneak) { + Vec3d eyes = wouldSneak ? RayTraceUtils.inferSneakingEyePosition(ctx.player()) : ctx.player().getPositionEyes(1.0F); Rotation rotation = calcRotationFromVec3d(eyes, offsetPos, ctx.playerRotations()); - RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance, wouldSneak); + RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rotation, blockReachDistance, wouldSneak); //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 && result.getBlockPos().equals(pos.down())) { + if (ctx.world().getBlockState(pos).getBlock() instanceof BlockFire && result.getBlockPos().equals(pos.down())) { return Optional.of(rotation); } } @@ -237,12 +234,46 @@ public static Optional reachableOffset(EntityPlayerSP entity, BlockPos * 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 ctx Context for the viewing entity * @param pos The target block position * @param blockReachDistance The block reach distance of the entity * @return The optional rotation */ - public static Optional reachableCenter(EntityPlayerSP entity, BlockPos pos, double blockReachDistance, boolean wouldSneak) { + public static Optional reachableCenter(IPlayerContext ctx, BlockPos pos, double blockReachDistance, boolean wouldSneak) { + return reachableOffset(ctx, pos, VecUtils.calculateBlockCenter(ctx.world(), pos), blockReachDistance, wouldSneak); + } + + @Deprecated + public static Optional reachable(EntityPlayerSP entity, BlockPos pos, double blockReachDistance) { + return reachable(entity, pos, blockReachDistance, false); + } + + @Deprecated + public static Optional reachable(EntityPlayerSP entity, BlockPos pos, double blockReachDistance, boolean wouldSneak) { + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(entity); + IPlayerContext ctx = baritone.getPlayerContext(); + return reachable(ctx, pos, blockReachDistance, wouldSneak); + } + + @Deprecated + public static Optional reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance, boolean wouldSneak) { + Vec3d eyes = wouldSneak ? RayTraceUtils.inferSneakingEyePosition(entity) : entity.getPositionEyes(1.0F); + Rotation rotation = calcRotationFromVec3d(eyes, offsetPos, new Rotation(entity.rotationYaw, entity.rotationPitch)); + RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance, wouldSneak); + //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 && result.getBlockPos().equals(pos.down())) { + return Optional.of(rotation); + } + } + return Optional.empty(); + } + + @Deprecated + public static Optional reachableCenter(Entity entity, BlockPos pos, double blockReachDistance, boolean wouldSneak) { return reachableOffset(entity, pos, VecUtils.calculateBlockCenter(entity.world, pos), blockReachDistance, wouldSneak); } } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index c46b24dea..5a17d26c5 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -164,7 +164,7 @@ protected boolean prepared(MovementState state) { if (!MovementHelper.canWalkThrough(ctx, blockPos) && !(BlockStateInterface.getBlock(ctx, blockPos) instanceof BlockLiquid)) { // can't break liquid, so don't try somethingInTheWay = true; MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, blockPos)); - Optional reachable = RotationUtils.reachable(ctx.player(), blockPos, ctx.playerController().getBlockReachDistance()); + Optional reachable = RotationUtils.reachable(ctx, blockPos, ctx.playerController().getBlockReachDistance()); if (reachable.isPresent()) { Rotation rotTowardsBlock = reachable.get(); state.setTarget(new MovementState.MovementTarget(rotTowardsBlock, true)); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 88f1e26ff..0198b28fe 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -251,7 +251,7 @@ public MovementState updateState(MovementState state) { Block fr = frState.getBlock(); // TODO: Evaluate usage of getMaterial().isReplaceable() if (!(fr instanceof BlockAir || frState.getMaterial().isReplaceable())) { - RotationUtils.reachable(ctx.player(), src, ctx.playerController().getBlockReachDistance()) + RotationUtils.reachable(ctx, src, ctx.playerController().getBlockReachDistance()) .map(rot -> new MovementState.MovementTarget(rot, true)) .ifPresent(state::setTarget); state.setInput(Input.JUMP, false); // breaking is like 5x slower when you're jumping diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index c7868a4a0..6f8582457 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -283,7 +283,7 @@ private Optional> toBreakNearPlayer(BuilderCalcu IBlockState curr = bcc.bsi.get0(x, y, z); if (curr.getBlock() != Blocks.AIR && !(curr.getBlock() instanceof BlockLiquid) && !valid(curr, desired, false)) { BetterBlockPos pos = new BetterBlockPos(x, y, z); - Optional rot = RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()); + Optional rot = RotationUtils.reachable(ctx, pos, ctx.playerController().getBlockReachDistance()); if (rot.isPresent()) { return Optional.of(new Tuple<>(pos, rot.get())); } diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index a9188299c..1536bdb61 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -268,7 +268,7 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { both.addAll(openSoulsand); for (BlockPos pos : both) { boolean soulsand = openSoulsand.contains(pos); - Optional rot = RotationUtils.reachableOffset(ctx.player(), pos, new Vec3d(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance(), false); + Optional rot = RotationUtils.reachableOffset(ctx, pos, new Vec3d(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance(), false); if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, soulsand ? this::isNetherWart : this::isPlantable)) { RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance()); if (result.typeOfHit == RayTraceResult.Type.BLOCK && result.sideHit == EnumFacing.UP) { @@ -286,7 +286,7 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { continue; } Vec3d faceCenter = new Vec3d(pos).add(0.5, 0.5, 0.5).add(new Vec3d(dir.getDirectionVec()).scale(0.5)); - Optional rot = RotationUtils.reachableOffset(ctx.player(), pos, faceCenter, ctx.playerController().getBlockReachDistance(), false); + Optional rot = RotationUtils.reachableOffset(ctx, pos, faceCenter, ctx.playerController().getBlockReachDistance(), false); if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, this::isCocoa)) { RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance()); if (result.typeOfHit == RayTraceResult.Type.BLOCK && result.sideHit == dir) { diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 16fc3dda5..7f8376b84 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -210,7 +210,7 @@ private Goal createGoal(BlockPos pos) { private boolean rightClick() { for (BlockPos pos : knownLocations) { - Optional reachable = RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()); + Optional reachable = RotationUtils.reachable(ctx, pos, ctx.playerController().getBlockReachDistance()); if (reachable.isPresent()) { baritone.getLookBehavior().updateTarget(reachable.get(), true); if (knownLocations.contains(ctx.getSelectedBlock().orElse(null))) { diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 6880dd86c..e7d7b3365 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -397,7 +397,7 @@ private boolean addNearby() { // is an x-ray and it'll get caught if (filter.has(bsi.get0(x, y, z))) { BlockPos pos = new BlockPos(x, y, z); - if ((Baritone.settings().legitMineIncludeDiagonals.value && knownOreLocations.stream().anyMatch(ore -> ore.distanceSq(pos) <= 2 /* sq means this is pytha dist <= sqrt(2) */)) || RotationUtils.reachable(ctx.player(), pos, fakedBlockReachDistance).isPresent()) { + if ((Baritone.settings().legitMineIncludeDiagonals.value && knownOreLocations.stream().anyMatch(ore -> ore.distanceSq(pos) <= 2 /* sq means this is pytha dist <= sqrt(2) */)) || RotationUtils.reachable(ctx, pos, fakedBlockReachDistance).isPresent()) { knownOreLocations.add(pos); } } From 1d5ee079b4aea9925041eae05a923da513b1ba5e Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 12:11:50 -0500 Subject: [PATCH 054/111] Read `serverRotation` from packet and invalidate on world load --- .../java/baritone/behavior/LookBehavior.java | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index c38cee6f9..d1e5d244f 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -20,11 +20,13 @@ import baritone.Baritone; import baritone.api.Settings; import baritone.api.behavior.ILookBehavior; +import baritone.api.event.events.PacketEvent; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.RotationMoveEvent; -import baritone.api.event.events.type.EventState; +import baritone.api.event.events.WorldEvent; import baritone.api.utils.IPlayerContext; import baritone.api.utils.Rotation; +import net.minecraft.network.play.client.CPacketPlayer; public final class LookBehavior extends Behavior implements ILookBehavior { @@ -56,17 +58,9 @@ public void updateTarget(Rotation rotation, boolean blockInteract) { @Override public void onPlayerUpdate(PlayerUpdateEvent event) { - // Capture the player rotation before it's reset to determine the rotation the server knows - // Alternatively, this could be done with a packet event... Maybe that's a better idea. - if (event.getState() == EventState.POST) { - this.serverRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); - } - - // There's nothing left to be done if there isn't a set target if (this.target == null) { return; } - switch (event.getState()) { case PRE: { switch (this.target.mode) { @@ -111,6 +105,24 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { } } + @Override + public void onSendPacket(PacketEvent event) { + if (!(event.getPacket() instanceof CPacketPlayer)) { + return; + } + + final CPacketPlayer packet = (CPacketPlayer) event.getPacket(); + if (packet instanceof CPacketPlayer.Rotation || packet instanceof CPacketPlayer.PositionRotation) { + this.serverRotation = new Rotation(packet.getYaw(0.0f), packet.getPitch(0.0f)); + } + } + + @Override + public void onWorldEvent(WorldEvent event) { + this.serverRotation = null; + this.target = null; + } + public void pig() { if (this.target != null) { ctx.player().rotationYaw = this.target.rotation.getYaw(); From 67a085c95fca4be8a6f85d4c2a5dfcc0bb9f3d89 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 13:16:37 -0500 Subject: [PATCH 055/111] Batch together GL_LINES draw calls --- .../baritone/command/defaults/SelCommand.java | 2 +- .../baritone/selection/SelectionRenderer.java | 8 +-- src/main/java/baritone/utils/IRenderer.java | 16 +++-- .../java/baritone/utils/PathRenderer.java | 65 +++++++++++++------ 4 files changed, 60 insertions(+), 31 deletions(-) diff --git a/src/main/java/baritone/command/defaults/SelCommand.java b/src/main/java/baritone/command/defaults/SelCommand.java index 5677eec3c..d6c2e890d 100644 --- a/src/main/java/baritone/command/defaults/SelCommand.java +++ b/src/main/java/baritone/command/defaults/SelCommand.java @@ -72,7 +72,7 @@ public void onRenderPass(RenderEvent event) { float lineWidth = Baritone.settings().selectionLineWidth.value; boolean ignoreDepth = Baritone.settings().renderSelectionIgnoreDepth.value; IRenderer.startLines(color, opacity, lineWidth, ignoreDepth); - IRenderer.drawAABB(new AxisAlignedBB(pos1, pos1.add(1, 1, 1))); + IRenderer.emitAABB(new AxisAlignedBB(pos1, pos1.add(1, 1, 1))); IRenderer.endLines(ignoreDepth); } }); diff --git a/src/main/java/baritone/selection/SelectionRenderer.java b/src/main/java/baritone/selection/SelectionRenderer.java index 89104d030..b688e9670 100644 --- a/src/main/java/baritone/selection/SelectionRenderer.java +++ b/src/main/java/baritone/selection/SelectionRenderer.java @@ -23,27 +23,27 @@ public static void renderSelections(ISelection[] selections) { boolean ignoreDepth = settings.renderSelectionIgnoreDepth.value; float lineWidth = settings.selectionLineWidth.value; - if (!settings.renderSelection.value) { + if (!settings.renderSelection.value || selections.length == 0) { return; } IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth, ignoreDepth); for (ISelection selection : selections) { - IRenderer.drawAABB(selection.aabb(), SELECTION_BOX_EXPANSION); + IRenderer.emitAABB(selection.aabb(), SELECTION_BOX_EXPANSION); } if (settings.renderSelectionCorners.value) { IRenderer.glColor(settings.colorSelectionPos1.value, opacity); for (ISelection selection : selections) { - IRenderer.drawAABB(new AxisAlignedBB(selection.pos1(), selection.pos1().add(1, 1, 1))); + IRenderer.emitAABB(new AxisAlignedBB(selection.pos1(), selection.pos1().add(1, 1, 1))); } IRenderer.glColor(settings.colorSelectionPos2.value, opacity); for (ISelection selection : selections) { - IRenderer.drawAABB(new AxisAlignedBB(selection.pos2(), selection.pos2().add(1, 1, 1))); + IRenderer.emitAABB(new AxisAlignedBB(selection.pos2(), selection.pos2().add(1, 1, 1))); } } diff --git a/src/main/java/baritone/utils/IRenderer.java b/src/main/java/baritone/utils/IRenderer.java index e5a5ee907..3476c0307 100644 --- a/src/main/java/baritone/utils/IRenderer.java +++ b/src/main/java/baritone/utils/IRenderer.java @@ -54,6 +54,7 @@ static void startLines(Color color, float alpha, float lineWidth, boolean ignore if (ignoreDepth) { GlStateManager.disableDepth(); } + buffer.begin(GL_LINES, DefaultVertexFormats.POSITION); } static void startLines(Color color, float lineWidth, boolean ignoreDepth) { @@ -61,6 +62,7 @@ static void startLines(Color color, float lineWidth, boolean ignoreDepth) { } static void endLines(boolean ignoredDepth) { + tessellator.draw(); if (ignoredDepth) { GlStateManager.enableDepth(); } @@ -70,10 +72,9 @@ static void endLines(boolean ignoredDepth) { GlStateManager.disableBlend(); } - static void drawAABB(AxisAlignedBB aabb) { + static void emitAABB(AxisAlignedBB aabb) { AxisAlignedBB toDraw = aabb.offset(-renderManager.viewerPosX, -renderManager.viewerPosY, -renderManager.viewerPosZ); - buffer.begin(GL_LINES, DefaultVertexFormats.POSITION); // bottom buffer.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); buffer.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex(); @@ -101,10 +102,15 @@ static void drawAABB(AxisAlignedBB aabb) { buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex(); buffer.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); - tessellator.draw(); } - static void drawAABB(AxisAlignedBB aabb, double expand) { - drawAABB(aabb.grow(expand, expand, expand)); + static void emitAABB(AxisAlignedBB aabb, double expand) { + emitAABB(aabb.grow(expand, expand, expand)); + } + + static void drawAABB(AxisAlignedBB aabb) { + buffer.begin(GL_LINES, DefaultVertexFormats.POSITION); + emitAABB(aabb); + tessellator.draw(); } } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 2fe224706..2aef0ab54 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -29,7 +29,6 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.tileentity.TileEntityBeaconRenderer; -import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; import net.minecraft.util.math.AxisAlignedBB; @@ -37,6 +36,7 @@ import net.minecraft.util.math.MathHelper; import java.awt.*; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -76,7 +76,7 @@ public static void render(RenderEvent event, PathingBehavior behavior) { } if (goal != null && settings.renderGoal.value) { - drawDankLitGoalBox(renderView, goal, partialTicks, settings.colorGoalBox.value); + drawGoal(renderView, goal, partialTicks, settings.colorGoalBox.value); } if (!settings.renderPath.value) { @@ -153,26 +153,28 @@ public static void drawPath(IPath path, int startIndex, Color color, boolean fad IRenderer.glColor(color, alpha); } - drawLine(start.x, start.y, start.z, end.x, end.y, end.z); - - tessellator.draw(); + emitLine(start.x, start.y, start.z, end.x, end.y, end.z); } IRenderer.endLines(settings.renderPathIgnoreDepth.value); } - public static void drawLine(double x1, double y1, double z1, double x2, double y2, double z2) { + public static void emitLine(double x1, double y1, double z1, double x2, double y2, double z2) { double vpX = renderManager.viewerPosX; double vpY = renderManager.viewerPosY; double vpZ = renderManager.viewerPosZ; boolean renderPathAsFrickinThingy = !settings.renderPathAsLine.value; - buffer.begin(renderPathAsFrickinThingy ? GL_LINE_STRIP : GL_LINES, DefaultVertexFormats.POSITION); buffer.pos(x1 + 0.5D - vpX, y1 + 0.5D - vpY, z1 + 0.5D - vpZ).endVertex(); buffer.pos(x2 + 0.5D - vpX, y2 + 0.5D - vpY, z2 + 0.5D - vpZ).endVertex(); if (renderPathAsFrickinThingy) { + buffer.pos(x2 + 0.5D - vpX, y2 + 0.5D - vpY, z2 + 0.5D - vpZ).endVertex(); + buffer.pos(x2 + 0.5D - vpX, y2 + 0.53D - vpY, z2 + 0.5D - vpZ).endVertex(); + buffer.pos(x2 + 0.5D - vpX, y2 + 0.53D - vpY, z2 + 0.5D - vpZ).endVertex(); + buffer.pos(x1 + 0.5D - vpX, y1 + 0.53D - vpY, z1 + 0.5D - vpZ).endVertex(); + buffer.pos(x1 + 0.5D - vpX, y1 + 0.53D - vpY, z1 + 0.5D - vpZ).endVertex(); buffer.pos(x1 + 0.5D - vpX, y1 + 0.5D - vpY, z1 + 0.5D - vpZ).endVertex(); } @@ -194,13 +196,17 @@ public static void drawManySelectionBoxes(Entity player, Collection po toDraw = state.getSelectedBoundingBox(player.world, pos); } - IRenderer.drawAABB(toDraw, .002D); + IRenderer.emitAABB(toDraw, .002D); }); IRenderer.endLines(settings.renderSelectionBoxesIgnoreDepth.value); } - public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTicks, Color color) { + public static void drawGoal(Entity player, Goal goal, float partialTicks, Color color) { + drawGoal(player, goal, partialTicks, color, true); + } + + public static void drawGoal(Entity player, Goal goal, float partialTicks, Color color, boolean setupRender) { double renderPosX = renderManager.viewerPosX; double renderPosY = renderManager.viewerPosY; double renderPosZ = renderManager.viewerPosZ; @@ -232,6 +238,7 @@ public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTic y2 -= 0.5; maxY--; } + drawDankLitGoalBox(color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender); } else if (goal instanceof GoalXZ) { GoalXZ goalPos = (GoalXZ) goal; @@ -273,14 +280,22 @@ public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTic y2 = 0; minY = 0 - renderPosY; maxY = 256 - renderPosY; + drawDankLitGoalBox(color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender); } else if (goal instanceof GoalComposite) { + // Simple way to determine if goals can be batched, without having some sort of GoalRenderer + boolean batch = Arrays.stream(((GoalComposite) goal).goals()).allMatch(IGoalRenderPos.class::isInstance); + + if (batch) { + IRenderer.startLines(color, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value); + } for (Goal g : ((GoalComposite) goal).goals()) { - drawDankLitGoalBox(player, g, partialTicks, color); + drawGoal(player, g, partialTicks, color, !batch); + } + if (batch) { + IRenderer.endLines(settings.renderGoalIgnoreDepth.value); } - return; } else if (goal instanceof GoalInverted) { - drawDankLitGoalBox(player, ((GoalInverted) goal).origin, partialTicks, settings.colorInvertedGoalBox.value); - return; + drawGoal(player, ((GoalInverted) goal).origin, partialTicks, settings.colorInvertedGoalBox.value); } else if (goal instanceof GoalYLevel) { GoalYLevel goalpos = (GoalYLevel) goal; minX = player.posX - settings.yLevelBoxSize.value - renderPosX; @@ -291,16 +306,18 @@ public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTic maxY = minY + 2; y1 = 1 + y + goalpos.level - renderPosY; y2 = 1 - y + goalpos.level - renderPosY; - } else { - return; + drawDankLitGoalBox(color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender); } + } - IRenderer.startLines(color, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value); + private static void drawDankLitGoalBox(Color color, double minX, double maxX, double minZ, double maxZ, double minY, double maxY, double y1, double y2, boolean setupRender) { + if (setupRender) { + IRenderer.startLines(color, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value); + } renderHorizontalQuad(minX, maxX, minZ, maxZ, y1); renderHorizontalQuad(minX, maxX, minZ, maxZ, y2); - buffer.begin(GL_LINES, DefaultVertexFormats.POSITION); buffer.pos(minX, minY, minZ).endVertex(); buffer.pos(minX, maxY, minZ).endVertex(); buffer.pos(maxX, minY, minZ).endVertex(); @@ -309,19 +326,25 @@ public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTic buffer.pos(maxX, maxY, maxZ).endVertex(); buffer.pos(minX, minY, maxZ).endVertex(); buffer.pos(minX, maxY, maxZ).endVertex(); - tessellator.draw(); - IRenderer.endLines(settings.renderGoalIgnoreDepth.value); + if (setupRender) { + IRenderer.endLines(settings.renderGoalIgnoreDepth.value); + } } 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, minZ).endVertex(); + buffer.pos(maxX, y, maxZ).endVertex(); + buffer.pos(maxX, y, maxZ).endVertex(); buffer.pos(minX, y, maxZ).endVertex(); - tessellator.draw(); + + buffer.pos(minX, y, maxZ).endVertex(); + buffer.pos(minX, y, minZ).endVertex(); } } } From c8a0ae9e102e9f85efba642f8a52744d7dc2d1d1 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 13:44:08 -0500 Subject: [PATCH 056/111] Do `nudgeToLevel` and `randomLooking` when using freeLook --- .../java/baritone/behavior/LookBehavior.java | 46 ++++++++----------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index d1e5d244f..0dc56a3e2 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -58,43 +58,37 @@ public void updateTarget(Rotation rotation, boolean blockInteract) { @Override public void onPlayerUpdate(PlayerUpdateEvent event) { - if (this.target == null) { + if (this.target == null || this.target.mode == Target.Mode.NONE) { return; } switch (event.getState()) { case PRE: { - switch (this.target.mode) { - case CLIENT: { - ctx.player().rotationYaw = this.target.rotation.getYaw(); - float oldPitch = ctx.player().rotationPitch; - float desiredPitch = this.target.rotation.getPitch(); - ctx.player().rotationPitch = desiredPitch; - ctx.player().rotationYaw += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; - ctx.player().rotationPitch += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; - if (desiredPitch == oldPitch && !Baritone.settings().freeLook.value) { - nudgeToLevel(); - } - // The target can be invalidated now since it won't be needed for RotationMoveEvent - this.target = null; - break; - } - case SERVER: { - // Copy the player's actual rotation - this.prevRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); - ctx.player().rotationYaw = this.target.rotation.getYaw(); - ctx.player().rotationPitch = this.target.rotation.getPitch(); - break; - } - default: - break; + if (this.target.mode == Target.Mode.SERVER) { + this.prevRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); + } + + ctx.player().rotationYaw = this.target.rotation.getYaw(); + float oldPitch = ctx.playerRotations().getPitch(); + float desiredPitch = this.target.rotation.getPitch(); + ctx.player().rotationPitch = desiredPitch; + ctx.player().rotationYaw += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; + ctx.player().rotationPitch += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; + if (desiredPitch == oldPitch) { + nudgeToLevel(); + } + + if (this.target.mode == Target.Mode.CLIENT) { + // The target can be invalidated now since it won't be needed for RotationMoveEvent + this.target = null; } break; } case POST: { // Reset the player's rotations back to their original values - if (this.target.mode == Target.Mode.SERVER) { + if (this.prevRotation != null) { ctx.player().rotationYaw = this.prevRotation.getYaw(); ctx.player().rotationPitch = this.prevRotation.getPitch(); + this.prevRotation = null; } // The target is done being used for this game tick, so it can be invalidated this.target = null; From ed34ae73c002d5b23e0e6efc36283dfbe4c78fb7 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 13:46:10 -0500 Subject: [PATCH 057/111] Fix `Mode.NONE` target invalidation --- src/main/java/baritone/behavior/LookBehavior.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 0dc56a3e2..1e109482c 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -58,11 +58,14 @@ public void updateTarget(Rotation rotation, boolean blockInteract) { @Override public void onPlayerUpdate(PlayerUpdateEvent event) { - if (this.target == null || this.target.mode == Target.Mode.NONE) { + if (this.target == null) { return; } switch (event.getState()) { case PRE: { + if (this.target.mode == Target.Mode.NONE) { + return; + } if (this.target.mode == Target.Mode.SERVER) { this.prevRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); } From 7da802a2389b832b79c41b26f6b4bf4025a9a84e Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 16:21:05 -0500 Subject: [PATCH 058/111] Fix `censorCoordinates` recalc bug Adds `equals` and `toString` implementations where needed Replaces `toString` equality check with actual `equals` check in `forceRevalidate` --- .../baritone/api/pathing/goals/GoalAxis.java | 5 ++ .../baritone/api/pathing/goals/GoalBlock.java | 11 ++++ .../api/pathing/goals/GoalComposite.java | 9 +++ .../api/pathing/goals/GoalGetToBlock.java | 11 ++++ .../api/pathing/goals/GoalInverted.java | 11 ++++ .../baritone/api/pathing/goals/GoalNear.java | 12 ++++ .../api/pathing/goals/GoalRunAway.java | 12 ++++ .../pathing/goals/GoalStrictDirection.java | 13 +++++ .../api/pathing/goals/GoalTwoBlocks.java | 11 ++++ .../baritone/api/pathing/goals/GoalXZ.java | 10 ++++ .../api/pathing/goals/GoalYLevel.java | 9 +++ .../java/baritone/process/BuilderProcess.java | 57 +++++++++++++++++-- .../java/baritone/process/MineProcess.java | 15 +++++ .../baritone/utils/PathingControlManager.java | 2 +- 14 files changed, 183 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalAxis.java b/src/api/java/baritone/api/pathing/goals/GoalAxis.java index 7c9b26705..ad8fb892e 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalAxis.java +++ b/src/api/java/baritone/api/pathing/goals/GoalAxis.java @@ -42,6 +42,11 @@ public double heuristic(int x0, int y, int z0) { return flatAxisDistance * BaritoneAPI.getSettings().costHeuristic.value + GoalYLevel.calculate(BaritoneAPI.getSettings().axisHeight.value, y); } + @Override + public boolean equals(Object o) { + return o.getClass() == GoalAxis.class; + } + @Override public String toString() { return "GoalAxis"; diff --git a/src/api/java/baritone/api/pathing/goals/GoalBlock.java b/src/api/java/baritone/api/pathing/goals/GoalBlock.java index bd339549b..ad2c3eadb 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalBlock.java @@ -66,6 +66,17 @@ public double heuristic(int x, int y, int z) { return calculate(xDiff, yDiff, zDiff); } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GoalBlock goal = (GoalBlock) o; + if (x != goal.x) return false; + if (y != goal.y) return false; + return z == goal.z; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalComposite.java b/src/api/java/baritone/api/pathing/goals/GoalComposite.java index 47522492b..f407fe733 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalComposite.java +++ b/src/api/java/baritone/api/pathing/goals/GoalComposite.java @@ -67,6 +67,15 @@ public double heuristic() { return min; } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GoalComposite goal = (GoalComposite) o; + return Arrays.equals(goals, goal.goals); + } + @Override public String toString() { return "GoalComposite" + Arrays.toString(goals); diff --git a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java index 8d6fdcb30..3d2c0713a 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java @@ -60,6 +60,17 @@ public double heuristic(int x, int y, int z) { return GoalBlock.calculate(xDiff, yDiff < 0 ? yDiff + 1 : yDiff, zDiff); } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GoalGetToBlock goal = (GoalGetToBlock) o; + if (x != goal.x) return false; + if (y != goal.y) return false; + return z == goal.z; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalInverted.java b/src/api/java/baritone/api/pathing/goals/GoalInverted.java index 354e2ce39..acfdd68b2 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalInverted.java +++ b/src/api/java/baritone/api/pathing/goals/GoalInverted.java @@ -17,6 +17,8 @@ package baritone.api.pathing.goals; +import java.util.Objects; + /** * Invert any goal. *

@@ -50,6 +52,15 @@ public double heuristic() { return Double.NEGATIVE_INFINITY; } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GoalInverted goal = (GoalInverted) o; + return Objects.equals(origin, goal.origin); + } + @Override public String toString() { return String.format("GoalInverted{%s}", origin.toString()); diff --git a/src/api/java/baritone/api/pathing/goals/GoalNear.java b/src/api/java/baritone/api/pathing/goals/GoalNear.java index 2252446cd..44f0ab040 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalNear.java +++ b/src/api/java/baritone/api/pathing/goals/GoalNear.java @@ -86,6 +86,18 @@ public BlockPos getGoalPos() { return new BlockPos(x, y, z); } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GoalNear goal = (GoalNear) o; + if (x != goal.x) return false; + if (y != goal.y) return false; + if (z != goal.z) return false; + return rangeSq == goal.rangeSq; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index b704ae4a6..3d7caa734 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -23,6 +23,7 @@ import net.minecraft.util.math.BlockPos; import java.util.Arrays; +import java.util.Objects; /** * Useful for automated combat (retreating specifically) @@ -124,6 +125,17 @@ public double heuristic() {// TODO less hacky solution return maxInside; } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GoalRunAway goal = (GoalRunAway) o; + if (distanceSq != goal.distanceSq) return false; + if (!Arrays.equals(from, goal.from)) return false; + return Objects.equals(maintainY, goal.maintainY); + } + @Override public String toString() { if (maintainY != null) { diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java index e93f47ac0..86208f0ca 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java +++ b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java @@ -69,6 +69,19 @@ public double heuristic() { return Double.NEGATIVE_INFINITY; } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GoalStrictDirection goal = (GoalStrictDirection) o; + if (x != goal.x) return false; + if (y != goal.y) return false; + if (z != goal.z) return false; + if (dx != goal.dx) return false; + return dz == goal.dz; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java index 27be981e4..4df65f609 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java +++ b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java @@ -72,6 +72,17 @@ public BlockPos getGoalPos() { return new BlockPos(x, y, z); } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GoalTwoBlocks goal = (GoalTwoBlocks) o; + if (x != goal.x) return false; + if (y != goal.y) return false; + return z == goal.z; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalXZ.java b/src/api/java/baritone/api/pathing/goals/GoalXZ.java index 63d39cd78..c77743389 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalXZ.java +++ b/src/api/java/baritone/api/pathing/goals/GoalXZ.java @@ -64,6 +64,16 @@ public double heuristic(int x, int y, int z) {//mostly copied from GoalBlock return calculate(xDiff, zDiff); } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GoalXZ goal = (GoalXZ) o; + if (x != goal.x) return false; + return z == goal.z; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java index 603ef9bd1..8fc7850b9 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java +++ b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java @@ -58,6 +58,15 @@ public static double calculate(int goalY, int currentY) { return 0; } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GoalYLevel goal = (GoalYLevel) o; + return level == goal.level; + } + @Override public String toString() { return String.format( diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index c7868a4a0..f9514fb95 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -30,10 +30,7 @@ import baritone.api.schematic.IStaticSchematic; import baritone.api.schematic.SubstituteSchematic; import baritone.api.schematic.format.ISchematicFormat; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.RayTraceUtils; -import baritone.api.utils.Rotation; -import baritone.api.utils.RotationUtils; +import baritone.api.utils.*; import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -764,6 +761,16 @@ public double heuristic(int x, int y, int z) { return primary.heuristic(x, y, z); } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + JankyGoalComposite goal = (JankyGoalComposite) o; + if (!Objects.equals(primary, goal.primary)) return false; + return Objects.equals(fallback, goal.fallback); + } + @Override public String toString() { return "JankyComposite Primary: " + primary + " Fallback: " + fallback; @@ -785,6 +792,16 @@ public boolean isInGoal(int x, int y, int z) { // but any other adjacent works for breaking, including inside or below return super.isInGoal(x, y, z); } + + @Override + public String toString() { + return String.format( + "GoalBreak{x=%s,y=%s,z=%s}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) + ); + } } private Goal placementGoal(BlockPos pos, BuilderCalculationContext bcc) { @@ -828,6 +845,7 @@ public GoalAdjacent(BlockPos pos, BlockPos no, boolean allowSameLevel) { this.allowSameLevel = allowSameLevel; } + @Override public boolean isInGoal(int x, int y, int z) { if (x == this.x && y == this.y && z == this.z) { return false; @@ -844,10 +862,30 @@ public boolean isInGoal(int x, int y, int z) { return super.isInGoal(x, y, z); } + @Override public double heuristic(int x, int y, int z) { // prioritize lower y coordinates return this.y * 100 + super.heuristic(x, y, z); } + + @Override + public boolean equals(Object o) { + if (!super.equals(o)) return false; + + GoalAdjacent goal = (GoalAdjacent) o; + if (allowSameLevel != goal.allowSameLevel) return false; + return Objects.equals(no, goal.no); + } + + @Override + public String toString() { + return String.format( + "GoalAdjacent{x=%s,y=%s,z=%s}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) + ); + } } public static class GoalPlace extends GoalBlock { @@ -856,10 +894,21 @@ public GoalPlace(BlockPos placeAt) { super(placeAt.up()); } + @Override public double heuristic(int x, int y, int z) { // prioritize lower y coordinates return this.y * 100 + super.heuristic(x, y, z); } + + @Override + public String toString() { + return String.format( + "GoalPlace{x=%s,y=%s,z=%s}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) + ); + } } @Override diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 6880dd86c..866dcc19d 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -319,6 +319,21 @@ public double heuristic(int x, int y, int z) { int zDiff = z - this.z; return GoalBlock.calculate(xDiff, yDiff < -1 ? yDiff + 2 : yDiff == -1 ? 0 : yDiff, zDiff); } + + @Override + public boolean equals(Object o) { + return super.equals(o); + } + + @Override + public String toString() { + return String.format( + "GoalThreeBlocks{x=%s,y=%s,z=%s}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) + ); + } } public List droppedItemsScan() { diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index a83e53a1e..236e41cc6 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -160,7 +160,7 @@ public boolean forceRevalidate(Goal newGoal) { if (newGoal.isInGoal(current.getPath().getDest())) { return false; } - return !newGoal.toString().equals(current.getPath().getGoal().toString()); + return !newGoal.equals(current.getPath().getGoal()); } return false; } From 5bdd5b0c0d095797021481a8816600c954883335 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 16:50:02 -0500 Subject: [PATCH 059/111] =?UTF-8?q?=F0=9F=91=8C=20appease=20leijurv?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../baritone/api/pathing/goals/GoalBlock.java | 14 ++++++++----- .../api/pathing/goals/GoalComposite.java | 8 ++++++-- .../api/pathing/goals/GoalGetToBlock.java | 14 ++++++++----- .../api/pathing/goals/GoalInverted.java | 8 ++++++-- .../baritone/api/pathing/goals/GoalNear.java | 16 +++++++++------ .../api/pathing/goals/GoalRunAway.java | 14 ++++++++----- .../pathing/goals/GoalStrictDirection.java | 18 ++++++++++------- .../api/pathing/goals/GoalTwoBlocks.java | 14 ++++++++----- .../baritone/api/pathing/goals/GoalXZ.java | 11 ++++++---- .../api/pathing/goals/GoalYLevel.java | 8 ++++++-- .../java/baritone/process/BuilderProcess.java | 20 ++++++++++++------- 11 files changed, 95 insertions(+), 50 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalBlock.java b/src/api/java/baritone/api/pathing/goals/GoalBlock.java index ad2c3eadb..68d783aa3 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalBlock.java @@ -68,13 +68,17 @@ public double heuristic(int x, int y, int z) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } GoalBlock goal = (GoalBlock) o; - if (x != goal.x) return false; - if (y != goal.y) return false; - return z == goal.z; + return x == goal.x + && y != goal.y + && z == goal.z; } @Override diff --git a/src/api/java/baritone/api/pathing/goals/GoalComposite.java b/src/api/java/baritone/api/pathing/goals/GoalComposite.java index f407fe733..d64f8e33e 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalComposite.java +++ b/src/api/java/baritone/api/pathing/goals/GoalComposite.java @@ -69,8 +69,12 @@ public double heuristic() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } GoalComposite goal = (GoalComposite) o; return Arrays.equals(goals, goal.goals); diff --git a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java index 3d2c0713a..b5caafa48 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java @@ -62,13 +62,17 @@ public double heuristic(int x, int y, int z) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } GoalGetToBlock goal = (GoalGetToBlock) o; - if (x != goal.x) return false; - if (y != goal.y) return false; - return z == goal.z; + return x == goal.x + && y == goal.y + && z == goal.z; } @Override diff --git a/src/api/java/baritone/api/pathing/goals/GoalInverted.java b/src/api/java/baritone/api/pathing/goals/GoalInverted.java index acfdd68b2..e559088ef 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalInverted.java +++ b/src/api/java/baritone/api/pathing/goals/GoalInverted.java @@ -54,8 +54,12 @@ public double heuristic() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } GoalInverted goal = (GoalInverted) o; return Objects.equals(origin, goal.origin); diff --git a/src/api/java/baritone/api/pathing/goals/GoalNear.java b/src/api/java/baritone/api/pathing/goals/GoalNear.java index 44f0ab040..166138ff4 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalNear.java +++ b/src/api/java/baritone/api/pathing/goals/GoalNear.java @@ -88,14 +88,18 @@ public BlockPos getGoalPos() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } GoalNear goal = (GoalNear) o; - if (x != goal.x) return false; - if (y != goal.y) return false; - if (z != goal.z) return false; - return rangeSq == goal.rangeSq; + return x == goal.x + && y == goal.y + && z == goal.z + && rangeSq == goal.rangeSq; } @Override diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index 3d7caa734..166ad5a98 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -127,13 +127,17 @@ public double heuristic() {// TODO less hacky solution @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } GoalRunAway goal = (GoalRunAway) o; - if (distanceSq != goal.distanceSq) return false; - if (!Arrays.equals(from, goal.from)) return false; - return Objects.equals(maintainY, goal.maintainY); + return distanceSq == goal.distanceSq + && Arrays.equals(from, goal.from) + && Objects.equals(maintainY, goal.maintainY); } @Override diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java index 86208f0ca..3d9909ad1 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java +++ b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java @@ -71,15 +71,19 @@ public double heuristic() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } GoalStrictDirection goal = (GoalStrictDirection) o; - if (x != goal.x) return false; - if (y != goal.y) return false; - if (z != goal.z) return false; - if (dx != goal.dx) return false; - return dz == goal.dz; + return x == goal.x + && y != goal.y + && z == goal.z + && dx == goal.dx + && dz == goal.dz; } @Override diff --git a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java index 4df65f609..d6fff33a2 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java +++ b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java @@ -74,13 +74,17 @@ public BlockPos getGoalPos() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } GoalTwoBlocks goal = (GoalTwoBlocks) o; - if (x != goal.x) return false; - if (y != goal.y) return false; - return z == goal.z; + return x == goal.x + && y == goal.y + && z == goal.z; } @Override diff --git a/src/api/java/baritone/api/pathing/goals/GoalXZ.java b/src/api/java/baritone/api/pathing/goals/GoalXZ.java index c77743389..2c551d395 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalXZ.java +++ b/src/api/java/baritone/api/pathing/goals/GoalXZ.java @@ -66,12 +66,15 @@ public double heuristic(int x, int y, int z) {//mostly copied from GoalBlock @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } GoalXZ goal = (GoalXZ) o; - if (x != goal.x) return false; - return z == goal.z; + return x == goal.x && z == goal.z; } @Override diff --git a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java index 8fc7850b9..37745e8de 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java +++ b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java @@ -60,8 +60,12 @@ public static double calculate(int goalY, int currentY) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } GoalYLevel goal = (GoalYLevel) o; return level == goal.level; diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index f9514fb95..69368282d 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -763,12 +763,16 @@ public double heuristic(int x, int y, int z) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } JankyGoalComposite goal = (JankyGoalComposite) o; - if (!Objects.equals(primary, goal.primary)) return false; - return Objects.equals(fallback, goal.fallback); + return Objects.equals(primary, goal.primary) + && Objects.equals(fallback, goal.fallback); } @Override @@ -870,11 +874,13 @@ public double heuristic(int x, int y, int z) { @Override public boolean equals(Object o) { - if (!super.equals(o)) return false; + if (!super.equals(o)) { + return false; + } GoalAdjacent goal = (GoalAdjacent) o; - if (allowSameLevel != goal.allowSameLevel) return false; - return Objects.equals(no, goal.no); + return allowSameLevel == goal.allowSameLevel + && Objects.equals(no, goal.no); } @Override From 8a65a1cfc593be38405bf9420be17988f93959c7 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 16:52:20 -0500 Subject: [PATCH 060/111] =?UTF-8?q?=F0=9F=90=9B=20fix=20incorrect=20compar?= =?UTF-8?q?ison=20operator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/java/baritone/api/pathing/goals/GoalBlock.java | 2 +- .../java/baritone/api/pathing/goals/GoalStrictDirection.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalBlock.java b/src/api/java/baritone/api/pathing/goals/GoalBlock.java index 68d783aa3..d76fdc7af 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalBlock.java @@ -77,7 +77,7 @@ public boolean equals(Object o) { GoalBlock goal = (GoalBlock) o; return x == goal.x - && y != goal.y + && y == goal.y && z == goal.z; } diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java index 3d9909ad1..b8e4b43b2 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java +++ b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java @@ -80,7 +80,7 @@ public boolean equals(Object o) { GoalStrictDirection goal = (GoalStrictDirection) o; return x == goal.x - && y != goal.y + && y == goal.y && z == goal.z && dx == goal.dx && dz == goal.dz; From c217a34f1368bff64bbf8123e9c7eae1a89e3881 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 17:05:56 -0500 Subject: [PATCH 061/111] =?UTF-8?q?=F0=9F=90=9B=20fix=20batch=20render=20c?= =?UTF-8?q?olor=20bug=20by=20backporting=201.17+=20render=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/baritone/utils/IRenderer.java | 57 ++++++++++--------- .../java/baritone/utils/PathRenderer.java | 52 ++++++++--------- 2 files changed, 57 insertions(+), 52 deletions(-) diff --git a/src/main/java/baritone/utils/IRenderer.java b/src/main/java/baritone/utils/IRenderer.java index 3476c0307..26a7cf1ad 100644 --- a/src/main/java/baritone/utils/IRenderer.java +++ b/src/main/java/baritone/utils/IRenderer.java @@ -38,9 +38,14 @@ public interface IRenderer { RenderManager renderManager = Helper.mc.getRenderManager(); Settings settings = BaritoneAPI.getSettings(); + float[] color = new float[] {1.0F, 1.0F, 1.0F, 255.0F}; + static void glColor(Color color, float alpha) { float[] colorComponents = color.getColorComponents(null); - GlStateManager.color(colorComponents[0], colorComponents[1], colorComponents[2], alpha); + IRenderer.color[0] = colorComponents[0]; + IRenderer.color[1] = colorComponents[1]; + IRenderer.color[2] = colorComponents[2]; + IRenderer.color[3] = alpha; } static void startLines(Color color, float alpha, float lineWidth, boolean ignoreDepth) { @@ -54,7 +59,7 @@ static void startLines(Color color, float alpha, float lineWidth, boolean ignore if (ignoreDepth) { GlStateManager.disableDepth(); } - buffer.begin(GL_LINES, DefaultVertexFormats.POSITION); + buffer.begin(GL_LINES, DefaultVertexFormats.POSITION_COLOR); } static void startLines(Color color, float lineWidth, boolean ignoreDepth) { @@ -76,32 +81,32 @@ static void emitAABB(AxisAlignedBB aabb) { AxisAlignedBB toDraw = aabb.offset(-renderManager.viewerPosX, -renderManager.viewerPosY, -renderManager.viewerPosZ); // bottom - buffer.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); + buffer.pos(toDraw.minX, toDraw.minY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.minX, toDraw.minY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); // top - buffer.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); + buffer.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); // corners - buffer.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); - buffer.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); - buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); + buffer.pos(toDraw.minX, toDraw.minY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); } static void emitAABB(AxisAlignedBB aabb, double expand) { diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 2aef0ab54..deec261d4 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -165,18 +165,18 @@ public static void emitLine(double x1, double y1, double z1, double x2, double y double vpZ = renderManager.viewerPosZ; boolean renderPathAsFrickinThingy = !settings.renderPathAsLine.value; - buffer.pos(x1 + 0.5D - vpX, y1 + 0.5D - vpY, z1 + 0.5D - vpZ).endVertex(); - buffer.pos(x2 + 0.5D - vpX, y2 + 0.5D - vpY, z2 + 0.5D - vpZ).endVertex(); + buffer.pos(x1 + 0.5D - vpX, y1 + 0.5D - vpY, z1 + 0.5D - vpZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(x2 + 0.5D - vpX, y2 + 0.5D - vpY, z2 + 0.5D - vpZ).color(color[0], color[1], color[2], color[3]).endVertex(); if (renderPathAsFrickinThingy) { - buffer.pos(x2 + 0.5D - vpX, y2 + 0.5D - vpY, z2 + 0.5D - vpZ).endVertex(); - buffer.pos(x2 + 0.5D - vpX, y2 + 0.53D - vpY, z2 + 0.5D - vpZ).endVertex(); + buffer.pos(x2 + 0.5D - vpX, y2 + 0.5D - vpY, z2 + 0.5D - vpZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(x2 + 0.5D - vpX, y2 + 0.53D - vpY, z2 + 0.5D - vpZ).color(color[0], color[1], color[2], color[3]).endVertex(); - buffer.pos(x2 + 0.5D - vpX, y2 + 0.53D - vpY, z2 + 0.5D - vpZ).endVertex(); - buffer.pos(x1 + 0.5D - vpX, y1 + 0.53D - vpY, z1 + 0.5D - vpZ).endVertex(); + buffer.pos(x2 + 0.5D - vpX, y2 + 0.53D - vpY, z2 + 0.5D - vpZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(x1 + 0.5D - vpX, y1 + 0.53D - vpY, z1 + 0.5D - vpZ).color(color[0], color[1], color[2], color[3]).endVertex(); - buffer.pos(x1 + 0.5D - vpX, y1 + 0.53D - vpY, z1 + 0.5D - vpZ).endVertex(); - buffer.pos(x1 + 0.5D - vpX, y1 + 0.5D - vpY, z1 + 0.5D - vpZ).endVertex(); + buffer.pos(x1 + 0.5D - vpX, y1 + 0.53D - vpY, z1 + 0.5D - vpZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(x1 + 0.5D - vpX, y1 + 0.5D - vpY, z1 + 0.5D - vpZ).color(color[0], color[1], color[2], color[3]).endVertex(); } } @@ -310,22 +310,22 @@ public static void drawGoal(Entity player, Goal goal, float partialTicks, Color } } - private static void drawDankLitGoalBox(Color color, double minX, double maxX, double minZ, double maxZ, double minY, double maxY, double y1, double y2, boolean setupRender) { + private static void drawDankLitGoalBox(Color colorIn, double minX, double maxX, double minZ, double maxZ, double minY, double maxY, double y1, double y2, boolean setupRender) { if (setupRender) { - IRenderer.startLines(color, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value); + IRenderer.startLines(colorIn, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value); } renderHorizontalQuad(minX, maxX, minZ, maxZ, y1); renderHorizontalQuad(minX, maxX, minZ, maxZ, y2); - buffer.pos(minX, minY, minZ).endVertex(); - buffer.pos(minX, maxY, minZ).endVertex(); - buffer.pos(maxX, minY, minZ).endVertex(); - buffer.pos(maxX, maxY, minZ).endVertex(); - buffer.pos(maxX, minY, maxZ).endVertex(); - buffer.pos(maxX, maxY, maxZ).endVertex(); - buffer.pos(minX, minY, maxZ).endVertex(); - buffer.pos(minX, maxY, maxZ).endVertex(); + buffer.pos(minX, minY, minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(minX, maxY, minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(maxX, minY, minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(maxX, maxY, minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(maxX, minY, maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(maxX, maxY, maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(minX, minY, maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(minX, maxY, maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); if (setupRender) { IRenderer.endLines(settings.renderGoalIgnoreDepth.value); @@ -334,17 +334,17 @@ private static void drawDankLitGoalBox(Color color, double minX, double maxX, do private static void renderHorizontalQuad(double minX, double maxX, double minZ, double maxZ, double y) { if (y != 0) { - buffer.pos(minX, y, minZ).endVertex(); - buffer.pos(maxX, y, minZ).endVertex(); + buffer.pos(minX, y, minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(maxX, y, minZ).color(color[0], color[1], color[2], color[3]).endVertex(); - buffer.pos(maxX, y, minZ).endVertex(); - buffer.pos(maxX, y, maxZ).endVertex(); + buffer.pos(maxX, y, minZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(maxX, y, maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); - buffer.pos(maxX, y, maxZ).endVertex(); - buffer.pos(minX, y, maxZ).endVertex(); + buffer.pos(maxX, y, maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(minX, y, maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); - buffer.pos(minX, y, maxZ).endVertex(); - buffer.pos(minX, y, minZ).endVertex(); + buffer.pos(minX, y, maxZ).color(color[0], color[1], color[2], color[3]).endVertex(); + buffer.pos(minX, y, minZ).color(color[0], color[1], color[2], color[3]).endVertex(); } } } From 13fc58933d6cf1db497d5303d290f65588b6c652 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 19:03:03 -0500 Subject: [PATCH 062/111] Don't bother returning `serverRotations` if no free look --- src/main/java/baritone/behavior/LookBehavior.java | 12 +++++++++--- .../baritone/utils/player/PrimaryPlayerContext.java | 7 ++----- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 1e109482c..702c3738d 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -28,6 +28,8 @@ import baritone.api.utils.Rotation; import net.minecraft.network.play.client.CPacketPlayer; +import java.util.Optional; + public final class LookBehavior extends Behavior implements ILookBehavior { /** @@ -70,9 +72,9 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { this.prevRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); } - ctx.player().rotationYaw = this.target.rotation.getYaw(); float oldPitch = ctx.playerRotations().getPitch(); float desiredPitch = this.target.rotation.getPitch(); + ctx.player().rotationYaw = this.target.rotation.getYaw(); ctx.player().rotationPitch = desiredPitch; ctx.player().rotationYaw += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; ctx.player().rotationPitch += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; @@ -126,8 +128,12 @@ public void pig() { } } - public Rotation getEffectiveRotation() { - return this.serverRotation; + public Optional getEffectiveRotation() { + if (Baritone.settings().freeLook.value || Baritone.settings().blockFreeLook.value) { + return Optional.of(this.serverRotation); + } + // If neither of the freeLook settings are on, just defer to the player's actual rotations + return Optional.empty(); } @Override diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java index e4484f0be..20d82f2bc 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java @@ -58,11 +58,8 @@ public IWorldData worldData() { @Override public Rotation playerRotations() { - final Rotation lbTarget = ((LookBehavior) BaritoneAPI.getProvider().getPrimaryBaritone().getLookBehavior()).getEffectiveRotation(); - if (lbTarget == null || !Baritone.settings().blockFreeLook.value) { - return IPlayerContext.super.playerRotations(); - } - return lbTarget; + return ((LookBehavior) BaritoneAPI.getProvider().getPrimaryBaritone().getLookBehavior()).getEffectiveRotation() + .orElseGet(IPlayerContext.super::playerRotations); } @Override From 4885d49d20debf7bc4f8328c11e08549e57c5abe Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 20:00:03 -0500 Subject: [PATCH 063/111] Reorganize code --- .../java/baritone/behavior/LookBehavior.java | 32 ++++++++++++------- .../utils/player/PrimaryPlayerContext.java | 1 - 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 702c3738d..db0c255f7 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -72,16 +72,23 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { this.prevRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); } - float oldPitch = ctx.playerRotations().getPitch(); + final float oldPitch = ctx.playerRotations().getPitch(); + + float desiredYaw = this.target.rotation.getYaw(); float desiredPitch = this.target.rotation.getPitch(); - ctx.player().rotationYaw = this.target.rotation.getYaw(); - ctx.player().rotationPitch = desiredPitch; - ctx.player().rotationYaw += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; - ctx.player().rotationPitch += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; + + // In other words, the target doesn't care about the pitch, so it used playerRotations().getPitch() + // and it's safe to adjust it to a normal level if (desiredPitch == oldPitch) { - nudgeToLevel(); + desiredPitch = nudgeToLevel(desiredPitch); } + desiredYaw += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; + desiredPitch += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; + + ctx.player().rotationYaw = desiredYaw; + ctx.player().rotationPitch = desiredPitch; + if (this.target.mode == Target.Mode.CLIENT) { // The target can be invalidated now since it won't be needed for RotationMoveEvent this.target = null; @@ -130,7 +137,7 @@ public void pig() { public Optional getEffectiveRotation() { if (Baritone.settings().freeLook.value || Baritone.settings().blockFreeLook.value) { - return Optional.of(this.serverRotation); + return Optional.ofNullable(this.serverRotation); } // If neither of the freeLook settings are on, just defer to the player's actual rotations return Optional.empty(); @@ -146,12 +153,13 @@ public void onPlayerRotationMove(RotationMoveEvent event) { /** * Nudges the player's pitch to a regular level. (Between {@code -20} and {@code 10}, increments are by {@code 1}) */ - private void nudgeToLevel() { - if (ctx.player().rotationPitch < -20) { - ctx.player().rotationPitch++; - } else if (ctx.player().rotationPitch > 10) { - ctx.player().rotationPitch--; + private float nudgeToLevel(float pitch) { + if (pitch < -20) { + return pitch + 1; + } else if (pitch > 10) { + return pitch - 1; } + return pitch; } private static class Target { diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java index 20d82f2bc..02db73a5c 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java @@ -17,7 +17,6 @@ package baritone.utils.player; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.cache.IWorldData; import baritone.api.utils.*; From c8b8deb3d62d5a786054fd1939293cb71673258c Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 21:04:30 -0500 Subject: [PATCH 064/111] Ensure angle delta is producible with mouse movement --- .../java/baritone/behavior/LookBehavior.java | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index db0c255f7..99e496e6f 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -24,6 +24,7 @@ import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.RotationMoveEvent; import baritone.api.event.events.WorldEvent; +import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.api.utils.Rotation; import net.minecraft.network.play.client.CPacketPlayer; @@ -72,6 +73,7 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { this.prevRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); } + final float oldYaw = ctx.playerRotations().getYaw(); final float oldPitch = ctx.playerRotations().getPitch(); float desiredYaw = this.target.rotation.getYaw(); @@ -86,8 +88,8 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { desiredYaw += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; desiredPitch += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; - ctx.player().rotationYaw = desiredYaw; - ctx.player().rotationPitch = desiredPitch; + ctx.player().rotationYaw = calculateMouseMove(oldYaw, desiredYaw); + ctx.player().rotationPitch = calculateMouseMove(oldPitch, desiredPitch); if (this.target.mode == Target.Mode.CLIENT) { // The target can be invalidated now since it won't be needed for RotationMoveEvent @@ -153,7 +155,7 @@ public void onPlayerRotationMove(RotationMoveEvent event) { /** * Nudges the player's pitch to a regular level. (Between {@code -20} and {@code 10}, increments are by {@code 1}) */ - private float nudgeToLevel(float pitch) { + private static float nudgeToLevel(float pitch) { if (pitch < -20) { return pitch + 1; } else if (pitch > 10) { @@ -162,6 +164,22 @@ private float nudgeToLevel(float pitch) { return pitch; } + private static float calculateMouseMove(float current, float target) { + final float delta = target - current; + final int deltaPx = angleToMouse(delta); + return current + mouseToAngle(deltaPx); + } + + private static int angleToMouse(float angleDelta) { + final float minAngleChange = mouseToAngle(1); + return Math.round(angleDelta / minAngleChange); + } + + private static float mouseToAngle(int mouseDelta) { + final float f = Helper.mc.gameSettings.mouseSensitivity * 0.6f + 0.2f; + return mouseDelta * f * f * f * 8.0f * 0.15f; + } + private static class Target { public final Rotation rotation; From 2022d33d03296a41689fa4cd186b15ecc2e8a324 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 21:12:49 -0500 Subject: [PATCH 065/111] Fix incorrect references to player and world --- .../java/baritone/command/defaults/SurfaceCommand.java | 8 ++++---- .../java/baritone/process/InventoryPauserProcess.java | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/command/defaults/SurfaceCommand.java b/src/main/java/baritone/command/defaults/SurfaceCommand.java index 842b8050c..5d914aded 100644 --- a/src/main/java/baritone/command/defaults/SurfaceCommand.java +++ b/src/main/java/baritone/command/defaults/SurfaceCommand.java @@ -38,13 +38,13 @@ protected SurfaceCommand(IBaritone baritone) { @Override public void execute(String label, IArgConsumer args) throws CommandException { - final BetterBlockPos playerPos = baritone.getPlayerContext().playerFeet(); - final int surfaceLevel = baritone.getPlayerContext().world().getSeaLevel(); - final int worldHeight = baritone.getPlayerContext().world().getActualHeight(); + final BetterBlockPos playerPos = ctx.playerFeet(); + final int surfaceLevel = ctx.world().getSeaLevel(); + final int worldHeight = ctx.world().getActualHeight(); // Ensure this command will not run if you are above the surface level and the block above you is air // As this would imply that your are already on the open surface - if (playerPos.getY() > surfaceLevel && mc.world.getBlockState(playerPos.up()).getBlock() instanceof BlockAir) { + if (playerPos.getY() > surfaceLevel && ctx.world().getBlockState(playerPos.up()).getBlock() instanceof BlockAir) { logDirect("Already at surface"); return; } diff --git a/src/main/java/baritone/process/InventoryPauserProcess.java b/src/main/java/baritone/process/InventoryPauserProcess.java index ab210532b..9752912b9 100644 --- a/src/main/java/baritone/process/InventoryPauserProcess.java +++ b/src/main/java/baritone/process/InventoryPauserProcess.java @@ -34,14 +34,14 @@ public InventoryPauserProcess(Baritone baritone) { @Override public boolean isActive() { - if (mc.player == null || mc.world == null) { + if (ctx.player() == null || ctx.world() == null) { return false; } return true; } private double motion() { - return Math.sqrt(mc.player.motionX * mc.player.motionX + mc.player.motionZ * mc.player.motionZ); + return Math.sqrt(ctx.player().motionX * ctx.player().motionX + ctx.player().motionZ * ctx.player().motionZ); } private boolean stationaryNow() { From 76fe0d14d3199cf219d3a67ddada62f0153aa702 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 12 Jun 2023 21:13:10 -0500 Subject: [PATCH 066/111] Simplify some player context references --- src/main/java/baritone/command/defaults/GoalCommand.java | 2 +- src/main/java/baritone/command/defaults/GotoCommand.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/command/defaults/GoalCommand.java b/src/main/java/baritone/command/defaults/GoalCommand.java index 40822e057..a174ecad9 100644 --- a/src/main/java/baritone/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/command/defaults/GoalCommand.java @@ -51,7 +51,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { } } else { args.requireMax(3); - BetterBlockPos origin = baritone.getPlayerContext().playerFeet(); + BetterBlockPos origin = ctx.playerFeet(); Goal goal = args.getDatatypePost(RelativeGoal.INSTANCE, origin); goalProcess.setGoal(goal); logDirect(String.format("Goal: %s", goal.toString())); diff --git a/src/main/java/baritone/command/defaults/GotoCommand.java b/src/main/java/baritone/command/defaults/GotoCommand.java index 896e3f5f8..333d7fa57 100644 --- a/src/main/java/baritone/command/defaults/GotoCommand.java +++ b/src/main/java/baritone/command/defaults/GotoCommand.java @@ -46,7 +46,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { // is no need to handle the case of empty arguments. if (args.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) != null) { args.requireMax(3); - BetterBlockPos origin = baritone.getPlayerContext().playerFeet(); + BetterBlockPos origin = ctx.playerFeet(); Goal goal = args.getDatatypePost(RelativeGoal.INSTANCE, origin); logDirect(String.format("Going to: %s", goal.toString())); baritone.getCustomGoalProcess().setGoalAndPath(goal); From 714ebb2c2d1df2c37c01a1d25a42aa8267121463 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Jun 2023 18:24:31 -0500 Subject: [PATCH 067/111] Deprecate `Helper.mc` and begin to replace usages --- src/api/java/baritone/api/utils/Helper.java | 7 +++--- .../baritone/api/utils/gui/BaritoneToast.java | 3 ++- src/main/java/baritone/Baritone.java | 18 ++++++++----- src/main/java/baritone/BaritoneProvider.java | 4 +-- .../java/baritone/behavior/LookBehavior.java | 8 +++--- .../java/baritone/cache/WorldProvider.java | 5 ++++ .../baritone/utils/InputOverrideHandler.java | 3 +-- ...ontext.java => BaritonePlayerContext.java} | 25 +++++++++++++------ ...ler.java => BaritonePlayerController.java} | 11 +++++--- 9 files changed, 55 insertions(+), 29 deletions(-) rename src/main/java/baritone/utils/player/{PrimaryPlayerContext.java => BaritonePlayerContext.java} (69%) rename src/main/java/baritone/utils/player/{PrimaryPlayerController.java => BaritonePlayerController.java} (91%) diff --git a/src/api/java/baritone/api/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java index 9bed37383..e49744b4f 100755 --- a/src/api/java/baritone/api/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -44,6 +44,7 @@ public interface Helper { /** * Instance of the game */ + @Deprecated Minecraft mc = Minecraft.getMinecraft(); static ITextComponent getPrefix() { @@ -70,7 +71,7 @@ static ITextComponent getPrefix() { * @param message The message to display in the popup */ default void logToast(ITextComponent title, ITextComponent message) { - mc.addScheduledTask(() -> BaritoneAPI.getSettings().toaster.value.accept(title, message)); + Minecraft.getMinecraft().addScheduledTask(() -> BaritoneAPI.getSettings().toaster.value.accept(title, message)); } /** @@ -131,7 +132,7 @@ default void logNotificationDirect(String message) { * @param error Whether to log as an error */ default void logNotificationDirect(String message, boolean error) { - mc.addScheduledTask(() -> BaritoneAPI.getSettings().notifier.value.accept(message, error)); + Minecraft.getMinecraft().addScheduledTask(() -> BaritoneAPI.getSettings().notifier.value.accept(message, error)); } /** @@ -168,7 +169,7 @@ default void logDirect(boolean logAsToast, ITextComponent... components) { if (logAsToast) { logToast(getPrefix(), component); } else { - mc.addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component)); + Minecraft.getMinecraft().addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component)); } } diff --git a/src/api/java/baritone/api/utils/gui/BaritoneToast.java b/src/api/java/baritone/api/utils/gui/BaritoneToast.java index eb6361478..9e9a6403c 100644 --- a/src/api/java/baritone/api/utils/gui/BaritoneToast.java +++ b/src/api/java/baritone/api/utils/gui/BaritoneToast.java @@ -17,6 +17,7 @@ package baritone.api.utils.gui; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.toasts.GuiToast; import net.minecraft.client.gui.toasts.IToast; import net.minecraft.client.renderer.GlStateManager; @@ -73,6 +74,6 @@ public static void addOrUpdate(GuiToast toast, ITextComponent title, ITextCompon } public static void addOrUpdate(ITextComponent title, ITextComponent subtitle) { - addOrUpdate(net.minecraft.client.Minecraft.getMinecraft().getToastGui(), title, subtitle, baritone.api.BaritoneAPI.getSettings().toastTimer.value); + addOrUpdate(Minecraft.getMinecraft().getToastGui(), title, subtitle, baritone.api.BaritoneAPI.getSettings().toastTimer.value); } } diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 61db54211..173cef876 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -21,7 +21,6 @@ import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.event.listener.IEventBus; -import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.behavior.*; import baritone.cache.WorldProvider; @@ -33,7 +32,7 @@ import baritone.utils.GuiClick; import baritone.utils.InputOverrideHandler; import baritone.utils.PathingControlManager; -import baritone.utils.player.PrimaryPlayerContext; +import baritone.utils.player.BaritonePlayerContext; import net.minecraft.client.Minecraft; import java.io.File; @@ -64,6 +63,8 @@ public class Baritone implements IBaritone { } } + private final Minecraft mc; + private GameEventHandler gameEventHandler; private PathingBehavior pathingBehavior; @@ -91,11 +92,12 @@ public class Baritone implements IBaritone { public BlockStateInterface bsi; - Baritone() { + Baritone(Minecraft mc) { + this.mc = mc; this.gameEventHandler = new GameEventHandler(this); // Define this before behaviors try and get it, or else it will be null and the builds will fail! - this.playerContext = PrimaryPlayerContext.INSTANCE; + this.playerContext = new BaritonePlayerContext(this); { // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist @@ -119,7 +121,7 @@ public class Baritone implements IBaritone { this.pathingControlManager.registerProcess(inventoryPauserProcess = new InventoryPauserProcess(this)); } - this.worldProvider = new WorldProvider(); + this.worldProvider = new WorldProvider(this); this.selectionManager = new SelectionManager(this); this.commandManager = new CommandManager(this); } @@ -219,11 +221,15 @@ public void openClick() { new Thread(() -> { try { Thread.sleep(100); - Helper.mc.addScheduledTask(() -> Helper.mc.displayGuiScreen(new GuiClick())); + mc.addScheduledTask(() -> mc.displayGuiScreen(new GuiClick())); } catch (Exception ignored) {} }).start(); } + public Minecraft getMinecraft() { + return this.mc; + } + public static Settings settings() { return BaritoneAPI.getSettings(); } diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index c49c02e10..b7c2403d2 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -23,10 +23,10 @@ import baritone.api.command.ICommandSystem; import baritone.api.schematic.ISchematicSystem; import baritone.cache.FasterWorldScanner; -import baritone.cache.WorldScanner; import baritone.command.CommandSystem; import baritone.command.ExampleBaritoneControl; import baritone.utils.schematic.SchematicSystem; +import net.minecraft.client.Minecraft; import java.util.Collections; import java.util.List; @@ -41,7 +41,7 @@ public final class BaritoneProvider implements IBaritoneProvider { private final List all; { - this.primary = new Baritone(); + this.primary = new Baritone(Minecraft.getMinecraft()); this.all = Collections.singletonList(this.primary); // Setup chat control, just for the primary instance diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 99e496e6f..2d237dfb8 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -164,19 +164,19 @@ private static float nudgeToLevel(float pitch) { return pitch; } - private static float calculateMouseMove(float current, float target) { + private float calculateMouseMove(float current, float target) { final float delta = target - current; final int deltaPx = angleToMouse(delta); return current + mouseToAngle(deltaPx); } - private static int angleToMouse(float angleDelta) { + private int angleToMouse(float angleDelta) { final float minAngleChange = mouseToAngle(1); return Math.round(angleDelta / minAngleChange); } - private static float mouseToAngle(int mouseDelta) { - final float f = Helper.mc.gameSettings.mouseSensitivity * 0.6f + 0.2f; + private float mouseToAngle(int mouseDelta) { + final float f = baritone.getMinecraft().gameSettings.mouseSensitivity * 0.6f + 0.2f; return mouseDelta * f * f * f * 8.0f * 0.15f; } diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index 97b15a137..85d8a04bf 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -44,9 +44,14 @@ public class WorldProvider implements IWorldProvider, Helper { private static final Map worldCache = new HashMap<>(); // this is how the bots have the same cached world + private Baritone baritone; private WorldData currentWorld; private World mcWorld; // this let's us detect a broken load/unload hook + public WorldProvider(Baritone baritone) { + this.baritone = baritone; + } + @Override public final WorldData getCurrentWorld() { detectAndHandleBrokenLoading(); diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index d1c4689a2..b7f320e96 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -23,7 +23,6 @@ import baritone.api.utils.IInputOverrideHandler; import baritone.api.utils.input.Input; import baritone.behavior.Behavior; -import net.minecraft.client.Minecraft; import net.minecraft.util.MovementInputFromOptions; import java.util.HashMap; @@ -100,7 +99,7 @@ public final void onTick(TickEvent event) { } } else { if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { // allow other movement inputs that aren't this one, e.g. for a freecam - ctx.player().movementInput = new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings); + ctx.player().movementInput = new MovementInputFromOptions(baritone.getMinecraft().gameSettings); } } // only set it if it was previously incorrect diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java b/src/main/java/baritone/utils/player/BaritonePlayerContext.java similarity index 69% rename from src/main/java/baritone/utils/player/PrimaryPlayerContext.java rename to src/main/java/baritone/utils/player/BaritonePlayerContext.java index 02db73a5c..6af714942 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java +++ b/src/main/java/baritone/utils/player/BaritonePlayerContext.java @@ -17,10 +17,11 @@ package baritone.utils.player; -import baritone.api.BaritoneAPI; +import baritone.Baritone; import baritone.api.cache.IWorldData; import baritone.api.utils.*; import baritone.behavior.LookBehavior; +import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; @@ -31,33 +32,41 @@ * @author Brady * @since 11/12/2018 */ -public enum PrimaryPlayerContext implements IPlayerContext, Helper { +public final class BaritonePlayerContext implements IPlayerContext { - INSTANCE; + private final Baritone baritone; + private final Minecraft mc; + private final IPlayerController playerController; + + public BaritonePlayerContext(Baritone baritone) { + this.baritone = baritone; + this.mc = baritone.getMinecraft(); + this.playerController = new BaritonePlayerController(baritone); + } @Override public EntityPlayerSP player() { - return mc.player; + return this.mc.player; } @Override public IPlayerController playerController() { - return PrimaryPlayerController.INSTANCE; + return this.playerController; } @Override public World world() { - return mc.world; + return this.mc.world; } @Override public IWorldData worldData() { - return BaritoneAPI.getProvider().getPrimaryBaritone().getWorldProvider().getCurrentWorld(); + return this.baritone.getWorldProvider().getCurrentWorld(); } @Override public Rotation playerRotations() { - return ((LookBehavior) BaritoneAPI.getProvider().getPrimaryBaritone().getLookBehavior()).getEffectiveRotation() + return ((LookBehavior) this.baritone.getLookBehavior()).getEffectiveRotation() .orElseGet(IPlayerContext.super::playerRotations); } diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerController.java b/src/main/java/baritone/utils/player/BaritonePlayerController.java similarity index 91% rename from src/main/java/baritone/utils/player/PrimaryPlayerController.java rename to src/main/java/baritone/utils/player/BaritonePlayerController.java index b013f9161..95a55e026 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerController.java +++ b/src/main/java/baritone/utils/player/BaritonePlayerController.java @@ -17,9 +17,10 @@ package baritone.utils.player; -import baritone.api.utils.Helper; +import baritone.Baritone; import baritone.api.utils.IPlayerController; import baritone.utils.accessor.IPlayerControllerMP; +import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; @@ -39,9 +40,13 @@ * @author Brady * @since 12/14/2018 */ -public enum PrimaryPlayerController implements IPlayerController, Helper { +public final class BaritonePlayerController implements IPlayerController { - INSTANCE; + private final Minecraft mc; + + public BaritonePlayerController(Baritone baritone) { + this.mc = baritone.getMinecraft(); + } @Override public void syncHeldItem() { From ab3d9e9c47d04584150c8585367458dbc8558c97 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Jun 2023 21:13:34 -0500 Subject: [PATCH 068/111] I LOVE `final` --- src/main/java/baritone/Baritone.java | 54 +++++++++---------- src/main/java/baritone/behavior/Behavior.java | 1 - .../baritone/behavior/PathingBehavior.java | 8 +-- .../java/baritone/cache/WorldProvider.java | 2 +- .../java/baritone/utils/BlockBreakHelper.java | 3 +- .../java/baritone/utils/BlockPlaceHelper.java | 3 +- .../utils/player/BaritonePlayerContext.java | 4 +- 7 files changed, 36 insertions(+), 39 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 173cef876..4a873c226 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -49,8 +49,8 @@ */ public class Baritone implements IBaritone { - private static ThreadPoolExecutor threadPool; - private static File dir; + private static final ThreadPoolExecutor threadPool; + private static final File dir; static { threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); @@ -65,30 +65,30 @@ public class Baritone implements IBaritone { private final Minecraft mc; - private GameEventHandler gameEventHandler; + private final GameEventHandler gameEventHandler; - private PathingBehavior pathingBehavior; - private LookBehavior lookBehavior; - private InventoryBehavior inventoryBehavior; - private WaypointBehavior waypointBehavior; - private InputOverrideHandler inputOverrideHandler; + private final PathingBehavior pathingBehavior; + private final LookBehavior lookBehavior; + private final InventoryBehavior inventoryBehavior; + private final WaypointBehavior waypointBehavior; + private final InputOverrideHandler inputOverrideHandler; - private FollowProcess followProcess; - private MineProcess mineProcess; - private GetToBlockProcess getToBlockProcess; - private CustomGoalProcess customGoalProcess; - private BuilderProcess builderProcess; - private ExploreProcess exploreProcess; - private BackfillProcess backfillProcess; - private FarmProcess farmProcess; - private InventoryPauserProcess inventoryPauserProcess; + private final FollowProcess followProcess; + private final MineProcess mineProcess; + private final GetToBlockProcess getToBlockProcess; + private final CustomGoalProcess customGoalProcess; + private final BuilderProcess builderProcess; + private final ExploreProcess exploreProcess; + private final BackfillProcess backfillProcess; + private final FarmProcess farmProcess; + private final InventoryPauserProcess inventoryPauserProcess; - private PathingControlManager pathingControlManager; - private SelectionManager selectionManager; - private CommandManager commandManager; + private final PathingControlManager pathingControlManager; + private final SelectionManager selectionManager; + private final CommandManager commandManager; - private IPlayerContext playerContext; - private WorldProvider worldProvider; + private final IPlayerContext playerContext; + private final WorldProvider worldProvider; public BlockStateInterface bsi; @@ -101,11 +101,11 @@ public class Baritone implements IBaritone { { // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist - pathingBehavior = new PathingBehavior(this); - lookBehavior = new LookBehavior(this); - inventoryBehavior = new InventoryBehavior(this); - inputOverrideHandler = new InputOverrideHandler(this); - waypointBehavior = new WaypointBehavior(this); + this.registerBehavior(pathingBehavior = new PathingBehavior(this)); + this.registerBehavior(lookBehavior = new LookBehavior(this)); + this.registerBehavior(inventoryBehavior = new InventoryBehavior(this)); + this.registerBehavior(inputOverrideHandler = new InputOverrideHandler(this)); + this.registerBehavior(waypointBehavior = new WaypointBehavior(this)); } this.pathingControlManager = new PathingControlManager(this); diff --git a/src/main/java/baritone/behavior/Behavior.java b/src/main/java/baritone/behavior/Behavior.java index 36273c026..848beb298 100644 --- a/src/main/java/baritone/behavior/Behavior.java +++ b/src/main/java/baritone/behavior/Behavior.java @@ -35,6 +35,5 @@ public class Behavior implements IBehavior { protected Behavior(Baritone baritone) { this.baritone = baritone; this.ctx = baritone.getPlayerContext(); - baritone.registerBehavior(this); } } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 33ef14ef2..23f2b1431 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -36,6 +36,7 @@ import baritone.utils.PathRenderer; import baritone.utils.PathingCommandContext; import baritone.utils.pathing.Favoring; +import net.minecraft.client.settings.GameSettings; import net.minecraft.util.math.BlockPos; import java.util.ArrayList; @@ -237,13 +238,14 @@ private void tickPath() { @Override public void onPlayerUpdate(PlayerUpdateEvent event) { if (current != null) { + final GameSettings settings = baritone.getMinecraft().gameSettings; switch (event.getState()) { case PRE: - lastAutoJump = mc.gameSettings.autoJump; - mc.gameSettings.autoJump = false; + lastAutoJump = settings.autoJump; + settings.autoJump = false; break; case POST: - mc.gameSettings.autoJump = lastAutoJump; + settings.autoJump = lastAutoJump; break; default: break; diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index 85d8a04bf..d0458ea60 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -44,7 +44,7 @@ public class WorldProvider implements IWorldProvider, Helper { private static final Map worldCache = new HashMap<>(); // this is how the bots have the same cached world - private Baritone baritone; + private final Baritone baritone; private WorldData currentWorld; private World mcWorld; // this let's us detect a broken load/unload hook diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index 26e82cd78..c4ed11f0c 100644 --- a/src/main/java/baritone/utils/BlockBreakHelper.java +++ b/src/main/java/baritone/utils/BlockBreakHelper.java @@ -17,7 +17,6 @@ package baritone.utils; -import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import net.minecraft.util.EnumHand; import net.minecraft.util.math.RayTraceResult; @@ -26,7 +25,7 @@ * @author Brady * @since 8/25/2018 */ -public final class BlockBreakHelper implements Helper { +public final class BlockBreakHelper { private final IPlayerContext ctx; private boolean didBreakLastTick; diff --git a/src/main/java/baritone/utils/BlockPlaceHelper.java b/src/main/java/baritone/utils/BlockPlaceHelper.java index 440bfb93d..69dea61b8 100644 --- a/src/main/java/baritone/utils/BlockPlaceHelper.java +++ b/src/main/java/baritone/utils/BlockPlaceHelper.java @@ -18,13 +18,12 @@ package baritone.utils; import baritone.Baritone; -import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.math.RayTraceResult; -public class BlockPlaceHelper implements Helper { +public class BlockPlaceHelper { private final IPlayerContext ctx; private int rightClickTimer; diff --git a/src/main/java/baritone/utils/player/BaritonePlayerContext.java b/src/main/java/baritone/utils/player/BaritonePlayerContext.java index 6af714942..0bb118a1d 100644 --- a/src/main/java/baritone/utils/player/BaritonePlayerContext.java +++ b/src/main/java/baritone/utils/player/BaritonePlayerContext.java @@ -20,7 +20,6 @@ import baritone.Baritone; import baritone.api.cache.IWorldData; import baritone.api.utils.*; -import baritone.behavior.LookBehavior; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.math.RayTraceResult; @@ -66,8 +65,7 @@ public IWorldData worldData() { @Override public Rotation playerRotations() { - return ((LookBehavior) this.baritone.getLookBehavior()).getEffectiveRotation() - .orElseGet(IPlayerContext.super::playerRotations); + return this.baritone.getLookBehavior().getEffectiveRotation().orElseGet(IPlayerContext.super::playerRotations); } @Override From 382f82b0e0ec38d419fb58245d6ae143a34887f2 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Jun 2023 21:17:42 -0500 Subject: [PATCH 069/111] Move `Minecraft` to `IPlayerContext` --- src/api/java/baritone/api/utils/IPlayerContext.java | 3 +++ src/main/java/baritone/Baritone.java | 6 +----- src/main/java/baritone/behavior/LookBehavior.java | 2 +- src/main/java/baritone/behavior/PathingBehavior.java | 7 +++---- .../java/baritone/utils/InputOverrideHandler.java | 2 +- .../baritone/utils/player/BaritonePlayerContext.java | 11 ++++++++--- .../utils/player/BaritonePlayerController.java | 4 ++-- 7 files changed, 19 insertions(+), 16 deletions(-) diff --git a/src/api/java/baritone/api/utils/IPlayerContext.java b/src/api/java/baritone/api/utils/IPlayerContext.java index fcc4c81cc..525f73ddc 100644 --- a/src/api/java/baritone/api/utils/IPlayerContext.java +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -19,6 +19,7 @@ import baritone.api.cache.IWorldData; import net.minecraft.block.BlockSlab; +import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; @@ -33,6 +34,8 @@ */ public interface IPlayerContext { + Minecraft minecraft(); + EntityPlayerSP player(); IPlayerController playerController(); diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 4a873c226..488850f82 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -97,7 +97,7 @@ public class Baritone implements IBaritone { this.gameEventHandler = new GameEventHandler(this); // Define this before behaviors try and get it, or else it will be null and the builds will fail! - this.playerContext = new BaritonePlayerContext(this); + this.playerContext = new BaritonePlayerContext(this, mc); { // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist @@ -226,10 +226,6 @@ public void openClick() { }).start(); } - public Minecraft getMinecraft() { - return this.mc; - } - public static Settings settings() { return BaritoneAPI.getSettings(); } diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 2d237dfb8..67aa45e39 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -176,7 +176,7 @@ private int angleToMouse(float angleDelta) { } private float mouseToAngle(int mouseDelta) { - final float f = baritone.getMinecraft().gameSettings.mouseSensitivity * 0.6f + 0.2f; + final float f = ctx.minecraft().gameSettings.mouseSensitivity * 0.6f + 0.2f; return mouseDelta * f * f * f * 8.0f * 0.15f; } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 23f2b1431..f5433fe8d 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -238,14 +238,13 @@ private void tickPath() { @Override public void onPlayerUpdate(PlayerUpdateEvent event) { if (current != null) { - final GameSettings settings = baritone.getMinecraft().gameSettings; switch (event.getState()) { case PRE: - lastAutoJump = settings.autoJump; - settings.autoJump = false; + lastAutoJump = ctx.minecraft().gameSettings.autoJump; + ctx.minecraft().gameSettings.autoJump = false; break; case POST: - settings.autoJump = lastAutoJump; + ctx.minecraft().gameSettings.autoJump = lastAutoJump; break; default: break; diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index b7f320e96..f110b9ce1 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -99,7 +99,7 @@ public final void onTick(TickEvent event) { } } else { if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { // allow other movement inputs that aren't this one, e.g. for a freecam - ctx.player().movementInput = new MovementInputFromOptions(baritone.getMinecraft().gameSettings); + ctx.player().movementInput = new MovementInputFromOptions(ctx.minecraft().gameSettings); } } // only set it if it was previously incorrect diff --git a/src/main/java/baritone/utils/player/BaritonePlayerContext.java b/src/main/java/baritone/utils/player/BaritonePlayerContext.java index 0bb118a1d..601d2bb72 100644 --- a/src/main/java/baritone/utils/player/BaritonePlayerContext.java +++ b/src/main/java/baritone/utils/player/BaritonePlayerContext.java @@ -37,10 +37,15 @@ public final class BaritonePlayerContext implements IPlayerContext { private final Minecraft mc; private final IPlayerController playerController; - public BaritonePlayerContext(Baritone baritone) { + public BaritonePlayerContext(Baritone baritone, Minecraft mc) { this.baritone = baritone; - this.mc = baritone.getMinecraft(); - this.playerController = new BaritonePlayerController(baritone); + this.mc = mc; + this.playerController = new BaritonePlayerController(mc); + } + + @Override + public Minecraft minecraft() { + return this.mc; } @Override diff --git a/src/main/java/baritone/utils/player/BaritonePlayerController.java b/src/main/java/baritone/utils/player/BaritonePlayerController.java index 95a55e026..b0e94e8c5 100644 --- a/src/main/java/baritone/utils/player/BaritonePlayerController.java +++ b/src/main/java/baritone/utils/player/BaritonePlayerController.java @@ -44,8 +44,8 @@ public final class BaritonePlayerController implements IPlayerController { private final Minecraft mc; - public BaritonePlayerController(Baritone baritone) { - this.mc = baritone.getMinecraft(); + public BaritonePlayerController(Minecraft mc) { + this.mc = mc; } @Override From c7f4e366e21d5e79d050cd28eeed57b8f6809691 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Jun 2023 23:07:26 -0500 Subject: [PATCH 070/111] Remove `mc` references from `WorldProvider` Also refactored a bit, should be a lot easier to merge upwards to new game versions --- .../baritone/api/cache/IWorldProvider.java | 9 + src/main/java/baritone/Baritone.java | 26 +-- .../java/baritone/cache/WorldProvider.java | 172 ++++++++++-------- .../java/baritone/event/GameEventHandler.java | 2 +- .../player/BaritonePlayerController.java | 1 - 5 files changed, 122 insertions(+), 88 deletions(-) diff --git a/src/api/java/baritone/api/cache/IWorldProvider.java b/src/api/java/baritone/api/cache/IWorldProvider.java index 0e54ef469..b9ca149c7 100644 --- a/src/api/java/baritone/api/cache/IWorldProvider.java +++ b/src/api/java/baritone/api/cache/IWorldProvider.java @@ -17,6 +17,8 @@ package baritone.api.cache; +import java.util.function.Consumer; + /** * @author Brady * @since 9/24/2018 @@ -29,4 +31,11 @@ public interface IWorldProvider { * @return The current world data */ IWorldData getCurrentWorld(); + + default void ifWorldLoaded(Consumer callback) { + final IWorldData currentWorld = this.getCurrentWorld(); + if (currentWorld != null) { + callback.accept(currentWorld); + } + } } diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 488850f82..7cfa15009 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -35,9 +35,9 @@ import baritone.utils.player.BaritonePlayerContext; import net.minecraft.client.Minecraft; -import java.io.File; import java.io.IOException; import java.nio.file.Files; +import java.nio.file.Path; import java.util.concurrent.Executor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; @@ -50,20 +50,13 @@ public class Baritone implements IBaritone { private static final ThreadPoolExecutor threadPool; - private static final 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) {} - } } private final Minecraft mc; + private final Path directory; private final GameEventHandler gameEventHandler; @@ -96,6 +89,13 @@ public class Baritone implements IBaritone { this.mc = mc; this.gameEventHandler = new GameEventHandler(this); + this.directory = mc.gameDir.toPath().resolve("baritone"); + if (!Files.exists(this.directory)) { + try { + Files.createDirectories(this.directory); + } catch (IOException ignored) {} + } + // Define this before behaviors try and get it, or else it will be null and the builds will fail! this.playerContext = new BaritonePlayerContext(this, mc); @@ -226,12 +226,12 @@ public void openClick() { }).start(); } - public static Settings settings() { - return BaritoneAPI.getSettings(); + public Path getDirectory() { + return this.directory; } - public static File getDir() { - return dir; + public static Settings settings() { + return BaritoneAPI.getSettings(); } public static Executor getExecutor() { diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index d0458ea60..59f671c99 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -19,108 +19,85 @@ import baritone.Baritone; import baritone.api.cache.IWorldProvider; -import baritone.api.utils.Helper; +import baritone.api.utils.IPlayerContext; import baritone.utils.accessor.IAnvilChunkLoader; import baritone.utils.accessor.IChunkProviderServer; -import net.minecraft.server.integrated.IntegratedServer; +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.util.Tuple; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.apache.commons.lang3.SystemUtils; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; -import java.util.function.Consumer; +import java.util.Optional; /** * @author Brady * @since 8/4/2018 */ -public class WorldProvider implements IWorldProvider, Helper { +public class WorldProvider implements IWorldProvider { - private static final Map worldCache = new HashMap<>(); // this is how the bots have the same cached world + private static final Map worldCache = new HashMap<>(); private final Baritone baritone; + private final IPlayerContext ctx; private WorldData currentWorld; - private World mcWorld; // this let's us detect a broken load/unload hook + + /** + * This lets us detect a broken load/unload hook. + * @see #detectAndHandleBrokenLoading() + */ + private World mcWorld; public WorldProvider(Baritone baritone) { this.baritone = baritone; + this.ctx = baritone.getPlayerContext(); } @Override public final WorldData getCurrentWorld() { - detectAndHandleBrokenLoading(); + this.detectAndHandleBrokenLoading(); return this.currentWorld; } /** * Called when a new world is initialized to discover the * - * @param dimension The ID of the world's dimension + * @param world The new world */ - public final void initWorld(int dimension) { - File directory; - File readme; - - IntegratedServer integratedServer = mc.getIntegratedServer(); - - // If there is an integrated server running (Aka Singleplayer) then do magic to find the world save file - if (mc.isSingleplayer()) { - WorldServer localServerWorld = integratedServer.getWorld(dimension); - IChunkProviderServer provider = (IChunkProviderServer) localServerWorld.getChunkProvider(); - IAnvilChunkLoader loader = (IAnvilChunkLoader) provider.getChunkLoader(); - directory = loader.getChunkSaveLocation(); - - // Gets the "depth" of this directory relative the the game's run directory, 2 is the location of the world - if (directory.toPath().relativize(mc.gameDir.toPath()).getNameCount() != 2) { - // subdirectory of the main save directory for this world - directory = directory.getParentFile(); - } - - directory = new File(directory, "baritone"); - readme = directory; - } else { // Otherwise, the server must be remote... - String folderName; - if (mc.getCurrentServerData() != null) { - folderName = mc.getCurrentServerData().serverIP; - } else { - //replaymod causes null currentServerData and false singleplayer. - System.out.println("World seems to be a replay. Not loading Baritone cache."); - currentWorld = null; - mcWorld = mc.world; - return; - } - if (SystemUtils.IS_OS_WINDOWS) { - folderName = folderName.replace(":", "_"); - } - directory = new File(Baritone.getDir(), folderName); - readme = Baritone.getDir(); - } + public final void initWorld(World world) { + this.getSaveDirectories(world).ifPresent(dirs -> { + final Path worldDir = dirs.getFirst(); + final Path readmeDir = dirs.getSecond(); - // 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) {} + try { + // lol wtf is this baritone folder in my minecraft save? + // good thing we have a readme + Files.createDirectories(readmeDir); + Files.write( + readmeDir.resolve("readme.txt"), + "https://github.com/cabaletta/baritone\n".getBytes(StandardCharsets.US_ASCII) + ); + } catch (IOException ignored) {} - // We will actually store the world data in a subfolder: "DIM" - Path dir = new File(directory, "DIM" + dimension).toPath(); - if (!Files.exists(dir)) { + // We will actually store the world data in a subfolder: "DIM" + final Path worldDataDir = this.getWorldDataDirectory(worldDir, world); try { - Files.createDirectories(dir); + Files.createDirectories(worldDataDir); } catch (IOException ignored) {} - } - System.out.println("Baritone world data dir: " + dir); - synchronized (worldCache) { - this.currentWorld = worldCache.computeIfAbsent(dir, d -> new WorldData(d, dimension)); - } - this.mcWorld = mc.world; + System.out.println("Baritone world data dir: " + worldDataDir); + synchronized (worldCache) { + final int dimension = world.provider.getDimensionType().getId(); + this.currentWorld = worldCache.computeIfAbsent(worldDataDir, d -> new WorldData(d, dimension)); + } + this.mcWorld = ctx.world(); + }); } public final void closeWorld() { @@ -133,26 +110,75 @@ public final void closeWorld() { world.onClose(); } - public final void ifWorldLoaded(Consumer currentWorldConsumer) { - detectAndHandleBrokenLoading(); - if (this.currentWorld != null) { - currentWorldConsumer.accept(this.currentWorld); + private Path getWorldDataDirectory(Path parent, World world) { + return parent.resolve("DIM" + world.provider.getDimensionType().getId()); + } + + /** + * @param world The world + * @return An {@link Optional} containing the world's baritone dir and readme dir, or {@link Optional#empty()} if + * the world isn't valid for caching. + */ + private Optional> getSaveDirectories(World world) { + Path worldDir; + Path readmeDir; + + // If there is an integrated server running (Aka Singleplayer) then do magic to find the world save file + if (ctx.minecraft().isSingleplayer()) { + final int dimension = world.provider.getDimensionType().getId(); + final WorldServer localServerWorld = ctx.minecraft().getIntegratedServer().getWorld(dimension); + final IChunkProviderServer provider = (IChunkProviderServer) localServerWorld.getChunkProvider(); + final IAnvilChunkLoader loader = (IAnvilChunkLoader) provider.getChunkLoader(); + worldDir = loader.getChunkSaveLocation().toPath(); + + // Gets the "depth" of this directory relative to the game's run directory, 2 is the location of the world + if (worldDir.relativize(ctx.minecraft().gameDir.toPath()).getNameCount() != 2) { + // subdirectory of the main save directory for this world + worldDir = worldDir.getParent(); + } + + worldDir = worldDir.resolve("baritone"); + readmeDir = worldDir; + } else { // Otherwise, the server must be remote... + String folderName; + final ServerData serverData = ctx.minecraft().getCurrentServerData(); + if (serverData != null) { + folderName = serverData.serverIP; + } else { + //replaymod causes null currentServerData and false singleplayer. + System.out.println("World seems to be a replay. Not loading Baritone cache."); + currentWorld = null; + mcWorld = ctx.world(); + return Optional.empty(); + } + if (SystemUtils.IS_OS_WINDOWS) { + folderName = folderName.replace(":", "_"); + } + // TODO: This should probably be in "baritone/servers" + worldDir = baritone.getDirectory().resolve(folderName); + // Just write the readme to the baritone directory instead of each server save in it + readmeDir = baritone.getDirectory(); } + + return Optional.of(new Tuple<>(worldDir, readmeDir)); } - private final void detectAndHandleBrokenLoading() { - if (this.mcWorld != mc.world) { + /** + * Why does this exist instead of fixing the event? Some mods break the event. Lol. + */ + private void detectAndHandleBrokenLoading() { + if (this.mcWorld != ctx.world()) { if (this.currentWorld != null) { System.out.println("mc.world unloaded unnoticed! Unloading Baritone cache now."); closeWorld(); } - if (mc.world != null) { + if (ctx.world() != null) { System.out.println("mc.world loaded unnoticed! Loading Baritone cache now."); - initWorld(mc.world.provider.getDimensionType().getId()); + initWorld(ctx.world()); } - } else if (currentWorld == null && mc.world != null && (mc.isSingleplayer() || mc.getCurrentServerData() != null)) { + } else if (this.currentWorld == null && ctx.world() != null && (ctx.minecraft().isSingleplayer() || ctx.minecraft().getCurrentServerData() != null)) { System.out.println("Retrying to load Baritone cache"); - initWorld(mc.world.provider.getDimensionType().getId()); + initWorld(ctx.world()); } } } diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 8916f7f37..0b46eb5e1 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -114,7 +114,7 @@ public final void onWorldEvent(WorldEvent event) { if (event.getState() == EventState.POST) { cache.closeWorld(); if (event.getWorld() != null) { - cache.initWorld(event.getWorld().provider.getDimensionType().getId()); + cache.initWorld(event.getWorld()); } } diff --git a/src/main/java/baritone/utils/player/BaritonePlayerController.java b/src/main/java/baritone/utils/player/BaritonePlayerController.java index b0e94e8c5..694ffab6c 100644 --- a/src/main/java/baritone/utils/player/BaritonePlayerController.java +++ b/src/main/java/baritone/utils/player/BaritonePlayerController.java @@ -17,7 +17,6 @@ package baritone.utils.player; -import baritone.Baritone; import baritone.api.utils.IPlayerController; import baritone.utils.accessor.IPlayerControllerMP; import net.minecraft.client.Minecraft; From dd7b492b0cf81bc102dee39bc7d7d70eaf44826d Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Jun 2023 23:21:20 -0500 Subject: [PATCH 071/111] registerBehavior is called explicitly now --- src/main/java/baritone/Baritone.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 7cfa15009..637af2e3b 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -100,7 +100,6 @@ public class Baritone implements IBaritone { this.playerContext = new BaritonePlayerContext(this, mc); { - // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist this.registerBehavior(pathingBehavior = new PathingBehavior(this)); this.registerBehavior(lookBehavior = new LookBehavior(this)); this.registerBehavior(inventoryBehavior = new InventoryBehavior(this)); From 88e604426c64951d5f2a1a6818a16aab45b55651 Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 13 Jun 2023 21:30:31 -0700 Subject: [PATCH 072/111] 1.20.1 --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8ae8090d7..c135ebdf8 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,9 @@ Minecraft Minecraft Minecraft - Minecraft + Minecraft + Minecraft + Minecraft

@@ -64,6 +66,7 @@ Baritone is the pathfinding system used in [Impact](https://impactclient.net/) s | [1.19.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.4/baritone-api-forge-1.9.4.jar) | [1.19.2 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.4/baritone-api-fabric-1.9.4.jar) | | [1.19.3 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar) | [1.19.3 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar) | | [1.19.4 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-forge-1.9.3.jar) | [1.19.4 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-fabric-1.9.3.jar) | +| [1.20.1 Forge](https://github.com/cabaletta/baritone/releases/download/v1.10.1/baritone-api-forge-1.10.1.jar) | [1.20.1 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.10.1/baritone-api-fabric-1.10.1.jar) | **How to immediately get started:** Type `#goto 1000 500` in chat to go to x=1000 z=500. Type `#mine diamond_ore` to mine diamond ore. Type `#stop` to stop. For more, read [the usage page](USAGE.md) and/or watch this [tutorial playlist](https://www.youtube.com/playlist?list=PLnwnJ1qsS7CoQl9Si-RTluuzCo_4Oulpa) From 5e724c1e3af7e67466664548694fa2bfaac5145a Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 13 Jun 2023 21:31:10 -0700 Subject: [PATCH 073/111] making these clickable was a mistake --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index c135ebdf8..5fefcdf47 100644 --- a/README.md +++ b/README.md @@ -4,16 +4,16 @@

- Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft

From 6a80b0d4ffea38131462557e67f56c0d2ca42701 Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 13 Jun 2023 21:31:49 -0700 Subject: [PATCH 074/111] forgot github markdown is stupid --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 5fefcdf47..11fed3581 100644 --- a/README.md +++ b/README.md @@ -4,16 +4,16 @@

- Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft

From 54f0a3c14c63cc58f1188daaa329d660c898b6c9 Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 13 Jun 2023 21:32:21 -0700 Subject: [PATCH 075/111] marginally better --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 11fed3581..c6a90ff93 100644 --- a/README.md +++ b/README.md @@ -4,16 +4,16 @@

- Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft - Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft + Minecraft

From b03d31e99013be1283f7701c1ced02afcd012105 Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 13 Jun 2023 21:32:57 -0700 Subject: [PATCH 076/111] will github let me do this --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c6a90ff93..bbb386a74 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Baritone is the pathfinding system used in [Impact](https://impactclient.net/) s [**Baritone Discord Server**](http://discord.gg/s6fRBAUpmr) **Quick download links:** - +

| Forge | Fabric | |---------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------| | [1.12.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.2.17/baritone-api-forge-1.2.17.jar) | | @@ -67,7 +67,7 @@ Baritone is the pathfinding system used in [Impact](https://impactclient.net/) s | [1.19.3 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar) | [1.19.3 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar) | | [1.19.4 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-forge-1.9.3.jar) | [1.19.4 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-fabric-1.9.3.jar) | | [1.20.1 Forge](https://github.com/cabaletta/baritone/releases/download/v1.10.1/baritone-api-forge-1.10.1.jar) | [1.20.1 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.10.1/baritone-api-fabric-1.10.1.jar) | - +

**How to immediately get started:** Type `#goto 1000 500` in chat to go to x=1000 z=500. Type `#mine diamond_ore` to mine diamond ore. Type `#stop` to stop. For more, read [the usage page](USAGE.md) and/or watch this [tutorial playlist](https://www.youtube.com/playlist?list=PLnwnJ1qsS7CoQl9Si-RTluuzCo_4Oulpa) For other versions of Minecraft or more complicated situations or for development, see [Installation & setup](SETUP.md). Also consider just installing [Impact](https://impactclient.net/), which comes with Baritone and is easier to install than wrangling with version JSONs and zips. For 1.16.5, [click here](https://www.youtube.com/watch?v=_4eVJ9Qz2J8) and see description. Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. There's a [showcase video](https://youtu.be/CZkLXWo4Fg4) made by @Adovin#6313 on Baritone which I recommend. From 3662b3fdf18e4acba7cf9022f1143367f4737887 Mon Sep 17 00:00:00 2001 From: leijurv Date: Tue, 13 Jun 2023 21:33:12 -0700 Subject: [PATCH 077/111] nope --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bbb386a74..c6a90ff93 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Baritone is the pathfinding system used in [Impact](https://impactclient.net/) s [**Baritone Discord Server**](http://discord.gg/s6fRBAUpmr) **Quick download links:** -

+ | Forge | Fabric | |---------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------| | [1.12.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.2.17/baritone-api-forge-1.2.17.jar) | | @@ -67,7 +67,7 @@ Baritone is the pathfinding system used in [Impact](https://impactclient.net/) s | [1.19.3 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar) | [1.19.3 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar) | | [1.19.4 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-forge-1.9.3.jar) | [1.19.4 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-fabric-1.9.3.jar) | | [1.20.1 Forge](https://github.com/cabaletta/baritone/releases/download/v1.10.1/baritone-api-forge-1.10.1.jar) | [1.20.1 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.10.1/baritone-api-fabric-1.10.1.jar) | -

+ **How to immediately get started:** Type `#goto 1000 500` in chat to go to x=1000 z=500. Type `#mine diamond_ore` to mine diamond ore. Type `#stop` to stop. For more, read [the usage page](USAGE.md) and/or watch this [tutorial playlist](https://www.youtube.com/playlist?list=PLnwnJ1qsS7CoQl9Si-RTluuzCo_4Oulpa) For other versions of Minecraft or more complicated situations or for development, see [Installation & setup](SETUP.md). Also consider just installing [Impact](https://impactclient.net/), which comes with Baritone and is easier to install than wrangling with version JSONs and zips. For 1.16.5, [click here](https://www.youtube.com/watch?v=_4eVJ9Qz2J8) and see description. Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. There's a [showcase video](https://youtu.be/CZkLXWo4Fg4) made by @Adovin#6313 on Baritone which I recommend. From 75d47bb1104be9ca2a8045ec52068e926bb613a7 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 14 Jun 2023 01:53:29 -0500 Subject: [PATCH 078/111] Fix all usages of `Helper.mc` --- .../api/command/datatypes/RelativeFile.java | 9 ++- .../baritone/api/utils/IPlayerContext.java | 2 + src/main/java/baritone/Baritone.java | 27 ++++++--- src/main/java/baritone/BaritoneProvider.java | 2 +- .../command/ExampleBaritoneControl.java | 11 ++-- .../command/defaults/ComeCommand.java | 9 +-- .../defaults/ExploreFilterCommand.java | 4 +- .../command/defaults/RenderCommand.java | 4 +- .../baritone/command/defaults/SelCommand.java | 6 +- .../command/defaults/SurfaceCommand.java | 2 +- src/main/java/baritone/utils/IRenderer.java | 6 +- .../java/baritone/utils/PathRenderer.java | 59 +++++++++++-------- .../utils/player/BaritonePlayerContext.java | 9 +++ 13 files changed, 91 insertions(+), 59 deletions(-) diff --git a/src/api/java/baritone/api/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/command/datatypes/RelativeFile.java index 0bc3604ab..ec605c048 100644 --- a/src/api/java/baritone/api/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/command/datatypes/RelativeFile.java @@ -19,6 +19,8 @@ import baritone.api.command.argument.IArgConsumer; import baritone.api.command.exception.CommandException; +import baritone.api.utils.Helper; +import net.minecraft.client.Minecraft; import java.io.File; import java.io.IOException; @@ -93,8 +95,13 @@ public static Stream tabComplete(IArgConsumer consumer, File base0) thro .filter(s -> !s.contains(" ")); } + @Deprecated public static File gameDir() { - File gameDir = HELPER.mc.gameDir.getAbsoluteFile(); + return gameDir(Helper.mc); + } + + public static File gameDir(Minecraft mc) { + File gameDir = mc.gameDir.getAbsoluteFile(); if (gameDir.getName().equals(".")) { return gameDir.getParentFile(); } diff --git a/src/api/java/baritone/api/utils/IPlayerContext.java b/src/api/java/baritone/api/utils/IPlayerContext.java index 525f73ddc..14ca69fb9 100644 --- a/src/api/java/baritone/api/utils/IPlayerContext.java +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -75,6 +75,8 @@ default Vec3d playerHead() { return new Vec3d(player().posX, player().posY + player().getEyeHeight(), player().posZ); } + BetterBlockPos viewerPos(); + default Rotation playerRotations() { return new Rotation(player().rotationYaw, player().rotationPitch); } diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 637af2e3b..e85b57ce4 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -42,6 +42,7 @@ import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.function.Function; /** * @author Brady @@ -100,11 +101,11 @@ public class Baritone implements IBaritone { this.playerContext = new BaritonePlayerContext(this, mc); { - this.registerBehavior(pathingBehavior = new PathingBehavior(this)); - this.registerBehavior(lookBehavior = new LookBehavior(this)); - this.registerBehavior(inventoryBehavior = new InventoryBehavior(this)); - this.registerBehavior(inputOverrideHandler = new InputOverrideHandler(this)); - this.registerBehavior(waypointBehavior = new WaypointBehavior(this)); + pathingBehavior = this.registerBehavior(PathingBehavior::new); + lookBehavior = this.registerBehavior(LookBehavior::new); + inventoryBehavior = this.registerBehavior(InventoryBehavior::new); + inputOverrideHandler = this.registerBehavior(InputOverrideHandler::new); + waypointBehavior = this.registerBehavior(WaypointBehavior::new); } this.pathingControlManager = new PathingControlManager(this); @@ -125,15 +126,21 @@ public class Baritone implements IBaritone { this.commandManager = new CommandManager(this); } + public void registerBehavior(Behavior behavior) { + this.gameEventHandler.registerEventListener(behavior); + } + + public T registerBehavior(Function constructor) { + final T behavior = constructor.apply(this); + this.registerBehavior(behavior); + return behavior; + } + @Override public PathingControlManager getPathingControlManager() { return this.pathingControlManager; } - public void registerBehavior(Behavior behavior) { - this.gameEventHandler.registerEventListener(behavior); - } - @Override public InputOverrideHandler getInputOverrideHandler() { return this.inputOverrideHandler; @@ -173,6 +180,7 @@ public LookBehavior getLookBehavior() { return this.lookBehavior; } + @Override public ExploreProcess getExploreProcess() { return this.exploreProcess; } @@ -182,6 +190,7 @@ public MineProcess getMineProcess() { return this.mineProcess; } + @Override public FarmProcess getFarmProcess() { return this.farmProcess; } diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index b7c2403d2..a0621af93 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -45,7 +45,7 @@ public final class BaritoneProvider implements IBaritoneProvider { this.all = Collections.singletonList(this.primary); // Setup chat control, just for the primary instance - new ExampleBaritoneControl(this.primary); + this.primary.registerBehavior(ExampleBaritoneControl::new); } @Override diff --git a/src/main/java/baritone/command/ExampleBaritoneControl.java b/src/main/java/baritone/command/ExampleBaritoneControl.java index 28ced07f4..1a7b69644 100644 --- a/src/main/java/baritone/command/ExampleBaritoneControl.java +++ b/src/main/java/baritone/command/ExampleBaritoneControl.java @@ -17,8 +17,8 @@ package baritone.command; +import baritone.Baritone; import baritone.api.BaritoneAPI; -import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.command.argument.ICommandArgument; import baritone.api.command.exception.CommandNotEnoughArgumentsException; @@ -30,6 +30,7 @@ import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.utils.Helper; import baritone.api.utils.SettingsUtil; +import baritone.behavior.Behavior; import baritone.command.argument.ArgConsumer; import baritone.command.argument.CommandArguments; import baritone.command.manager.CommandManager; @@ -49,14 +50,14 @@ import static baritone.api.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX; -public class ExampleBaritoneControl implements Helper, AbstractGameEventListener { +public class ExampleBaritoneControl extends Behavior implements Helper { private static final Settings settings = BaritoneAPI.getSettings(); private final ICommandManager manager; - public ExampleBaritoneControl(IBaritone baritone) { + public ExampleBaritoneControl(Baritone baritone) { + super(baritone); this.manager = baritone.getCommandManager(); - baritone.getGameEventHandler().registerEventListener(this); } @Override @@ -100,7 +101,7 @@ public boolean runCommand(String msg) { return false; } else if (msg.trim().equalsIgnoreCase("orderpizza")) { try { - ((IGuiScreen) mc.currentScreen).openLink(new URI("https://www.dominos.com/en/pages/order/")); + ((IGuiScreen) ctx.minecraft().currentScreen).openLink(new URI("https://www.dominos.com/en/pages/order/")); } catch (NullPointerException | URISyntaxException ignored) {} return false; } diff --git a/src/main/java/baritone/command/defaults/ComeCommand.java b/src/main/java/baritone/command/defaults/ComeCommand.java index 5d3e3b829..b111ee1de 100644 --- a/src/main/java/baritone/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/command/defaults/ComeCommand.java @@ -21,10 +21,7 @@ import baritone.api.command.Command; import baritone.api.command.argument.IArgConsumer; import baritone.api.command.exception.CommandException; -import baritone.api.command.exception.CommandInvalidStateException; import baritone.api.pathing.goals.GoalBlock; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.BlockPos; import java.util.Arrays; import java.util.List; @@ -39,11 +36,7 @@ public ComeCommand(IBaritone baritone) { @Override public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); - Entity entity = mc.getRenderViewEntity(); - if (entity == null) { - throw new CommandInvalidStateException("render view entity is null"); - } - baritone.getCustomGoalProcess().setGoalAndPath(new GoalBlock(new BlockPos(entity))); + baritone.getCustomGoalProcess().setGoalAndPath(new GoalBlock(ctx.viewerPos())); logDirect("Coming"); } diff --git a/src/main/java/baritone/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/command/defaults/ExploreFilterCommand.java index c2057551f..6f306a966 100644 --- a/src/main/java/baritone/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/command/defaults/ExploreFilterCommand.java @@ -41,7 +41,7 @@ public ExploreFilterCommand(IBaritone baritone) { @Override public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(2); - File file = args.getDatatypePost(RelativeFile.INSTANCE, mc.gameDir.getAbsoluteFile().getParentFile()); + File file = args.getDatatypePost(RelativeFile.INSTANCE, ctx.minecraft().gameDir.getAbsoluteFile().getParentFile()); boolean invert = false; if (args.hasAny()) { if (args.getString().equalsIgnoreCase("invert")) { @@ -65,7 +65,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { @Override public Stream tabComplete(String label, IArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { - return RelativeFile.tabComplete(args, RelativeFile.gameDir()); + return RelativeFile.tabComplete(args, RelativeFile.gameDir(ctx.minecraft())); } return Stream.empty(); } diff --git a/src/main/java/baritone/command/defaults/RenderCommand.java b/src/main/java/baritone/command/defaults/RenderCommand.java index cc9803d16..ab4a9dbcd 100644 --- a/src/main/java/baritone/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/command/defaults/RenderCommand.java @@ -37,8 +37,8 @@ public RenderCommand(IBaritone baritone) { public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); BetterBlockPos origin = ctx.playerFeet(); - int renderDistance = (mc.gameSettings.renderDistanceChunks + 1) * 16; - mc.renderGlobal.markBlockRangeForRenderUpdate( + int renderDistance = (ctx.minecraft().gameSettings.renderDistanceChunks + 1) * 16; + ctx.minecraft().renderGlobal.markBlockRangeForRenderUpdate( origin.x - renderDistance, 0, origin.z - renderDistance, diff --git a/src/main/java/baritone/command/defaults/SelCommand.java b/src/main/java/baritone/command/defaults/SelCommand.java index 9abe417ac..78035aa4e 100644 --- a/src/main/java/baritone/command/defaults/SelCommand.java +++ b/src/main/java/baritone/command/defaults/SelCommand.java @@ -92,7 +92,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { if (action == Action.POS2 && pos1 == null) { throw new CommandInvalidStateException("Set pos1 first before using pos2"); } - BetterBlockPos playerPos = mc.getRenderViewEntity() != null ? BetterBlockPos.from(new BlockPos(mc.getRenderViewEntity())) : ctx.playerFeet(); + BetterBlockPos playerPos = ctx.viewerPos(); BetterBlockPos pos = args.hasAny() ? args.getDatatypePost(RelativeBlockPos.INSTANCE, playerPos) : playerPos; args.requireMax(0); if (action == Action.POS1) { @@ -198,7 +198,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { baritone.getBuilderProcess().build("Fill", composite, origin); logDirect("Filling now"); } else if (action == Action.COPY) { - BetterBlockPos playerPos = mc.getRenderViewEntity() != null ? BetterBlockPos.from(new BlockPos(mc.getRenderViewEntity())) : ctx.playerFeet(); + BetterBlockPos playerPos = ctx.viewerPos(); BetterBlockPos pos = args.hasAny() ? args.getDatatypePost(RelativeBlockPos.INSTANCE, playerPos) : playerPos; args.requireMax(0); ISelection[] selections = manager.getSelections(); @@ -239,7 +239,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { clipboardOffset = origin.subtract(pos); logDirect("Selection copied"); } else if (action == Action.PASTE) { - BetterBlockPos playerPos = mc.getRenderViewEntity() != null ? BetterBlockPos.from(new BlockPos(mc.getRenderViewEntity())) : ctx.playerFeet(); + BetterBlockPos playerPos = ctx.viewerPos(); BetterBlockPos pos = args.hasAny() ? args.getDatatypePost(RelativeBlockPos.INSTANCE, playerPos) : playerPos; args.requireMax(0); if (clipboard == null) { diff --git a/src/main/java/baritone/command/defaults/SurfaceCommand.java b/src/main/java/baritone/command/defaults/SurfaceCommand.java index 5d914aded..9ab22bdc2 100644 --- a/src/main/java/baritone/command/defaults/SurfaceCommand.java +++ b/src/main/java/baritone/command/defaults/SurfaceCommand.java @@ -54,7 +54,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { for (int currentIteratedY = startingYPos; currentIteratedY < worldHeight; currentIteratedY++) { final BetterBlockPos newPos = new BetterBlockPos(playerPos.getX(), currentIteratedY, playerPos.getZ()); - if (!(mc.world.getBlockState(newPos).getBlock() instanceof BlockAir) && newPos.getY() > playerPos.getY()) { + if (!(ctx.world().getBlockState(newPos).getBlock() instanceof BlockAir) && newPos.getY() > playerPos.getY()) { Goal goal = new GoalBlock(newPos.up()); logDirect(String.format("Going to: %s", goal.toString())); baritone.getCustomGoalProcess().setGoalAndPath(goal); diff --git a/src/main/java/baritone/utils/IRenderer.java b/src/main/java/baritone/utils/IRenderer.java index 26a7cf1ad..2134bcb99 100644 --- a/src/main/java/baritone/utils/IRenderer.java +++ b/src/main/java/baritone/utils/IRenderer.java @@ -19,11 +19,12 @@ import baritone.api.BaritoneAPI; import baritone.api.Settings; -import baritone.api.utils.Helper; +import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.math.AxisAlignedBB; @@ -35,7 +36,8 @@ public interface IRenderer { Tessellator tessellator = Tessellator.getInstance(); BufferBuilder buffer = tessellator.getBuffer(); - RenderManager renderManager = Helper.mc.getRenderManager(); + RenderManager renderManager = Minecraft.getMinecraft().getRenderManager(); + TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); Settings settings = BaritoneAPI.getSettings(); float[] color = new float[] {1.0F, 1.0F, 1.0F, 255.0F}; diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index deec261d4..65bf6269c 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -22,7 +22,7 @@ import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.*; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.Helper; +import baritone.api.utils.IPlayerContext; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.behavior.PathingBehavior; import baritone.pathing.path.PathExecutor; @@ -52,31 +52,40 @@ public final class PathRenderer implements IRenderer { private PathRenderer() {} public static void render(RenderEvent event, PathingBehavior behavior) { - float partialTicks = event.getPartialTicks(); - Goal goal = behavior.getGoal(); - if (Helper.mc.currentScreen instanceof GuiClick) { - ((GuiClick) Helper.mc.currentScreen).onRender(); + final IPlayerContext ctx = behavior.ctx; + if (ctx.world() == null) { + return; + } + if (ctx.minecraft().currentScreen instanceof GuiClick) { + ((GuiClick) ctx.minecraft().currentScreen).onRender(); } - int thisPlayerDimension = behavior.baritone.getPlayerContext().world().provider.getDimensionType().getId(); - int currentRenderViewDimension = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().provider.getDimensionType().getId(); + final float partialTicks = event.getPartialTicks(); + final Goal goal = behavior.getGoal(); + + final int thisPlayerDimension = ctx.world().provider.getDimensionType().getId(); + final int currentRenderViewDimension = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().provider.getDimensionType().getId(); if (thisPlayerDimension != currentRenderViewDimension) { // this is a path for a bot in a different dimension, don't render it return; } - Entity renderView = Helper.mc.getRenderViewEntity(); - - if (renderView.world != BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world()) { - System.out.println("I have no idea what's going on"); - System.out.println("The primary baritone is in a different world than the render view entity"); - System.out.println("Not rendering the path"); - return; - } + // TODO: This is goofy 💀 (pr/deprecateHelperMc) + // renderView isn't even needed for drawGoal since it's only used to + // calculate GoalYLevel x/z bounds, and ends up just cancelling itself + // out because of viewerPosX/Y/Z. I just changed it to center around the + // actual player so the goal box doesn't follow the camera in freecam. +// Entity renderView = Helper.mc.getRenderViewEntity(); +// if (renderView.world != BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world()) { +// System.out.println("I have no idea what's going on"); +// System.out.println("The primary baritone is in a different world than the render view entity"); +// System.out.println("Not rendering the path"); +// return; +// } if (goal != null && settings.renderGoal.value) { - drawGoal(renderView, goal, partialTicks, settings.colorGoalBox.value); + drawGoal(ctx.player(), goal, partialTicks, settings.colorGoalBox.value); } if (!settings.renderPath.value) { @@ -86,9 +95,9 @@ public static void render(RenderEvent event, PathingBehavior behavior) { 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 if (current != null && settings.renderSelectionBoxes.value) { - drawManySelectionBoxes(renderView, current.toBreak(), settings.colorBlocksToBreak.value); - drawManySelectionBoxes(renderView, current.toPlace(), settings.colorBlocksToPlace.value); - drawManySelectionBoxes(renderView, current.toWalkInto(), settings.colorBlocksToWalkInto.value); + drawManySelectionBoxes(ctx.player(), current.toBreak(), settings.colorBlocksToBreak.value); + drawManySelectionBoxes(ctx.player(), current.toPlace(), settings.colorBlocksToPlace.value); + drawManySelectionBoxes(ctx.player(), current.toWalkInto(), settings.colorBlocksToWalkInto.value); } //drawManySelectionBoxes(player, Collections.singletonList(behavior.pathStart()), partialTicks, Color.WHITE); @@ -111,12 +120,12 @@ public static void render(RenderEvent event, PathingBehavior behavior) { currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { drawPath(mr, 0, settings.colorMostRecentConsidered.value, settings.fadePath.value, 10, 20); - drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), settings.colorMostRecentConsidered.value); + drawManySelectionBoxes(ctx.player(), Collections.singletonList(mr.getDest()), settings.colorMostRecentConsidered.value); }); }); } - public static void drawPath(IPath path, int startIndex, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) { + private static void drawPath(IPath path, int startIndex, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) { IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value); int fadeStart = fadeStart0 + startIndex; @@ -159,7 +168,7 @@ public static void drawPath(IPath path, int startIndex, Color color, boolean fad IRenderer.endLines(settings.renderPathIgnoreDepth.value); } - public static void emitLine(double x1, double y1, double z1, double x2, double y2, double z2) { + private static void emitLine(double x1, double y1, double z1, double x2, double y2, double z2) { double vpX = renderManager.viewerPosX; double vpY = renderManager.viewerPosY; double vpZ = renderManager.viewerPosZ; @@ -202,11 +211,11 @@ public static void drawManySelectionBoxes(Entity player, Collection po IRenderer.endLines(settings.renderSelectionBoxesIgnoreDepth.value); } - public static void drawGoal(Entity player, Goal goal, float partialTicks, Color color) { + private static void drawGoal(Entity player, Goal goal, float partialTicks, Color color) { drawGoal(player, goal, partialTicks, color, true); } - public static void drawGoal(Entity player, Goal goal, float partialTicks, Color color, boolean setupRender) { + private static void drawGoal(Entity player, Goal goal, float partialTicks, Color color, boolean setupRender) { double renderPosX = renderManager.viewerPosX; double renderPosY = renderManager.viewerPosY; double renderPosZ = renderManager.viewerPosZ; @@ -245,7 +254,7 @@ public static void drawGoal(Entity player, Goal goal, float partialTicks, Color if (settings.renderGoalXZBeacon.value) { glPushAttrib(GL_LIGHTING_BIT); - Helper.mc.getTextureManager().bindTexture(TileEntityBeaconRenderer.TEXTURE_BEACON_BEAM); + textureManager.bindTexture(TileEntityBeaconRenderer.TEXTURE_BEACON_BEAM); if (settings.renderGoalIgnoreDepth.value) { GlStateManager.disableDepth(); diff --git a/src/main/java/baritone/utils/player/BaritonePlayerContext.java b/src/main/java/baritone/utils/player/BaritonePlayerContext.java index 601d2bb72..7c7fe13f6 100644 --- a/src/main/java/baritone/utils/player/BaritonePlayerContext.java +++ b/src/main/java/baritone/utils/player/BaritonePlayerContext.java @@ -22,7 +22,10 @@ import baritone.api.utils.*; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.entity.Entity; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; /** @@ -68,6 +71,12 @@ public IWorldData worldData() { return this.baritone.getWorldProvider().getCurrentWorld(); } + @Override + public BetterBlockPos viewerPos() { + final Entity entity = this.mc.getRenderViewEntity(); + return entity == null ? this.playerFeet() : BetterBlockPos.from(new BlockPos(entity)); + } + @Override public Rotation playerRotations() { return this.baritone.getLookBehavior().getEffectiveRotation().orElseGet(IPlayerContext.super::playerRotations); From 2db2d8be59f8510028576c5640cd4f61ba7ebe20 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 14 Jun 2023 02:00:10 -0500 Subject: [PATCH 079/111] Steal `BaritoneList` from `bot-system` --- src/main/java/baritone/BaritoneProvider.java | 24 ++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index a0621af93..4593fefbc 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -28,7 +28,7 @@ import baritone.utils.schematic.SchematicSystem; import net.minecraft.client.Minecraft; -import java.util.Collections; +import java.util.AbstractList; import java.util.List; /** @@ -42,7 +42,7 @@ public final class BaritoneProvider implements IBaritoneProvider { { this.primary = new Baritone(Minecraft.getMinecraft()); - this.all = Collections.singletonList(this.primary); + this.all = this.new BaritoneList(); // Setup chat control, just for the primary instance this.primary.registerBehavior(ExampleBaritoneControl::new); @@ -50,12 +50,12 @@ public final class BaritoneProvider implements IBaritoneProvider { @Override public IBaritone getPrimaryBaritone() { - return primary; + return this.primary; } @Override public List getAllBaritones() { - return all; + return this.all; } @Override @@ -72,4 +72,20 @@ public ICommandSystem getCommandSystem() { public ISchematicSystem getSchematicSystem() { return SchematicSystem.INSTANCE; } + + private final class BaritoneList extends AbstractList { + + @Override + public int size() { + return 1; + } + + @Override + public IBaritone get(int index) { + if (index == 0) { + return BaritoneProvider.this.primary; + } + throw new IndexOutOfBoundsException(); + } + } } From 5b39c0dd969bcedc44fb864647f9713550316e98 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 14 Jun 2023 12:18:50 -0500 Subject: [PATCH 080/111] Remove `getMinecraft()` from `BlockStateInterface` --- .../java/baritone/api/process/IBuilderProcess.java | 1 + .../java/baritone/behavior/PathingBehavior.java | 1 - .../pathing/movement/CalculationContext.java | 4 ++-- .../java/baritone/utils/BlockStateInterface.java | 14 ++++---------- .../utils/BlockStateInterfaceAccessWrapper.java | 6 ++++-- .../utils/player/BaritonePlayerContext.java | 1 - 6 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/api/java/baritone/api/process/IBuilderProcess.java b/src/api/java/baritone/api/process/IBuilderProcess.java index c63113cdd..29d8968a7 100644 --- a/src/api/java/baritone/api/process/IBuilderProcess.java +++ b/src/api/java/baritone/api/process/IBuilderProcess.java @@ -51,6 +51,7 @@ public interface IBuilderProcess extends IBaritoneProcess { */ boolean build(String name, File schematic, Vec3i origin); + @Deprecated default boolean build(String schematicFile, BlockPos origin) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); return build(schematicFile, file, origin); diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index f5433fe8d..31a884622 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -36,7 +36,6 @@ import baritone.utils.PathRenderer; import baritone.utils.PathingCommandContext; import baritone.utils.pathing.Favoring; -import net.minecraft.client.settings.GameSettings; import net.minecraft.util.math.BlockPos; import java.util.ArrayList; diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 177435ef1..129f00e20 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -91,8 +91,8 @@ public CalculationContext(IBaritone baritone, boolean forUseOnAnotherThread) { this.baritone = baritone; EntityPlayerSP player = baritone.getPlayerContext().player(); this.world = baritone.getPlayerContext().world(); - this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld(); - this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); + this.worldData = (WorldData) baritone.getPlayerContext().worldData(); + this.bsi = new BlockStateInterface(baritone.getPlayerContext(), forUseOnAnotherThread); this.toolSet = new ToolSet(player); this.hasThrowaway = Baritone.settings().allowPlace.value && ((Baritone) baritone).getInventoryBehavior().hasGenericThrowaway(); this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.value && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether(); diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index f451c2f1d..1d6dcaf79 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -27,7 +27,6 @@ import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import net.minecraft.block.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.ChunkPos; @@ -44,7 +43,6 @@ public class BlockStateInterface { private final Long2ObjectMap loadedChunks; private final WorldData worldData; - protected final IBlockAccess world; public final BlockPos.MutableBlockPos isPassableBlockPos; public final IBlockAccess access; public final BetterWorldBorder worldBorder; @@ -61,13 +59,9 @@ public BlockStateInterface(IPlayerContext ctx) { } public BlockStateInterface(IPlayerContext ctx, boolean copyLoadedChunks) { - this(ctx.world(), (WorldData) ctx.worldData(), copyLoadedChunks); - } - - public BlockStateInterface(World world, WorldData worldData, boolean copyLoadedChunks) { - this.world = world; + final World world = ctx.world(); this.worldBorder = new BetterWorldBorder(world.getWorldBorder()); - this.worldData = worldData; + this.worldData = (WorldData) ctx.worldData(); Long2ObjectMap worldLoaded = ((IChunkProviderClient) world.getChunkProvider()).loadedChunks(); if (copyLoadedChunks) { this.loadedChunks = new Long2ObjectOpenHashMap<>(worldLoaded); // make a copy that we can safely access from another thread @@ -75,11 +69,11 @@ public BlockStateInterface(World world, WorldData worldData, boolean copyLoadedC this.loadedChunks = worldLoaded; // this will only be used on the main thread } this.useTheRealWorld = !Baritone.settings().pathThroughCachedOnly.value; - if (!Minecraft.getMinecraft().isCallingFromMinecraftThread()) { + if (!ctx.minecraft().isCallingFromMinecraftThread()) { throw new IllegalStateException(); } this.isPassableBlockPos = new BlockPos.MutableBlockPos(); - this.access = new BlockStateInterfaceAccessWrapper(this); + this.access = new BlockStateInterfaceAccessWrapper(this, world); } public boolean worldContainsLoadedChunk(int blockX, int blockZ) { diff --git a/src/main/java/baritone/utils/BlockStateInterfaceAccessWrapper.java b/src/main/java/baritone/utils/BlockStateInterfaceAccessWrapper.java index 6dded1dd5..7ebde5f23 100644 --- a/src/main/java/baritone/utils/BlockStateInterfaceAccessWrapper.java +++ b/src/main/java/baritone/utils/BlockStateInterfaceAccessWrapper.java @@ -37,9 +37,11 @@ public final class BlockStateInterfaceAccessWrapper implements IBlockAccess { private final BlockStateInterface bsi; + private final IBlockAccess world; - BlockStateInterfaceAccessWrapper(BlockStateInterface bsi) { + BlockStateInterfaceAccessWrapper(BlockStateInterface bsi, IBlockAccess world) { this.bsi = bsi; + this.world = world; } @Nullable @@ -76,6 +78,6 @@ public int getStrongPower(BlockPos pos, EnumFacing direction) { @Override public WorldType getWorldType() { - return this.bsi.world.getWorldType(); + return this.world.getWorldType(); } } diff --git a/src/main/java/baritone/utils/player/BaritonePlayerContext.java b/src/main/java/baritone/utils/player/BaritonePlayerContext.java index 7c7fe13f6..282d3d8b6 100644 --- a/src/main/java/baritone/utils/player/BaritonePlayerContext.java +++ b/src/main/java/baritone/utils/player/BaritonePlayerContext.java @@ -25,7 +25,6 @@ import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; /** From ae66004b80b69d802d507a4812995583d9525d34 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 14 Jun 2023 13:52:27 -0500 Subject: [PATCH 081/111] Custom registration of `Baritone` instances from `Minecraft` --- .../java/baritone/api/IBaritoneProvider.java | 40 ++++++++++++++-- src/main/java/baritone/BaritoneProvider.java | 48 +++++++++---------- 2 files changed, 60 insertions(+), 28 deletions(-) diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index 84a8abbbd..55d208e03 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -21,6 +21,7 @@ import baritone.api.command.ICommand; import baritone.api.command.ICommandSystem; import baritone.api.schematic.ISchematicSystem; +import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import java.util.List; @@ -52,15 +53,13 @@ public interface IBaritoneProvider { List getAllBaritones(); /** - * Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. This will likely be - * replaced with or be overloaded in addition to {@code #getBaritoneForUser(IBaritoneUser)} when - * {@code bot-system} is merged into {@code master}. + * Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. * * @param player The player * @return The {@link IBaritone} instance. */ default IBaritone getBaritoneForPlayer(EntityPlayerSP player) { - for (IBaritone baritone : getAllBaritones()) { + for (IBaritone baritone : this.getAllBaritones()) { if (Objects.equals(player, baritone.getPlayerContext().player())) { return baritone; } @@ -68,6 +67,39 @@ default IBaritone getBaritoneForPlayer(EntityPlayerSP player) { return null; } + /** + * Provides the {@link IBaritone} instance for a given {@link Minecraft}. + * + * @param minecraft The minecraft + * @return The {@link IBaritone} instance. + */ + default IBaritone getBaritoneForMinecraft(Minecraft minecraft) { + for (IBaritone baritone : this.getAllBaritones()) { + if (Objects.equals(minecraft, baritone.getPlayerContext().minecraft())) { + return baritone; + } + } + return null; + } + + /** + * Creates and registers a new {@link IBaritone} instance using the specified {@link Minecraft}. The existing + * instance is returned if already registered. + * + * @param minecraft The minecraft + * @return The {@link IBaritone} instance + */ + IBaritone createBaritone(Minecraft minecraft); + + /** + * Destroys and removes the specified {@link IBaritone} instance. If the specified instance is the + * {@link #getPrimaryBaritone() primary baritone}, this operation has no effect and will return {@code false}. + * + * @param baritone The baritone instance to remove + * @return Whether the baritone instance was removed + */ + boolean destroyBaritone(IBaritone baritone); + /** * Returns the {@link IWorldScanner} instance. This is not a type returned by * {@link IBaritone} implementation, because it is not linked with {@link IBaritone}. diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index 4593fefbc..b96cf03f7 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -28,8 +28,9 @@ import baritone.utils.schematic.SchematicSystem; import net.minecraft.client.Minecraft; -import java.util.AbstractList; +import java.util.Collections; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; /** * @author Brady @@ -37,25 +38,40 @@ */ public final class BaritoneProvider implements IBaritoneProvider { - private final Baritone primary; private final List all; + private final List allView; - { - this.primary = new Baritone(Minecraft.getMinecraft()); - this.all = this.new BaritoneList(); + public BaritoneProvider() { + this.all = new CopyOnWriteArrayList<>(); + this.allView = Collections.unmodifiableList(this.all); // Setup chat control, just for the primary instance - this.primary.registerBehavior(ExampleBaritoneControl::new); + final Baritone primary = (Baritone) this.createBaritone(Minecraft.getMinecraft()); + primary.registerBehavior(ExampleBaritoneControl::new); } @Override public IBaritone getPrimaryBaritone() { - return this.primary; + return this.all.get(0); } @Override public List getAllBaritones() { - return this.all; + return this.allView; + } + + @Override + public synchronized IBaritone createBaritone(Minecraft minecraft) { + IBaritone baritone = this.getBaritoneForMinecraft(minecraft); + if (baritone == null) { + this.all.add(baritone = new Baritone(minecraft)); + } + return baritone; + } + + @Override + public synchronized boolean destroyBaritone(IBaritone baritone) { + return baritone != this.getPrimaryBaritone() && this.all.remove(baritone); } @Override @@ -72,20 +88,4 @@ public ICommandSystem getCommandSystem() { public ISchematicSystem getSchematicSystem() { return SchematicSystem.INSTANCE; } - - private final class BaritoneList extends AbstractList { - - @Override - public int size() { - return 1; - } - - @Override - public IBaritone get(int index) { - if (index == 0) { - return BaritoneProvider.this.primary; - } - throw new IndexOutOfBoundsException(); - } - } } From 8534e1ba552135f83924c7a66550ff4f46d88459 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 14 Jun 2023 14:04:34 -0500 Subject: [PATCH 082/111] =?UTF-8?q?=F0=9F=92=9A=20appease=20codacy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/baritone/Baritone.java | 42 ++++++++++++++++------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index e85b57ce4..776e646af 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -20,7 +20,9 @@ import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; +import baritone.api.behavior.IBehavior; import baritone.api.event.listener.IEventBus; +import baritone.api.process.IBaritoneProcess; import baritone.api.utils.IPlayerContext; import baritone.behavior.*; import baritone.cache.WorldProvider; @@ -64,7 +66,6 @@ public class Baritone implements IBaritone { private final PathingBehavior pathingBehavior; private final LookBehavior lookBehavior; private final InventoryBehavior inventoryBehavior; - private final WaypointBehavior waypointBehavior; private final InputOverrideHandler inputOverrideHandler; private final FollowProcess followProcess; @@ -73,7 +74,6 @@ public class Baritone implements IBaritone { private final CustomGoalProcess customGoalProcess; private final BuilderProcess builderProcess; private final ExploreProcess exploreProcess; - private final BackfillProcess backfillProcess; private final FarmProcess farmProcess; private final InventoryPauserProcess inventoryPauserProcess; @@ -101,24 +101,24 @@ public class Baritone implements IBaritone { this.playerContext = new BaritonePlayerContext(this, mc); { - pathingBehavior = this.registerBehavior(PathingBehavior::new); - lookBehavior = this.registerBehavior(LookBehavior::new); - inventoryBehavior = this.registerBehavior(InventoryBehavior::new); - inputOverrideHandler = this.registerBehavior(InputOverrideHandler::new); - waypointBehavior = this.registerBehavior(WaypointBehavior::new); + this.pathingBehavior = this.registerBehavior(PathingBehavior::new); + this.lookBehavior = this.registerBehavior(LookBehavior::new); + this.inventoryBehavior = this.registerBehavior(InventoryBehavior::new); + this.inputOverrideHandler = this.registerBehavior(InputOverrideHandler::new); + this.registerBehavior(WaypointBehavior::new); } this.pathingControlManager = new PathingControlManager(this); { - this.pathingControlManager.registerProcess(followProcess = new FollowProcess(this)); - this.pathingControlManager.registerProcess(mineProcess = new MineProcess(this)); - this.pathingControlManager.registerProcess(customGoalProcess = new CustomGoalProcess(this)); // very high iq - this.pathingControlManager.registerProcess(getToBlockProcess = new GetToBlockProcess(this)); - this.pathingControlManager.registerProcess(builderProcess = new BuilderProcess(this)); - this.pathingControlManager.registerProcess(exploreProcess = new ExploreProcess(this)); - this.pathingControlManager.registerProcess(backfillProcess = new BackfillProcess(this)); - this.pathingControlManager.registerProcess(farmProcess = new FarmProcess(this)); - this.pathingControlManager.registerProcess(inventoryPauserProcess = new InventoryPauserProcess(this)); + this.followProcess = this.registerProcess(FollowProcess::new); + this.mineProcess = this.registerProcess(MineProcess::new); + this.customGoalProcess = this.registerProcess(CustomGoalProcess::new); // very high iq + this.getToBlockProcess = this.registerProcess(GetToBlockProcess::new); + this.builderProcess = this.registerProcess(BuilderProcess::new); + this.exploreProcess = this.registerProcess(ExploreProcess::new); + this.farmProcess = this.registerProcess(FarmProcess::new); + this.inventoryPauserProcess = this.registerProcess(InventoryPauserProcess::new); + this.registerProcess(BackfillProcess::new); } this.worldProvider = new WorldProvider(this); @@ -126,16 +126,22 @@ public class Baritone implements IBaritone { this.commandManager = new CommandManager(this); } - public void registerBehavior(Behavior behavior) { + public void registerBehavior(IBehavior behavior) { this.gameEventHandler.registerEventListener(behavior); } - public T registerBehavior(Function constructor) { + public T registerBehavior(Function constructor) { final T behavior = constructor.apply(this); this.registerBehavior(behavior); return behavior; } + public T registerProcess(Function constructor) { + final T behavior = constructor.apply(this); + this.pathingControlManager.registerProcess(behavior); + return behavior; + } + @Override public PathingControlManager getPathingControlManager() { return this.pathingControlManager; From ea9245ad26379a9daccae6907e132abca2d71311 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 14 Jun 2023 14:23:24 -0500 Subject: [PATCH 083/111] missed that :weary: --- src/api/java/baritone/api/utils/Helper.java | 3 ++- src/api/java/baritone/api/utils/SettingsUtil.java | 5 ++--- src/main/java/baritone/command/defaults/BuildCommand.java | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java index e49744b4f..b99074ae0 100755 --- a/src/api/java/baritone/api/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -42,7 +42,8 @@ public interface Helper { Helper HELPER = new Helper() {}; /** - * Instance of the game + * The main game instance returned by {@link Minecraft#getMinecraft()}. + * Deprecated since {@link IPlayerContext#minecraft()} should be used instead (In the majority of cases). */ @Deprecated Minecraft mc = Minecraft.getMinecraft(); diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 0b9c64737..efc080cf5 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -20,6 +20,7 @@ import baritone.api.BaritoneAPI; import baritone.api.Settings; import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; import net.minecraft.item.Item; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.Vec3i; @@ -44,8 +45,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static net.minecraft.client.Minecraft.getMinecraft; - public class SettingsUtil { public static final String SETTINGS_DEFAULT_NAME = "settings.txt"; @@ -105,7 +104,7 @@ public static synchronized void save(Settings settings) { } private static Path settingsByName(String name) { - return getMinecraft().gameDir.toPath().resolve("baritone").resolve(name); + return Minecraft.getMinecraft().gameDir.toPath().resolve("baritone").resolve(name); } public static List modifiedSettings(Settings settings) { diff --git a/src/main/java/baritone/command/defaults/BuildCommand.java b/src/main/java/baritone/command/defaults/BuildCommand.java index 724582865..12f287955 100644 --- a/src/main/java/baritone/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/command/defaults/BuildCommand.java @@ -26,7 +26,6 @@ import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandInvalidStateException; import baritone.api.utils.BetterBlockPos; -import net.minecraft.client.Minecraft; import org.apache.commons.io.FilenameUtils; import java.io.File; @@ -36,10 +35,11 @@ public class BuildCommand extends Command { - private static final File schematicsDir = new File(Minecraft.getMinecraft().gameDir, "schematics"); + private final File schematicsDir; public BuildCommand(IBaritone baritone) { super(baritone, "build"); + this.schematicsDir = new File(baritone.getPlayerContext().minecraft().gameDir, "schematics"); } @Override From f14caa3778c580877ea73d742339b67262ff4d70 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 14 Jun 2023 17:32:47 -0500 Subject: [PATCH 084/111] Fix cringe shift by injector --- .../java/baritone/launch/mixins/MixinEntityPlayerSP.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index 7c1225b9b..4f6031d78 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -61,9 +61,8 @@ private void sendChatMessage(String msg, CallbackInfo ci) { method = "onUpdate", at = @At( value = "INVOKE", - target = "net/minecraft/client/entity/EntityPlayerSP.isRiding()Z", - shift = At.Shift.BY, - by = -3 + target = "net/minecraft/client/entity/AbstractClientPlayer.onUpdate()V", + shift = At.Shift.AFTER ) ) private void onPreUpdate(CallbackInfo ci) { From 26a2945696d83227ebbc429ee1900a435eb21482 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 14 Jun 2023 19:13:07 -0500 Subject: [PATCH 085/111] remove comment --- src/main/java/baritone/utils/PathRenderer.java | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 65bf6269c..b3abc8cd2 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -71,19 +71,6 @@ public static void render(RenderEvent event, PathingBehavior behavior) { return; } - // TODO: This is goofy 💀 (pr/deprecateHelperMc) - // renderView isn't even needed for drawGoal since it's only used to - // calculate GoalYLevel x/z bounds, and ends up just cancelling itself - // out because of viewerPosX/Y/Z. I just changed it to center around the - // actual player so the goal box doesn't follow the camera in freecam. -// Entity renderView = Helper.mc.getRenderViewEntity(); -// if (renderView.world != BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world()) { -// System.out.println("I have no idea what's going on"); -// System.out.println("The primary baritone is in a different world than the render view entity"); -// System.out.println("Not rendering the path"); -// return; -// } - if (goal != null && settings.renderGoal.value) { drawGoal(ctx.player(), goal, partialTicks, settings.colorGoalBox.value); } From ef4cdfd646eda11108b1b408c0987b70b36f1802 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Fri, 16 Jun 2023 19:22:37 +0200 Subject: [PATCH 086/111] Fix render bug caused by color bug fix --- src/main/java/baritone/utils/GuiClick.java | 2 +- src/main/java/baritone/utils/IRenderer.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index 1716d74b6..72d436928 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -119,7 +119,7 @@ public void onRender() { if (clickStart != null && !clickStart.equals(currentMouseOver)) { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); - GlStateManager.color(Color.RED.getColorComponents(null)[0], Color.RED.getColorComponents(null)[1], Color.RED.getColorComponents(null)[2], 0.4F); + IRenderer.glColor(Color.RED, 0.4F); GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); diff --git a/src/main/java/baritone/utils/IRenderer.java b/src/main/java/baritone/utils/IRenderer.java index 2134bcb99..680d7e380 100644 --- a/src/main/java/baritone/utils/IRenderer.java +++ b/src/main/java/baritone/utils/IRenderer.java @@ -116,7 +116,7 @@ static void emitAABB(AxisAlignedBB aabb, double expand) { } static void drawAABB(AxisAlignedBB aabb) { - buffer.begin(GL_LINES, DefaultVertexFormats.POSITION); + buffer.begin(GL_LINES, DefaultVertexFormats.POSITION_COLOR); emitAABB(aabb); tessellator.draw(); } From f1bf1e8663724b3cb9dc0d40ce2b06807b2ff2aa Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Sat, 17 Jun 2023 00:36:35 +0200 Subject: [PATCH 087/111] Use IRenderer setup methods --- src/main/java/baritone/utils/GuiClick.java | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index 72d436928..c378aca53 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -117,21 +117,11 @@ public void onRender() { // drawSingleSelectionBox WHEN? PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(currentMouseOver), Color.CYAN); if (clickStart != null && !clickStart.equals(currentMouseOver)) { - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); - IRenderer.glColor(Color.RED, 0.4F); - GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); - GlStateManager.disableTexture2D(); - GlStateManager.depthMask(false); - GlStateManager.disableDepth(); + IRenderer.startLines(Color.RED, Baritone.settings().pathRenderLineWidthPixels.value, true); BetterBlockPos a = new BetterBlockPos(currentMouseOver); BetterBlockPos b = new BetterBlockPos(clickStart); - IRenderer.drawAABB(new AxisAlignedBB(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z), Math.max(a.x, b.x) + 1, Math.max(a.y, b.y) + 1, Math.max(a.z, b.z) + 1)); - GlStateManager.enableDepth(); - - GlStateManager.depthMask(true); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); + IRenderer.emitAABB(new AxisAlignedBB(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z), Math.max(a.x, b.x) + 1, Math.max(a.y, b.y) + 1, Math.max(a.z, b.z) + 1)); + IRenderer.endLines(true); } } } From e00e0032b49ac2f0c29f3cf3f6e70ec1ceaccd01 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Sat, 17 Jun 2023 01:40:19 +0200 Subject: [PATCH 088/111] Actually use stack hashes --- .../api/utils/BlockOptionalMetaLookup.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index 6d236e90e..6479854bc 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -17,6 +17,7 @@ package baritone.api.utils; +import baritone.api.utils.accessor.IItemStack; import com.google.common.collect.ImmutableSet; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -29,8 +30,9 @@ import java.util.stream.Stream; public class BlockOptionalMetaLookup { - private final Set blockSet; - private final Set blockStateSet; + private final ImmutableSet blockSet; + private final ImmutableSet blockStateSet; + private final ImmutableSet stackHashes; private final BlockOptionalMeta[] boms; public BlockOptionalMetaLookup(BlockOptionalMeta... boms) { @@ -45,6 +47,7 @@ public BlockOptionalMetaLookup(BlockOptionalMeta... boms) { } this.blockSet = ImmutableSet.copyOf(blocks); this.blockStateSet = ImmutableSet.copyOf(blockStates); + this.stackHashes = ImmutableSet.copyOf(stacks); } public BlockOptionalMetaLookup(Block... blocks) { @@ -75,13 +78,9 @@ public boolean has(IBlockState state) { } public boolean has(ItemStack stack) { - for (BlockOptionalMeta bom : boms) { - if (bom.matches(stack)) { - return true; - } - } - - return false; + int hash = ((IItemStack) (Object) stack).getBaritoneHash(); + return stackHashes.contains(hash) + || stackHashes.contains(hash - stack.getItemDamage()); } public List blocks() { From 6aeb73b5bd30f74a8f39271e2cd0b4fc96ec3f22 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Sun, 18 Jun 2023 19:18:46 +0200 Subject: [PATCH 089/111] Fix `CylinderMask` with horizontal alignment --- .../api/schematic/mask/shape/CylinderMask.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/schematic/mask/shape/CylinderMask.java b/src/api/java/baritone/api/schematic/mask/shape/CylinderMask.java index 71b0d43c9..790a9a05d 100644 --- a/src/api/java/baritone/api/schematic/mask/shape/CylinderMask.java +++ b/src/api/java/baritone/api/schematic/mask/shape/CylinderMask.java @@ -35,8 +35,8 @@ public final class CylinderMask extends AbstractMask implements StaticMask { public CylinderMask(int widthX, int heightY, int lengthZ, boolean filled, EnumFacing.Axis alignment) { super(widthX, heightY, lengthZ); - this.centerA = this.getA(widthX, heightY) / 2.0; - this.centerB = this.getB(heightY, lengthZ) / 2.0; + this.centerA = this.getA(widthX, heightY, alignment) / 2.0; + this.centerB = this.getB(heightY, lengthZ, alignment) / 2.0; this.radiusSqA = (this.centerA - 1) * (this.centerA - 1); this.radiusSqB = (this.centerB - 1) * (this.centerB - 1); this.filled = filled; @@ -45,8 +45,8 @@ public CylinderMask(int widthX, int heightY, int lengthZ, boolean filled, EnumFa @Override public boolean partOfMask(int x, int y, int z) { - double da = Math.abs((this.getA(x, y) + 0.5) - this.centerA); - double db = Math.abs((this.getB(y, z) + 0.5) - this.centerB); + double da = Math.abs((this.getA(x, y, this.alignment) + 0.5) - this.centerA); + double db = Math.abs((this.getB(y, z, this.alignment) + 0.5) - this.centerB); if (this.outside(da, db)) { return false; } @@ -59,11 +59,11 @@ private boolean outside(double da, double db) { return da * da / this.radiusSqA + db * db / this.radiusSqB > 1; } - private int getA(int x, int y) { - return this.alignment == EnumFacing.Axis.X ? y : x; + private static int getA(int x, int y, EnumFacing.Axis alignment) { + return alignment == EnumFacing.Axis.X ? y : x; } - private int getB(int y, int z) { - return this.alignment == EnumFacing.Axis.Z ? y : z; + private static int getB(int y, int z, EnumFacing.Axis alignment) { + return alignment == EnumFacing.Axis.Z ? y : z; } } From 5fd915ab8acf41ed379f9f05431ff24a39b96f32 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Sun, 18 Jun 2023 19:50:58 +0200 Subject: [PATCH 090/111] Tab complete the file argument for `#settings load` --- src/main/java/baritone/command/defaults/SetCommand.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/baritone/command/defaults/SetCommand.java b/src/main/java/baritone/command/defaults/SetCommand.java index dd6f1204b..4325cd625 100644 --- a/src/main/java/baritone/command/defaults/SetCommand.java +++ b/src/main/java/baritone/command/defaults/SetCommand.java @@ -22,12 +22,14 @@ import baritone.api.Settings; import baritone.api.command.Command; import baritone.api.command.argument.IArgConsumer; +import baritone.api.command.datatypes.RelativeFile; import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandInvalidStateException; import baritone.api.command.exception.CommandInvalidTypeException; import baritone.api.command.helpers.Paginator; import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.utils.SettingsUtil; +import net.minecraft.client.Minecraft; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; @@ -221,6 +223,9 @@ public Stream tabComplete(String label, IArgConsumer args) throws Comman .addToggleableSettings() .filterPrefix(args.getString()) .stream(); + } else if (Arrays.asList("ld", "load").contains(arg.toLowerCase(Locale.US))) { + // settings always use the directory of the main Minecraft instance + return RelativeFile.tabComplete(args, Minecraft.getMinecraft().gameDir.toPath().resolve("baritone").toFile()); } Settings.Setting setting = Baritone.settings().byLowerName.get(arg.toLowerCase(Locale.US)); if (setting != null) { From 6c8f2698d697c3ffaca7022f29644c6317435494 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 18 Jun 2023 19:31:51 -0700 Subject: [PATCH 091/111] cherry pick remainWithExistingLookDirection from fork --- src/api/java/baritone/api/Settings.java | 6 ++++++ src/api/java/baritone/api/utils/RotationUtils.java | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index bcd3eaa63..824dfd7e2 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -729,6 +729,12 @@ public final class Settings { */ public final Setting blockFreeLook = new Setting<>(false); + /** + * When true, the player will remain with its existing look direction as often as possible. + * Although, in some cases this can get it stuck, hence this setting to disable that behavior. + */ + public final Setting remainWithExistingLookDirection = new Setting<>(true); + /** * Will cause some minor behavioral differences to ensure that Baritone works on anticheats. *

diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index 1991ab878..b3b67d9ca 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -161,7 +161,7 @@ public static Optional reachable(IPlayerContext ctx, BlockPos pos, dou } public static Optional reachable(IPlayerContext ctx, BlockPos pos, double blockReachDistance, boolean wouldSneak) { - if (ctx.isLookingAt(pos)) { + if (BaritoneAPI.getSettings().remainWithExistingLookDirection.value && ctx.isLookingAt(pos)) { /* * why add 0.0001? * to indicate that we actually have a desired pitch From 1de2d5596594f3684e6e42b2279eb6c2c6ad42ee Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Mon, 19 Jun 2023 23:05:46 +0200 Subject: [PATCH 092/111] Tab complete block properties --- .../api/command/datatypes/BlockById.java | 122 +++++++++++++++++- 1 file changed, 116 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/command/datatypes/BlockById.java b/src/api/java/baritone/api/command/datatypes/BlockById.java index 3702725e3..8df3e0658 100644 --- a/src/api/java/baritone/api/command/datatypes/BlockById.java +++ b/src/api/java/baritone/api/command/datatypes/BlockById.java @@ -19,15 +19,28 @@ import baritone.api.command.exception.CommandException; import baritone.api.command.helpers.TabCompleteHelper; + import net.minecraft.block.Block; +import net.minecraft.block.properties.IProperty; import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import java.util.stream.Stream; public enum BlockById implements IDatatypeFor { INSTANCE; + /** + * Matches (domain:)?name([(property=value)*])? but the input can be truncated at any position. + * domain and name are [a-z0-9_.-]+ and [a-z0-9/_.-]+ because that's what mc 1.13+ accepts. + * property and value use the same format as domain. + */ + // Good luck reading this. + private static Pattern PATTERN = Pattern.compile("(?:[a-z0-9_.-]+:)?(?:[a-z0-9/_.-]+(?:\\[(?:(?:[a-z0-9_.-]+=[a-z0-9_.-]+,)*(?:[a-z0-9_.-]+(?:=(?:[a-z0-9_.-]+(?:\\])?)?)?)?|\\])?)?)?"); + @Override public Block get(IDatatypeContext ctx) throws CommandException { ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString()); @@ -40,14 +53,111 @@ public Block get(IDatatypeContext ctx) throws CommandException { @Override public Stream tabComplete(IDatatypeContext ctx) throws CommandException { + String arg = ctx.getConsumer().getString(); + + if (!PATTERN.matcher(arg).matches()) { + // Invalid format; we can't complete this. + return Stream.empty(); + } + + if (arg.endsWith("]")) { + // We are already done. + return Stream.empty(); + } + + if (!arg.contains("[")) { + // no properties so we are completing the block id + return new TabCompleteHelper() + .append( + Block.REGISTRY.getKeys() + .stream() + .map(Object::toString) + ) + .filterPrefixNamespaced(arg) + .sortAlphabetically() + .stream(); + } + + // destructuring assignment? Please? + String blockId, properties; + { + String[] parts = splitLast(arg, '['); + blockId = parts[0]; + properties = parts[1]; + } + + Block block = Block.REGISTRY.getObject(new ResourceLocation(blockId)); + if (block == null) { + // This block doesn't exist so there's no properties to complete. + return Stream.empty(); + } + + String leadingProperties, lastProperty; + { + String[] parts = splitLast(properties, ','); + leadingProperties = parts[0]; + lastProperty = parts[1]; + } + + if (!lastProperty.contains("=")) { + // The last property-value pair doesn't have a value yet so we are completing its name + Set usedProps = Stream.of(leadingProperties.split(",")) + .map(pair -> pair.split("=")[0]) + .collect(Collectors.toSet()); + + String prefix = arg.substring(0, arg.length() - lastProperty.length()); + return new TabCompleteHelper() + .append( + block.getBlockState() + .getProperties() + .stream() + .map(IProperty::getName) + ) + .filter(prop -> !usedProps.contains(prop)) + .filterPrefix(lastProperty) + .sortAlphabetically() + .map(prop -> prefix + prop) + .stream(); + } + + String lastName, lastValue; + { + String[] parts = splitLast(lastProperty, '='); + lastName = parts[0]; + lastValue = parts[1]; + } + + // We are completing the value of a property + String prefix = arg.substring(0, arg.length() - lastValue.length()); + + IProperty property = block.getBlockState().getProperty(lastName); + if (property == null) { + // The property does not exist so there's no values to complete + return Stream.empty(); + } + return new TabCompleteHelper() - .append( - Block.REGISTRY.getKeys() - .stream() - .map(Object::toString) - ) - .filterPrefixNamespaced(ctx.getConsumer().getString()) + .append(getValues(property)) + .filterPrefix(lastValue) .sortAlphabetically() + .map(val -> prefix + val) .stream(); } + + /** + * Always returns exactly two strings. + * If the separator is not found the FIRST returned string is empty. + */ + private static String[] splitLast(String string, char chr) { + int idx = string.lastIndexOf(chr); + if (idx == -1) { + return new String[]{"", string}; + } + return new String[]{string.substring(0, idx), string.substring(idx + 1)}; + } + + // this shouldn't need to be a separate method? + private static > Stream getValues(IProperty property) { + return property.getAllowedValues().stream().map(property::getName); + } } From e43200865cbdb305d11c913aae3cb90ea48ae4ab Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Mon, 19 Jun 2023 23:44:22 +0200 Subject: [PATCH 093/111] Move this to the right place --- .../api/command/datatypes/BlockById.java | 122 +----------------- .../datatypes/ForBlockOptionalMeta.java | 120 ++++++++++++++++- 2 files changed, 124 insertions(+), 118 deletions(-) diff --git a/src/api/java/baritone/api/command/datatypes/BlockById.java b/src/api/java/baritone/api/command/datatypes/BlockById.java index 8df3e0658..3702725e3 100644 --- a/src/api/java/baritone/api/command/datatypes/BlockById.java +++ b/src/api/java/baritone/api/command/datatypes/BlockById.java @@ -19,28 +19,15 @@ import baritone.api.command.exception.CommandException; import baritone.api.command.helpers.TabCompleteHelper; - import net.minecraft.block.Block; -import net.minecraft.block.properties.IProperty; import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; -import java.util.Set; -import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.stream.Stream; public enum BlockById implements IDatatypeFor { INSTANCE; - /** - * Matches (domain:)?name([(property=value)*])? but the input can be truncated at any position. - * domain and name are [a-z0-9_.-]+ and [a-z0-9/_.-]+ because that's what mc 1.13+ accepts. - * property and value use the same format as domain. - */ - // Good luck reading this. - private static Pattern PATTERN = Pattern.compile("(?:[a-z0-9_.-]+:)?(?:[a-z0-9/_.-]+(?:\\[(?:(?:[a-z0-9_.-]+=[a-z0-9_.-]+,)*(?:[a-z0-9_.-]+(?:=(?:[a-z0-9_.-]+(?:\\])?)?)?)?|\\])?)?)?"); - @Override public Block get(IDatatypeContext ctx) throws CommandException { ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString()); @@ -53,111 +40,14 @@ public Block get(IDatatypeContext ctx) throws CommandException { @Override public Stream tabComplete(IDatatypeContext ctx) throws CommandException { - String arg = ctx.getConsumer().getString(); - - if (!PATTERN.matcher(arg).matches()) { - // Invalid format; we can't complete this. - return Stream.empty(); - } - - if (arg.endsWith("]")) { - // We are already done. - return Stream.empty(); - } - - if (!arg.contains("[")) { - // no properties so we are completing the block id - return new TabCompleteHelper() - .append( - Block.REGISTRY.getKeys() - .stream() - .map(Object::toString) - ) - .filterPrefixNamespaced(arg) - .sortAlphabetically() - .stream(); - } - - // destructuring assignment? Please? - String blockId, properties; - { - String[] parts = splitLast(arg, '['); - blockId = parts[0]; - properties = parts[1]; - } - - Block block = Block.REGISTRY.getObject(new ResourceLocation(blockId)); - if (block == null) { - // This block doesn't exist so there's no properties to complete. - return Stream.empty(); - } - - String leadingProperties, lastProperty; - { - String[] parts = splitLast(properties, ','); - leadingProperties = parts[0]; - lastProperty = parts[1]; - } - - if (!lastProperty.contains("=")) { - // The last property-value pair doesn't have a value yet so we are completing its name - Set usedProps = Stream.of(leadingProperties.split(",")) - .map(pair -> pair.split("=")[0]) - .collect(Collectors.toSet()); - - String prefix = arg.substring(0, arg.length() - lastProperty.length()); - return new TabCompleteHelper() - .append( - block.getBlockState() - .getProperties() - .stream() - .map(IProperty::getName) - ) - .filter(prop -> !usedProps.contains(prop)) - .filterPrefix(lastProperty) - .sortAlphabetically() - .map(prop -> prefix + prop) - .stream(); - } - - String lastName, lastValue; - { - String[] parts = splitLast(lastProperty, '='); - lastName = parts[0]; - lastValue = parts[1]; - } - - // We are completing the value of a property - String prefix = arg.substring(0, arg.length() - lastValue.length()); - - IProperty property = block.getBlockState().getProperty(lastName); - if (property == null) { - // The property does not exist so there's no values to complete - return Stream.empty(); - } - return new TabCompleteHelper() - .append(getValues(property)) - .filterPrefix(lastValue) + .append( + Block.REGISTRY.getKeys() + .stream() + .map(Object::toString) + ) + .filterPrefixNamespaced(ctx.getConsumer().getString()) .sortAlphabetically() - .map(val -> prefix + val) .stream(); } - - /** - * Always returns exactly two strings. - * If the separator is not found the FIRST returned string is empty. - */ - private static String[] splitLast(String string, char chr) { - int idx = string.lastIndexOf(chr); - if (idx == -1) { - return new String[]{"", string}; - } - return new String[]{string.substring(0, idx), string.substring(idx + 1)}; - } - - // this shouldn't need to be a separate method? - private static > Stream getValues(IProperty property) { - return property.getAllowedValues().stream().map(property::getName); - } } diff --git a/src/api/java/baritone/api/command/datatypes/ForBlockOptionalMeta.java b/src/api/java/baritone/api/command/datatypes/ForBlockOptionalMeta.java index 978450a23..079ec03fd 100644 --- a/src/api/java/baritone/api/command/datatypes/ForBlockOptionalMeta.java +++ b/src/api/java/baritone/api/command/datatypes/ForBlockOptionalMeta.java @@ -18,20 +18,136 @@ package baritone.api.command.datatypes; import baritone.api.command.exception.CommandException; +import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.utils.BlockOptionalMeta; +import net.minecraft.block.Block; +import net.minecraft.block.properties.IProperty; +import net.minecraft.util.ResourceLocation; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import java.util.stream.Stream; public enum ForBlockOptionalMeta implements IDatatypeFor { INSTANCE; + /** + * Matches (domain:)?name([(property=value)*])? but the input can be truncated at any position. + * domain and name are [a-z0-9_.-]+ and [a-z0-9/_.-]+ because that's what mc 1.13+ accepts. + * property and value use the same format as domain. + */ + // Good luck reading this. + private static Pattern PATTERN = Pattern.compile("(?:[a-z0-9_.-]+:)?(?:[a-z0-9/_.-]+(?:\\[(?:(?:[a-z0-9_.-]+=[a-z0-9_.-]+,)*(?:[a-z0-9_.-]+(?:=(?:[a-z0-9_.-]+(?:\\])?)?)?)?|\\])?)?)?"); + @Override public BlockOptionalMeta get(IDatatypeContext ctx) throws CommandException { return new BlockOptionalMeta(ctx.getConsumer().getString()); } @Override - public Stream tabComplete(IDatatypeContext ctx) { - return ctx.getConsumer().tabCompleteDatatype(BlockById.INSTANCE); + public Stream tabComplete(IDatatypeContext ctx) throws CommandException { + String arg = ctx.getConsumer().peekString(); + + if (!PATTERN.matcher(arg).matches()) { + // Invalid format; we can't complete this. + ctx.getConsumer().getString(); + return Stream.empty(); + } + + if (arg.endsWith("]")) { + // We are already done. + ctx.getConsumer().getString(); + return Stream.empty(); + } + + if (!arg.contains("[")) { + // no properties so we are completing the block id + return ctx.getConsumer().tabCompleteDatatype(BlockById.INSTANCE); + } + + ctx.getConsumer().getString(); + + // destructuring assignment? Please? + String blockId, properties; + { + String[] parts = splitLast(arg, '['); + blockId = parts[0]; + properties = parts[1]; + } + + Block block = Block.REGISTRY.getObject(new ResourceLocation(blockId)); + if (block == null) { + // This block doesn't exist so there's no properties to complete. + return Stream.empty(); + } + + String leadingProperties, lastProperty; + { + String[] parts = splitLast(properties, ','); + leadingProperties = parts[0]; + lastProperty = parts[1]; + } + + if (!lastProperty.contains("=")) { + // The last property-value pair doesn't have a value yet so we are completing its name + Set usedProps = Stream.of(leadingProperties.split(",")) + .map(pair -> pair.split("=")[0]) + .collect(Collectors.toSet()); + + String prefix = arg.substring(0, arg.length() - lastProperty.length()); + return new TabCompleteHelper() + .append( + block.getBlockState() + .getProperties() + .stream() + .map(IProperty::getName) + ) + .filter(prop -> !usedProps.contains(prop)) + .filterPrefix(lastProperty) + .sortAlphabetically() + .map(prop -> prefix + prop) + .stream(); + } + + String lastName, lastValue; + { + String[] parts = splitLast(lastProperty, '='); + lastName = parts[0]; + lastValue = parts[1]; + } + + // We are completing the value of a property + String prefix = arg.substring(0, arg.length() - lastValue.length()); + + IProperty property = block.getBlockState().getProperty(lastName); + if (property == null) { + // The property does not exist so there's no values to complete + return Stream.empty(); + } + + return new TabCompleteHelper() + .append(getValues(property)) + .filterPrefix(lastValue) + .sortAlphabetically() + .map(val -> prefix + val) + .stream(); + } + + /** + * Always returns exactly two strings. + * If the separator is not found the FIRST returned string is empty. + */ + private static String[] splitLast(String string, char chr) { + int idx = string.lastIndexOf(chr); + if (idx == -1) { + return new String[]{"", string}; + } + return new String[]{string.substring(0, idx), string.substring(idx + 1)}; + } + + // this shouldn't need to be a separate method? + private static > Stream getValues(IProperty property) { + return property.getAllowedValues().stream().map(property::getName); } } From f55f7f19b4bb6ad6d36bdaeabe0eb6bcc6b84748 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Mon, 19 Jun 2023 23:50:42 +0200 Subject: [PATCH 094/111] Tab complete the datatype which will be parsed --- src/main/java/baritone/command/defaults/GotoCommand.java | 3 +-- src/main/java/baritone/command/defaults/MineCommand.java | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/command/defaults/GotoCommand.java b/src/main/java/baritone/command/defaults/GotoCommand.java index 333d7fa57..fc43026bb 100644 --- a/src/main/java/baritone/command/defaults/GotoCommand.java +++ b/src/main/java/baritone/command/defaults/GotoCommand.java @@ -20,7 +20,6 @@ import baritone.api.IBaritone; import baritone.api.command.Command; import baritone.api.command.argument.IArgConsumer; -import baritone.api.command.datatypes.BlockById; import baritone.api.command.datatypes.ForBlockOptionalMeta; import baritone.api.command.datatypes.RelativeCoordinate; import baritone.api.command.datatypes.RelativeGoal; @@ -61,7 +60,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { public Stream tabComplete(String label, IArgConsumer args) throws CommandException { // since it's either a goal or a block, I don't think we can tab complete properly? // so just tab complete for the block variant - return args.tabCompleteDatatype(BlockById.INSTANCE); + return args.tabCompleteDatatype(ForBlockOptionalMeta.INSTANCE); } @Override diff --git a/src/main/java/baritone/command/defaults/MineCommand.java b/src/main/java/baritone/command/defaults/MineCommand.java index 1ab5c3321..52e9e0e67 100644 --- a/src/main/java/baritone/command/defaults/MineCommand.java +++ b/src/main/java/baritone/command/defaults/MineCommand.java @@ -21,7 +21,6 @@ import baritone.api.IBaritone; import baritone.api.command.Command; import baritone.api.command.argument.IArgConsumer; -import baritone.api.command.datatypes.BlockById; import baritone.api.command.datatypes.ForBlockOptionalMeta; import baritone.api.command.exception.CommandException; import baritone.api.utils.BlockOptionalMeta; @@ -53,7 +52,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { @Override public Stream tabComplete(String label, IArgConsumer args) { - return args.tabCompleteDatatype(BlockById.INSTANCE); + return args.tabCompleteDatatype(ForBlockOptionalMeta.INSTANCE); } @Override From 13742df877ac734eb393df5d8a2dcd6336b3bdb5 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Tue, 20 Jun 2023 00:00:52 +0200 Subject: [PATCH 095/111] Complete the last argument, not the first one --- src/main/java/baritone/command/defaults/MineCommand.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/command/defaults/MineCommand.java b/src/main/java/baritone/command/defaults/MineCommand.java index 52e9e0e67..0f0f9bcb1 100644 --- a/src/main/java/baritone/command/defaults/MineCommand.java +++ b/src/main/java/baritone/command/defaults/MineCommand.java @@ -51,7 +51,11 @@ public void execute(String label, IArgConsumer args) throws CommandException { } @Override - public Stream tabComplete(String label, IArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) throws CommandException { + args.getAsOrDefault(Integer.class, 0); + while (args.has(2)) { + args.getDatatypeFor(ForBlockOptionalMeta.INSTANCE); + } return args.tabCompleteDatatype(ForBlockOptionalMeta.INSTANCE); } From 84777c2437cb72a028a9f59148187a5c503807c0 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Tue, 20 Jun 2023 00:01:33 +0200 Subject: [PATCH 096/111] Don't complete more than what's supported --- src/main/java/baritone/command/defaults/GotoCommand.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/command/defaults/GotoCommand.java b/src/main/java/baritone/command/defaults/GotoCommand.java index fc43026bb..c64d7fa00 100644 --- a/src/main/java/baritone/command/defaults/GotoCommand.java +++ b/src/main/java/baritone/command/defaults/GotoCommand.java @@ -60,6 +60,7 @@ public void execute(String label, IArgConsumer args) throws CommandException { public Stream tabComplete(String label, IArgConsumer args) throws CommandException { // since it's either a goal or a block, I don't think we can tab complete properly? // so just tab complete for the block variant + args.requireMax(1); return args.tabCompleteDatatype(ForBlockOptionalMeta.INSTANCE); } From b111fd2f3ef610dfebc5c3b41e1d4021ff829213 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Tue, 20 Jun 2023 00:02:56 +0200 Subject: [PATCH 097/111] Don't construct malformed `ResourceLocation`s Later mc versions throw an exception when you construct a malformed `ResourceLocation`. --- .../baritone/api/command/datatypes/BlockById.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/command/datatypes/BlockById.java b/src/api/java/baritone/api/command/datatypes/BlockById.java index 3702725e3..0efb738ca 100644 --- a/src/api/java/baritone/api/command/datatypes/BlockById.java +++ b/src/api/java/baritone/api/command/datatypes/BlockById.java @@ -23,11 +23,17 @@ import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; +import java.util.regex.Pattern; import java.util.stream.Stream; public enum BlockById implements IDatatypeFor { INSTANCE; + /** + * Matches (domain:)?name? where domain and name are [a-z0-9_.-]+ and [a-z0-9/_.-]+ respectively. + */ + private static Pattern PATTERN = Pattern.compile("(?:[a-z0-9_.-]+:)?[a-z0-9/_.-]*"); + @Override public Block get(IDatatypeContext ctx) throws CommandException { ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString()); @@ -40,13 +46,19 @@ public Block get(IDatatypeContext ctx) throws CommandException { @Override public Stream tabComplete(IDatatypeContext ctx) throws CommandException { + String arg = ctx.getConsumer().getString(); + + if (!PATTERN.matcher(arg).matches()) { + return Stream.empty(); + } + return new TabCompleteHelper() .append( Block.REGISTRY.getKeys() .stream() .map(Object::toString) ) - .filterPrefixNamespaced(ctx.getConsumer().getString()) + .filterPrefixNamespaced(arg) .sortAlphabetically() .stream(); } From f7a20a3acf49fb1c4b6a9553d1b9d02d2bfd2e49 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Tue, 20 Jun 2023 01:32:18 +0200 Subject: [PATCH 098/111] Don't swallow random exceptions, don't bother with CommandExceptions --- src/main/java/baritone/command/argument/ArgConsumer.java | 2 ++ src/main/java/baritone/command/manager/CommandManager.java | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/command/argument/ArgConsumer.java b/src/main/java/baritone/command/argument/ArgConsumer.java index 4a80681dd..42ac1e5a0 100644 --- a/src/main/java/baritone/command/argument/ArgConsumer.java +++ b/src/main/java/baritone/command/argument/ArgConsumer.java @@ -373,6 +373,8 @@ public > T getDatatypeForOrNull(D datatype) { public Stream tabCompleteDatatype(T datatype) { try { return datatype.tabComplete(this.context); + } catch (CommandException ignored) { + // NOP } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/baritone/command/manager/CommandManager.java b/src/main/java/baritone/command/manager/CommandManager.java index e7d24eb33..26f369df9 100644 --- a/src/main/java/baritone/command/manager/CommandManager.java +++ b/src/main/java/baritone/command/manager/CommandManager.java @@ -151,9 +151,12 @@ private void execute() { private Stream tabComplete() { try { return this.command.tabComplete(this.label, this.args); + } catch (CommandException ignored) { + // NOP } catch (Throwable t) { - return Stream.empty(); + t.printStackTrace(); } + return Stream.empty(); } } } From 31c9072970685e1a16ee191a8a94d8429c694634 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Tue, 20 Jun 2023 01:36:09 +0200 Subject: [PATCH 099/111] Forgot to git add --- src/main/java/baritone/command/manager/CommandManager.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/command/manager/CommandManager.java b/src/main/java/baritone/command/manager/CommandManager.java index 26f369df9..35cad4541 100644 --- a/src/main/java/baritone/command/manager/CommandManager.java +++ b/src/main/java/baritone/command/manager/CommandManager.java @@ -21,6 +21,7 @@ import baritone.api.IBaritone; import baritone.api.command.ICommand; import baritone.api.command.argument.ICommandArgument; +import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandUnhandledException; import baritone.api.command.exception.ICommandException; import baritone.api.command.helpers.TabCompleteHelper; From d87d1ab9b55cee52abeb18b702b32573fd384006 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Tue, 20 Jun 2023 02:00:08 +0200 Subject: [PATCH 100/111] Don't call `partOfMask` out of bounds --- .../mask/operator/BinaryOperatorMask.java | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/schematic/mask/operator/BinaryOperatorMask.java b/src/api/java/baritone/api/schematic/mask/operator/BinaryOperatorMask.java index e591c7873..bcce96651 100644 --- a/src/api/java/baritone/api/schematic/mask/operator/BinaryOperatorMask.java +++ b/src/api/java/baritone/api/schematic/mask/operator/BinaryOperatorMask.java @@ -33,7 +33,7 @@ public final class BinaryOperatorMask extends AbstractMask { private final BooleanBinaryOperator operator; public BinaryOperatorMask(Mask a, Mask b, BooleanBinaryOperator operator) { - super(a.widthX(), a.heightY(), a.lengthZ()); + super(Math.max(a.widthX(), b.widthX()), Math.max(a.heightY(), b.heightY()), Math.max(a.lengthZ(), b.lengthZ())); this.a = a; this.b = b; this.operator = operator; @@ -42,11 +42,15 @@ public BinaryOperatorMask(Mask a, Mask b, BooleanBinaryOperator operator) { @Override public boolean partOfMask(int x, int y, int z, IBlockState currentState) { return this.operator.applyAsBoolean( - this.a.partOfMask(x, y, z, currentState), - this.b.partOfMask(x, y, z, currentState) + partOfMask(a, x, y, z, currentState), + partOfMask(b, x, y, z, currentState) ); } + private static boolean partOfMask(Mask mask, int x, int y, int z, IBlockState currentState) { + return x < mask.widthX() && y < mask.heightY() && z < mask.lengthZ() && mask.partOfMask(x, y, z, currentState); + } + public static final class Static extends AbstractMask implements StaticMask { private final StaticMask a; @@ -54,7 +58,7 @@ public static final class Static extends AbstractMask implements StaticMask { private final BooleanBinaryOperator operator; public Static(StaticMask a, StaticMask b, BooleanBinaryOperator operator) { - super(a.widthX(), a.heightY(), a.lengthZ()); + super(Math.max(a.widthX(), b.widthX()), Math.max(a.heightY(), b.heightY()), Math.max(a.lengthZ(), b.lengthZ())); this.a = a; this.b = b; this.operator = operator; @@ -63,9 +67,13 @@ public Static(StaticMask a, StaticMask b, BooleanBinaryOperator operator) { @Override public boolean partOfMask(int x, int y, int z) { return this.operator.applyAsBoolean( - this.a.partOfMask(x, y, z), - this.b.partOfMask(x, y, z) + partOfMask(a, x, y, z), + partOfMask(b, x, y, z) ); } + + private static boolean partOfMask(StaticMask mask, int x, int y, int z) { + return x < mask.widthX() && y < mask.heightY() && z < mask.lengthZ() && mask.partOfMask(x, y, z); + } } } From 30278a1c5254713e135c8a2a2bbf302b0fc4a2f1 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Tue, 20 Jun 2023 02:44:29 +0200 Subject: [PATCH 101/111] Implement `hashCode` for goals --- .../baritone/api/pathing/goals/GoalAxis.java | 5 ++++ .../baritone/api/pathing/goals/GoalBlock.java | 6 +++++ .../api/pathing/goals/GoalComposite.java | 5 ++++ .../api/pathing/goals/GoalGetToBlock.java | 6 +++++ .../api/pathing/goals/GoalInverted.java | 5 ++++ .../baritone/api/pathing/goals/GoalNear.java | 6 +++++ .../api/pathing/goals/GoalRunAway.java | 8 ++++++ .../pathing/goals/GoalStrictDirection.java | 9 +++++++ .../api/pathing/goals/GoalTwoBlocks.java | 6 +++++ .../baritone/api/pathing/goals/GoalXZ.java | 8 ++++++ .../api/pathing/goals/GoalYLevel.java | 5 ++++ .../java/baritone/process/BuilderProcess.java | 26 +++++++++++++++++++ .../java/baritone/process/MineProcess.java | 5 ++++ 13 files changed, 100 insertions(+) diff --git a/src/api/java/baritone/api/pathing/goals/GoalAxis.java b/src/api/java/baritone/api/pathing/goals/GoalAxis.java index ad8fb892e..6e2f84e7a 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalAxis.java +++ b/src/api/java/baritone/api/pathing/goals/GoalAxis.java @@ -47,6 +47,11 @@ public boolean equals(Object o) { return o.getClass() == GoalAxis.class; } + @Override + public int hashCode() { + return 201385781; + } + @Override public String toString() { return "GoalAxis"; diff --git a/src/api/java/baritone/api/pathing/goals/GoalBlock.java b/src/api/java/baritone/api/pathing/goals/GoalBlock.java index d76fdc7af..24faa9b34 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalBlock.java @@ -17,6 +17,7 @@ package baritone.api.pathing.goals; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -81,6 +82,11 @@ public boolean equals(Object o) { && z == goal.z; } + @Override + public int hashCode() { + return (int) BetterBlockPos.longHash(x, y, z) * 905165533; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalComposite.java b/src/api/java/baritone/api/pathing/goals/GoalComposite.java index d64f8e33e..8e13a86e4 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalComposite.java +++ b/src/api/java/baritone/api/pathing/goals/GoalComposite.java @@ -80,6 +80,11 @@ public boolean equals(Object o) { return Arrays.equals(goals, goal.goals); } + @Override + public int hashCode() { + return Arrays.hashCode(goals); + } + @Override public String toString() { return "GoalComposite" + Arrays.toString(goals); diff --git a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java index b5caafa48..b8934a480 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java @@ -17,6 +17,7 @@ package baritone.api.pathing.goals; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -75,6 +76,11 @@ public boolean equals(Object o) { && z == goal.z; } + @Override + public int hashCode() { + return (int) BetterBlockPos.longHash(x, y, z) * -49639096; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalInverted.java b/src/api/java/baritone/api/pathing/goals/GoalInverted.java index e559088ef..4a3f75315 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalInverted.java +++ b/src/api/java/baritone/api/pathing/goals/GoalInverted.java @@ -65,6 +65,11 @@ public boolean equals(Object o) { return Objects.equals(origin, goal.origin); } + @Override + public int hashCode() { + return origin.hashCode() * 495796690; + } + @Override public String toString() { return String.format("GoalInverted{%s}", origin.toString()); diff --git a/src/api/java/baritone/api/pathing/goals/GoalNear.java b/src/api/java/baritone/api/pathing/goals/GoalNear.java index 166138ff4..e211c0194 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalNear.java +++ b/src/api/java/baritone/api/pathing/goals/GoalNear.java @@ -17,6 +17,7 @@ package baritone.api.pathing.goals; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import it.unimi.dsi.fastutil.doubles.DoubleIterator; @@ -102,6 +103,11 @@ public boolean equals(Object o) { && rangeSq == goal.rangeSq; } + @Override + public int hashCode() { + return (int) BetterBlockPos.longHash(x, y, z) + rangeSq; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index 166ad5a98..1e65d30f7 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -140,6 +140,14 @@ public boolean equals(Object o) { && Objects.equals(maintainY, goal.maintainY); } + @Override + public int hashCode() { + int hash = Arrays.hashCode(from); + hash = hash * 1196803141 + distanceSq; + hash = hash * -2053788840 + maintainY; + return hash; + } + @Override public String toString() { if (maintainY != null) { diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java index b8e4b43b2..b6bf16b33 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java +++ b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java @@ -17,6 +17,7 @@ package baritone.api.pathing.goals; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.SettingsUtil; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -86,6 +87,14 @@ public boolean equals(Object o) { && dz == goal.dz; } + @Override + public int hashCode() { + int hash = (int) BetterBlockPos.longHash(x, y, z); + hash = hash * 630627507 + dx; + hash = hash * -283028380 + dz; + return hash; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java index d6fff33a2..475d6e972 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java +++ b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java @@ -17,6 +17,7 @@ package baritone.api.pathing.goals; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -87,6 +88,11 @@ public boolean equals(Object o) { && z == goal.z; } + @Override + public int hashCode() { + return (int) BetterBlockPos.longHash(x, y, z) * 516508351; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalXZ.java b/src/api/java/baritone/api/pathing/goals/GoalXZ.java index 2c551d395..1c7535b38 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalXZ.java +++ b/src/api/java/baritone/api/pathing/goals/GoalXZ.java @@ -77,6 +77,14 @@ public boolean equals(Object o) { return x == goal.x && z == goal.z; } + @Override + public int hashCode() { + int hash = 1791873246; + hash = hash * 222601791 + x; + hash = hash * -1331679453 + z; + return hash; + } + @Override public String toString() { return String.format( diff --git a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java index 37745e8de..442906ad1 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java +++ b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java @@ -71,6 +71,11 @@ public boolean equals(Object o) { return level == goal.level; } + @Override + public int hashCode() { + return level * 1271009915; + } + @Override public String toString() { return String.format( diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index ac12471a3..62f865899 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -775,6 +775,14 @@ public boolean equals(Object o) { && Objects.equals(fallback, goal.fallback); } + @Override + public int hashCode() { + int hash = -1701079641; + hash = hash * 1196141026 + primary.hashCode(); + hash = hash * -80327868 + fallback.hashCode(); + return hash; + } + @Override public String toString() { return "JankyComposite Primary: " + primary + " Fallback: " + fallback; @@ -806,6 +814,11 @@ public String toString() { SettingsUtil.maybeCensor(z) ); } + + @Override + public int hashCode() { + return super.hashCode() * 1636324008; + } } private Goal placementGoal(BlockPos pos, BuilderCalculationContext bcc) { @@ -883,6 +896,14 @@ public boolean equals(Object o) { && Objects.equals(no, goal.no); } + @Override + public int hashCode() { + int hash = 806368046; + hash = hash * 1730799370 + (int) BetterBlockPos.longHash(no.getX(), no.getY(), no.getZ()); + hash = hash * 260592149 + (allowSameLevel ? -1314802005 : 1565710265); + return hash; + } + @Override public String toString() { return String.format( @@ -906,6 +927,11 @@ public double heuristic(int x, int y, int z) { return this.y * 100 + super.heuristic(x, y, z); } + @Override + public int hashCode() { + return super.hashCode() * 1910811835; + } + @Override public String toString() { return String.format( diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 777b48197..8cd1a6cae 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -325,6 +325,11 @@ public boolean equals(Object o) { return super.equals(o); } + @Override + public int hashCode() { + return super.hashCode() * 393857768; + } + @Override public String toString() { return String.format( From 41d730fb04f1058d8bab6e57b3d04cd77926b577 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Tue, 20 Jun 2023 03:20:44 +0200 Subject: [PATCH 102/111] Forgot to include target pos --- src/main/java/baritone/process/BuilderProcess.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 62f865899..bd14d09a7 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -899,6 +899,7 @@ public boolean equals(Object o) { @Override public int hashCode() { int hash = 806368046; + hash = hash * 1412661222 + super.hashCode(); hash = hash * 1730799370 + (int) BetterBlockPos.longHash(no.getX(), no.getY(), no.getZ()); hash = hash * 260592149 + (allowSameLevel ? -1314802005 : 1565710265); return hash; From 367ce5fa177cb6806937f37983932076bcd38172 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 14 Jun 2023 16:11:11 -0500 Subject: [PATCH 103/111] cherry pick Allow freeLook when using elytra --- .../api/event/events/RotationMoveEvent.java | 38 ++++++++- .../launch/mixins/MixinEntityLivingBase.java | 85 +++++++++++++++---- .../launch/mixins/MixinEntityPlayerSP.java | 16 ---- .../launch/mixins/MixinMinecraft.java | 15 ++++ .../java/baritone/behavior/LookBehavior.java | 1 + 5 files changed, 117 insertions(+), 38 deletions(-) diff --git a/src/api/java/baritone/api/event/events/RotationMoveEvent.java b/src/api/java/baritone/api/event/events/RotationMoveEvent.java index 109061c7e..a2ab17ed6 100644 --- a/src/api/java/baritone/api/event/events/RotationMoveEvent.java +++ b/src/api/java/baritone/api/event/events/RotationMoveEvent.java @@ -17,6 +17,7 @@ package baritone.api.event.events; +import baritone.api.utils.Rotation; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -31,14 +32,27 @@ public final class RotationMoveEvent { */ private final Type type; + private final Rotation original; + /** * The yaw rotation */ private float yaw; - public RotationMoveEvent(Type type, float yaw) { + /** + * The pitch rotation + */ + private float pitch; + + public RotationMoveEvent(Type type, float yaw, float pitch) { this.type = type; + this.original = new Rotation(yaw, pitch); this.yaw = yaw; + this.pitch = pitch; + } + + public Rotation getOriginal() { + return this.original; } /** @@ -46,21 +60,37 @@ public RotationMoveEvent(Type type, float yaw) { * * @param yaw Yaw rotation */ - public final void setYaw(float yaw) { + public void setYaw(float yaw) { this.yaw = yaw; } /** * @return The yaw rotation */ - public final float getYaw() { + public float getYaw() { return this.yaw; } + /** + * Set the pitch movement rotation + * + * @param pitch Pitch rotation + */ + public void setPitch(float pitch) { + this.pitch = pitch; + } + + /** + * @return The pitch rotation + */ + public float getPitch() { + return pitch; + } + /** * @return The type of the event */ - public final Type getType() { + public Type getType() { return this.type; } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java index 0fd2436c9..f8544dd2f 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -25,11 +25,14 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; 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 java.util.Optional; + import static org.spongepowered.asm.lib.Opcodes.GETFIELD; /** @@ -42,11 +45,14 @@ public abstract class MixinEntityLivingBase extends Entity { /** * Event called to override the movement direction when jumping */ + @Unique private RotationMoveEvent jumpRotationEvent; - public MixinEntityLivingBase(World worldIn, RotationMoveEvent jumpRotationEvent) { + @Unique + private RotationMoveEvent elytraRotationEvent; + + public MixinEntityLivingBase(World worldIn) { super(worldIn); - this.jumpRotationEvent = jumpRotationEvent; } @Inject( @@ -54,14 +60,10 @@ public MixinEntityLivingBase(World worldIn, RotationMoveEvent jumpRotationEvent) at = @At("HEAD") ) private void preMoveRelative(CallbackInfo ci) { - // noinspection ConstantConditions - if (EntityPlayerSP.class.isInstance(this)) { - IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); - if (baritone != null) { - this.jumpRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.JUMP, this.rotationYaw); - baritone.getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent); - } - } + this.getBaritone().ifPresent(baritone -> { + this.jumpRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.JUMP, this.rotationYaw, this.rotationPitch); + baritone.getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent); + }); } @Redirect( @@ -79,6 +81,38 @@ private float overrideYaw(EntityLivingBase self) { return self.rotationYaw; } + @Inject( + method = "travel", + at = @At( + value = "INVOKE", + target = "net/minecraft/entity/EntityLivingBase.getLookVec()Lnet/minecraft/util/math/Vec3d;" + ) + ) + private void onPreElytraMove(float strafe, float vertical, float forward, CallbackInfo ci) { + this.getBaritone().ifPresent(baritone -> { + this.elytraRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw, this.rotationPitch); + baritone.getGameEventHandler().onPlayerRotationMove(this.elytraRotationEvent); + this.rotationYaw = this.elytraRotationEvent.getYaw(); + this.rotationPitch = this.elytraRotationEvent.getPitch(); + }); + } + + @Inject( + method = "travel", + at = @At( + value = "INVOKE", + target = "net/minecraft/entity/EntityLivingBase.move(Lnet/minecraft/entity/MoverType;DDD)V", + shift = At.Shift.AFTER + ) + ) + private void onPostElytraMove(float strafe, float vertical, float forward, CallbackInfo ci) { + if (this.elytraRotationEvent != null) { + this.rotationYaw = this.elytraRotationEvent.getOriginal().getYaw(); + this.rotationPitch = this.elytraRotationEvent.getOriginal().getPitch(); + this.elytraRotationEvent = null; + } + } + @Redirect( method = "travel", at = @At( @@ -86,17 +120,32 @@ private float overrideYaw(EntityLivingBase self) { target = "net/minecraft/entity/EntityLivingBase.moveRelative(FFFF)V" ) ) - private void travel(EntityLivingBase self, float strafe, float up, float forward, float friction) { - // noinspection ConstantConditions - if (!EntityPlayerSP.class.isInstance(this) || BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this) == null) { + private void onMoveRelative(EntityLivingBase self, float strafe, float up, float forward, float friction) { + Optional baritone = this.getBaritone(); + if (!baritone.isPresent()) { moveRelative(strafe, up, forward, friction); return; } - RotationMoveEvent motionUpdateRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw); - BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(motionUpdateRotationEvent); - float originalYaw = this.rotationYaw; - this.rotationYaw = motionUpdateRotationEvent.getYaw(); + + RotationMoveEvent event = new RotationMoveEvent(RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw, this.rotationPitch); + baritone.get().getGameEventHandler().onPlayerRotationMove(event); + + this.rotationYaw = event.getYaw(); + this.rotationPitch = event.getPitch(); + this.moveRelative(strafe, up, forward, friction); - this.rotationYaw = originalYaw; + + this.rotationYaw = event.getOriginal().getYaw(); + this.rotationPitch = event.getOriginal().getPitch(); + } + + @Unique + private Optional getBaritone() { + // noinspection ConstantConditions + if (EntityPlayerSP.class.isInstance(this)) { + return Optional.ofNullable(BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this)); + } else { + return Optional.empty(); + } } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index 4f6031d78..281ff96f5 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -72,22 +72,6 @@ private void onPreUpdate(CallbackInfo ci) { } } - @Inject( - method = "onUpdate", - at = @At( - value = "INVOKE", - target = "net/minecraft/client/entity/EntityPlayerSP.onUpdateWalkingPlayer()V", - shift = At.Shift.BY, - by = 2 - ) - ) - private void onPostUpdate(CallbackInfo ci) { - IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); - if (baritone != null) { - baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST)); - } - } - @Redirect( method = "onLivingUpdate", at = @At( diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 097c72905..edc1e3fcc 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -20,6 +20,7 @@ import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.event.events.BlockInteractEvent; +import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.TickEvent; import baritone.api.event.events.WorldEvent; import baritone.api.event.events.type.EventState; @@ -84,7 +85,21 @@ private void runTick(CallbackInfo ci) { baritone.getGameEventHandler().onTick(tickProvider.apply(EventState.PRE, type)); } + } + @Inject( + method = "runTick", + at = @At( + value = "INVOKE", + target = "net/minecraft/client/multiplayer/WorldClient.updateEntities()V", + shift = At.Shift.AFTER + ) + ) + private void postUpdateEntities(CallbackInfo ci) { + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(this.player); + if (baritone != null) { + baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST)); + } } @Inject( diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 67aa45e39..d3c514ac2 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -149,6 +149,7 @@ public Optional getEffectiveRotation() { public void onPlayerRotationMove(RotationMoveEvent event) { if (this.target != null) { event.setYaw(this.target.rotation.getYaw()); + event.setPitch(this.target.rotation.getPitch()); } } From 7e426bd2e8ad15ba571b9775fdf779fc09390318 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 21 Jun 2023 17:35:47 -0500 Subject: [PATCH 104/111] AimProcessor API --- .../baritone/api/behavior/ILookBehavior.java | 19 +- .../api/behavior/look/IAimProcessor.java | 44 ++++ .../java/baritone/behavior/LookBehavior.java | 188 +++++++++++++----- .../behavior/look/ForkableRandom.java | 85 ++++++++ 4 files changed, 283 insertions(+), 53 deletions(-) create mode 100644 src/api/java/baritone/api/behavior/look/IAimProcessor.java create mode 100644 src/main/java/baritone/behavior/look/ForkableRandom.java diff --git a/src/api/java/baritone/api/behavior/ILookBehavior.java b/src/api/java/baritone/api/behavior/ILookBehavior.java index 218e8b59a..eb7c992b8 100644 --- a/src/api/java/baritone/api/behavior/ILookBehavior.java +++ b/src/api/java/baritone/api/behavior/ILookBehavior.java @@ -17,6 +17,8 @@ package baritone.api.behavior; +import baritone.api.Settings; +import baritone.api.behavior.look.IAimProcessor; import baritone.api.utils.Rotation; /** @@ -27,10 +29,25 @@ public interface ILookBehavior extends IBehavior { /** * Updates the current {@link ILookBehavior} target to target the specified rotations on the next tick. If any sort - * of block interaction is required, {@code blockInteract} should be {@code true}. + * of block interaction is required, {@code blockInteract} should be {@code true}. It is not guaranteed that the + * rotations set by the caller will be the exact rotations expressed by the client (This is due to settings like + * {@link Settings#randomLooking}). If the rotations produced by this behavior are required, then the + * {@link #getAimProcessor() aim processor} should be used. * * @param rotation The target rotations * @param blockInteract Whether the target rotations are needed for a block interaction */ void updateTarget(Rotation rotation, boolean blockInteract); + + /** + * The aim processor instance for this {@link ILookBehavior}, which is responsible for applying additional, deterministic + * transformations to the target rotation set by {@link #updateTarget}. Whenever {@link IAimProcessor#nextRotation(Rotation)} + * is called on the instance returned by this method, the returned value always reflects what would happen in the + * upcoming tick. In other words, it is a pure function, and no internal state changes. If simulation of the + * rotation states beyond the next tick is required, then a {@link IAimProcessor#fork(int) fork} should be created. + * + * @return The aim processor + * @see IAimProcessor#fork(int) + */ + IAimProcessor getAimProcessor(); } diff --git a/src/api/java/baritone/api/behavior/look/IAimProcessor.java b/src/api/java/baritone/api/behavior/look/IAimProcessor.java new file mode 100644 index 000000000..72a4c681d --- /dev/null +++ b/src/api/java/baritone/api/behavior/look/IAimProcessor.java @@ -0,0 +1,44 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.behavior.look; + +import baritone.api.utils.Rotation; + +/** + * @author Brady + */ +public interface IAimProcessor { + + /** + * Returns the actual rotation that will be used when the desired rotation is requested. This is not guaranteed to + * return the same value for a given input. + * + * @param desired The desired rotation to set + * @return The actual rotation + */ + Rotation nextRotation(Rotation desired); + + /** + * Returns a copy of this {@link IAimProcessor} which has its own internal state and updates on each call to + * {@link #nextRotation(Rotation)}. + * + * @param ticksAdvanced The number of ticks to advance ahead of time + * @return The forked processor + */ + IAimProcessor fork(int ticksAdvanced); +} diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index d3c514ac2..aeb694181 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -20,13 +20,11 @@ import baritone.Baritone; import baritone.api.Settings; import baritone.api.behavior.ILookBehavior; -import baritone.api.event.events.PacketEvent; -import baritone.api.event.events.PlayerUpdateEvent; -import baritone.api.event.events.RotationMoveEvent; -import baritone.api.event.events.WorldEvent; -import baritone.api.utils.Helper; +import baritone.api.behavior.look.IAimProcessor; +import baritone.api.event.events.*; import baritone.api.utils.IPlayerContext; import baritone.api.utils.Rotation; +import baritone.behavior.look.ForkableRandom; import net.minecraft.network.play.client.CPacketPlayer; import java.util.Optional; @@ -44,14 +42,17 @@ public final class LookBehavior extends Behavior implements ILookBehavior { private Rotation serverRotation; /** - * The last player rotation. Used when free looking + * The last player rotation. Used to restore the player's angle when using free look. * * @see Settings#freeLook */ private Rotation prevRotation; + private final AimProcessor processor; + public LookBehavior(Baritone baritone) { super(baritone); + this.processor = new AimProcessor(baritone.getPlayerContext()); } @Override @@ -59,6 +60,19 @@ public void updateTarget(Rotation rotation, boolean blockInteract) { this.target = new Target(rotation, blockInteract); } + @Override + public IAimProcessor getAimProcessor() { + return this.processor; + } + + @Override + public void onTick(TickEvent event) { + if (event.getType() == TickEvent.Type.IN) { + // Unlike forked AimProcessors, the root one needs to be manually updated each game tick + this.processor.tick(); + } + } + @Override public void onPlayerUpdate(PlayerUpdateEvent event) { if (this.target == null) { @@ -67,34 +81,16 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { switch (event.getState()) { case PRE: { if (this.target.mode == Target.Mode.NONE) { + // Just return for PRE, we still want to set target to null on POST return; } if (this.target.mode == Target.Mode.SERVER) { this.prevRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); } - final float oldYaw = ctx.playerRotations().getYaw(); - final float oldPitch = ctx.playerRotations().getPitch(); - - float desiredYaw = this.target.rotation.getYaw(); - float desiredPitch = this.target.rotation.getPitch(); - - // In other words, the target doesn't care about the pitch, so it used playerRotations().getPitch() - // and it's safe to adjust it to a normal level - if (desiredPitch == oldPitch) { - desiredPitch = nudgeToLevel(desiredPitch); - } - - desiredYaw += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; - desiredPitch += (Math.random() - 0.5) * Baritone.settings().randomLooking.value; - - ctx.player().rotationYaw = calculateMouseMove(oldYaw, desiredYaw); - ctx.player().rotationPitch = calculateMouseMove(oldPitch, desiredPitch); - - if (this.target.mode == Target.Mode.CLIENT) { - // The target can be invalidated now since it won't be needed for RotationMoveEvent - this.target = null; - } + final Rotation actual = this.processor.nextRotation(this.target.rotation); + ctx.player().rotationYaw = actual.getYaw(); + ctx.player().rotationPitch = actual.getPitch(); break; } case POST: { @@ -133,7 +129,8 @@ public void onWorldEvent(WorldEvent event) { public void pig() { if (this.target != null) { - ctx.player().rotationYaw = this.target.rotation.getYaw(); + final Rotation actual = this.processor.nextRotation(this.target.rotation); + ctx.player().rotationYaw = actual.getYaw(); } } @@ -148,37 +145,124 @@ public Optional getEffectiveRotation() { @Override public void onPlayerRotationMove(RotationMoveEvent event) { if (this.target != null) { - event.setYaw(this.target.rotation.getYaw()); - event.setPitch(this.target.rotation.getPitch()); + final Rotation actual = this.target.rotation; + event.setYaw(actual.getYaw()); + event.setPitch(actual.getPitch()); } } - /** - * Nudges the player's pitch to a regular level. (Between {@code -20} and {@code 10}, increments are by {@code 1}) - */ - private static float nudgeToLevel(float pitch) { - if (pitch < -20) { - return pitch + 1; - } else if (pitch > 10) { - return pitch - 1; + private static final class AimProcessor extends AbstractAimProcessor { + + public AimProcessor(final IPlayerContext ctx) { + super(ctx); } - return pitch; - } - private float calculateMouseMove(float current, float target) { - final float delta = target - current; - final int deltaPx = angleToMouse(delta); - return current + mouseToAngle(deltaPx); + @Override + protected Rotation getPrevRotation() { + // Implementation will use LookBehavior.serverRotation + return ctx.playerRotations(); + } } - private int angleToMouse(float angleDelta) { - final float minAngleChange = mouseToAngle(1); - return Math.round(angleDelta / minAngleChange); - } + private static abstract class AbstractAimProcessor implements IAimProcessor { + + protected final IPlayerContext ctx; + private final ForkableRandom rand; + private double randomYawOffset; + private double randomPitchOffset; + + public AbstractAimProcessor(IPlayerContext ctx) { + this.ctx = ctx; + this.rand = new ForkableRandom(); + } + + private AbstractAimProcessor(final AbstractAimProcessor source) { + this.ctx = source.ctx; + this.rand = source.rand.fork(); + this.randomYawOffset = source.randomYawOffset; + this.randomPitchOffset = source.randomPitchOffset; + } - private float mouseToAngle(int mouseDelta) { - final float f = ctx.minecraft().gameSettings.mouseSensitivity * 0.6f + 0.2f; - return mouseDelta * f * f * f * 8.0f * 0.15f; + public void tick() { + this.randomYawOffset = (this.rand.nextDouble() - 0.5) * Baritone.settings().randomLooking.value; + this.randomPitchOffset = (this.rand.nextDouble() - 0.5) * Baritone.settings().randomLooking.value; + } + + @Override + public Rotation nextRotation(final Rotation rotation) { + final Rotation prev = this.getPrevRotation(); + + float desiredYaw = rotation.getYaw(); + float desiredPitch = rotation.getPitch(); + + // In other words, the target doesn't care about the pitch, so it used playerRotations().getPitch() + // and it's safe to adjust it to a normal level + if (desiredPitch == prev.getPitch()) { + desiredPitch = nudgeToLevel(desiredPitch); + } + + desiredYaw += this.randomYawOffset; + desiredPitch += this.randomPitchOffset; + + return new Rotation( + this.calculateMouseMove(prev.getYaw(), desiredYaw), + this.calculateMouseMove(prev.getPitch(), desiredPitch) + ); + } + + @Override + public final IAimProcessor fork(final int ticksAdvanced) { + final AbstractAimProcessor fork = new AbstractAimProcessor(this) { + + private Rotation prev = AbstractAimProcessor.this.getPrevRotation(); + + @Override + public Rotation nextRotation(Rotation rotation) { + final Rotation actual = super.nextRotation(rotation); + this.tick(); + return (this.prev = actual); + } + + @Override + protected Rotation getPrevRotation() { + return this.prev; + } + }; + for (int i = 0; i < ticksAdvanced; i++) { + fork.tick(); + } + return fork; + } + + protected abstract Rotation getPrevRotation(); + + /** + * Nudges the player's pitch to a regular level. (Between {@code -20} and {@code 10}, increments are by {@code 1}) + */ + private float nudgeToLevel(float pitch) { + if (pitch < -20) { + return pitch + 1; + } else if (pitch > 10) { + return pitch - 1; + } + return pitch; + } + + private float calculateMouseMove(float current, float target) { + final float delta = target - current; + final int deltaPx = angleToMouse(delta); + return current + mouseToAngle(deltaPx); + } + + private int angleToMouse(float angleDelta) { + final float minAngleChange = mouseToAngle(1); + return Math.round(angleDelta / minAngleChange); + } + + private float mouseToAngle(int mouseDelta) { + final float f = ctx.minecraft().gameSettings.mouseSensitivity * 0.6f + 0.2f; + return mouseDelta * f * f * f * 8.0f * 0.15f; + } } private static class Target { diff --git a/src/main/java/baritone/behavior/look/ForkableRandom.java b/src/main/java/baritone/behavior/look/ForkableRandom.java new file mode 100644 index 000000000..5f5f942d2 --- /dev/null +++ b/src/main/java/baritone/behavior/look/ForkableRandom.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.behavior.look; + +import java.util.Arrays; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.LongSupplier; + +/** + * Implementation of Xoroshiro256++ + *

+ * Extended to produce random double-precision floating point numbers, and allow copies to be spawned via {@link #fork}, + * which share the same internal state as the source object. + * + * @author Brady + */ +public final class ForkableRandom { + + private static final double DOUBLE_UNIT = 0x1.0p-53; + + private final long[] s; + + public ForkableRandom() { + this(System.nanoTime() ^ System.currentTimeMillis()); + } + + public ForkableRandom(long seedIn) { + final AtomicLong seed = new AtomicLong(seedIn); + final LongSupplier splitmix64 = () -> { + long z = seed.addAndGet(0x9e3779b97f4a7c15L); + z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L; + z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL; + return z ^ (z >>> 31); + }; + this.s = new long[] { + splitmix64.getAsLong(), + splitmix64.getAsLong(), + splitmix64.getAsLong(), + splitmix64.getAsLong() + }; + } + + private ForkableRandom(long[] s) { + this.s = s; + } + + public double nextDouble() { + return (this.next() >>> 11) * DOUBLE_UNIT; + } + + public long next() { + final long result = rotl(this.s[0] + this.s[3], 23) + this.s[0]; + final long t = this.s[1] << 17; + this.s[2] ^= this.s[0]; + this.s[3] ^= this.s[1]; + this.s[1] ^= this.s[2]; + this.s[0] ^= this.s[3]; + this.s[2] ^= t; + this.s[3] = rotl(this.s[3], 45); + return result; + } + + public ForkableRandom fork() { + return new ForkableRandom(Arrays.copyOf(this.s, 4)); + } + + private static long rotl(long x, int k) { + return (x << k) | (x >>> (64 - k)); + } +} From 0682e6370713961c31a56871bc32b924120556f3 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 21 Jun 2023 17:39:04 -0500 Subject: [PATCH 105/111] Apply processor to RotationMoveEvent --- src/main/java/baritone/behavior/LookBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index aeb694181..57dfd206c 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -145,7 +145,7 @@ public Optional getEffectiveRotation() { @Override public void onPlayerRotationMove(RotationMoveEvent event) { if (this.target != null) { - final Rotation actual = this.target.rotation; + final Rotation actual = this.processor.nextRotation(this.target.rotation); event.setYaw(actual.getYaw()); event.setPitch(actual.getPitch()); } From bfae100cb91b28ab41a4378997cbbc32d85f5217 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 22 Jun 2023 20:35:22 -0500 Subject: [PATCH 106/111] Create `ITickableAimProcessor` --- .../baritone/api/behavior/ILookBehavior.java | 9 ++-- .../api/behavior/look/IAimProcessor.java | 15 +++--- .../behavior/look/ITickableAimProcessor.java | 47 +++++++++++++++++ .../java/baritone/behavior/LookBehavior.java | 51 +++++++++++-------- 4 files changed, 88 insertions(+), 34 deletions(-) create mode 100644 src/api/java/baritone/api/behavior/look/ITickableAimProcessor.java diff --git a/src/api/java/baritone/api/behavior/ILookBehavior.java b/src/api/java/baritone/api/behavior/ILookBehavior.java index eb7c992b8..d78e7f8b3 100644 --- a/src/api/java/baritone/api/behavior/ILookBehavior.java +++ b/src/api/java/baritone/api/behavior/ILookBehavior.java @@ -40,14 +40,11 @@ public interface ILookBehavior extends IBehavior { void updateTarget(Rotation rotation, boolean blockInteract); /** - * The aim processor instance for this {@link ILookBehavior}, which is responsible for applying additional, deterministic - * transformations to the target rotation set by {@link #updateTarget}. Whenever {@link IAimProcessor#nextRotation(Rotation)} - * is called on the instance returned by this method, the returned value always reflects what would happen in the - * upcoming tick. In other words, it is a pure function, and no internal state changes. If simulation of the - * rotation states beyond the next tick is required, then a {@link IAimProcessor#fork(int) fork} should be created. + * The aim processor instance for this {@link ILookBehavior}, which is responsible for applying additional, + * deterministic transformations to the target rotation set by {@link #updateTarget}. * * @return The aim processor - * @see IAimProcessor#fork(int) + * @see IAimProcessor#fork */ IAimProcessor getAimProcessor(); } diff --git a/src/api/java/baritone/api/behavior/look/IAimProcessor.java b/src/api/java/baritone/api/behavior/look/IAimProcessor.java index 72a4c681d..c7c60f413 100644 --- a/src/api/java/baritone/api/behavior/look/IAimProcessor.java +++ b/src/api/java/baritone/api/behavior/look/IAimProcessor.java @@ -25,20 +25,21 @@ public interface IAimProcessor { /** - * Returns the actual rotation that will be used when the desired rotation is requested. This is not guaranteed to - * return the same value for a given input. + * Returns the actual rotation that will be used when the desired rotation is requested. The returned rotation + * always reflects what would happen in the upcoming tick. In other words, it is a pure function, and no internal + * state changes. If simulation of the rotation states beyond the next tick is required, then a + * {@link IAimProcessor#fork fork} should be created. * * @param desired The desired rotation to set * @return The actual rotation */ - Rotation nextRotation(Rotation desired); + Rotation peekRotation(Rotation desired); /** - * Returns a copy of this {@link IAimProcessor} which has its own internal state and updates on each call to - * {@link #nextRotation(Rotation)}. + * Returns a copy of this {@link IAimProcessor} which has its own internal state and is manually tickable. * - * @param ticksAdvanced The number of ticks to advance ahead of time * @return The forked processor + * @see ITickableAimProcessor */ - IAimProcessor fork(int ticksAdvanced); + ITickableAimProcessor fork(); } diff --git a/src/api/java/baritone/api/behavior/look/ITickableAimProcessor.java b/src/api/java/baritone/api/behavior/look/ITickableAimProcessor.java new file mode 100644 index 000000000..e0a07ae57 --- /dev/null +++ b/src/api/java/baritone/api/behavior/look/ITickableAimProcessor.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.behavior.look; + +import baritone.api.utils.Rotation; + +/** + * @author Brady + */ +public interface ITickableAimProcessor extends IAimProcessor { + + /** + * Advances the internal state of this aim processor by a single tick. + */ + void tick(); + + /** + * Calls {@link #tick()} the specified number of times. + * + * @param ticks The number of calls + */ + void advance(int ticks); + + /** + * Returns the actual rotation as provided by {@link #peekRotation(Rotation)}, and then automatically advances the + * internal state by one {@link #tick() tick}. + * + * @param rotation The desired rotation to set + * @return The actual rotation + */ + Rotation nextRotation(Rotation rotation); +} diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 57dfd206c..4ea0274d7 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -21,6 +21,7 @@ import baritone.api.Settings; import baritone.api.behavior.ILookBehavior; import baritone.api.behavior.look.IAimProcessor; +import baritone.api.behavior.look.ITickableAimProcessor; import baritone.api.event.events.*; import baritone.api.utils.IPlayerContext; import baritone.api.utils.Rotation; @@ -68,7 +69,6 @@ public IAimProcessor getAimProcessor() { @Override public void onTick(TickEvent event) { if (event.getType() == TickEvent.Type.IN) { - // Unlike forked AimProcessors, the root one needs to be manually updated each game tick this.processor.tick(); } } @@ -88,7 +88,7 @@ public void onPlayerUpdate(PlayerUpdateEvent event) { this.prevRotation = new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch); } - final Rotation actual = this.processor.nextRotation(this.target.rotation); + final Rotation actual = this.processor.peekRotation(this.target.rotation); ctx.player().rotationYaw = actual.getYaw(); ctx.player().rotationPitch = actual.getPitch(); break; @@ -129,7 +129,7 @@ public void onWorldEvent(WorldEvent event) { public void pig() { if (this.target != null) { - final Rotation actual = this.processor.nextRotation(this.target.rotation); + final Rotation actual = this.processor.peekRotation(this.target.rotation); ctx.player().rotationYaw = actual.getYaw(); } } @@ -145,7 +145,7 @@ public Optional getEffectiveRotation() { @Override public void onPlayerRotationMove(RotationMoveEvent event) { if (this.target != null) { - final Rotation actual = this.processor.nextRotation(this.target.rotation); + final Rotation actual = this.processor.peekRotation(this.target.rotation); event.setYaw(actual.getYaw()); event.setPitch(actual.getPitch()); } @@ -164,7 +164,7 @@ protected Rotation getPrevRotation() { } } - private static abstract class AbstractAimProcessor implements IAimProcessor { + private static abstract class AbstractAimProcessor implements ITickableAimProcessor { protected final IPlayerContext ctx; private final ForkableRandom rand; @@ -183,13 +183,8 @@ private AbstractAimProcessor(final AbstractAimProcessor source) { this.randomPitchOffset = source.randomPitchOffset; } - public void tick() { - this.randomYawOffset = (this.rand.nextDouble() - 0.5) * Baritone.settings().randomLooking.value; - this.randomPitchOffset = (this.rand.nextDouble() - 0.5) * Baritone.settings().randomLooking.value; - } - @Override - public Rotation nextRotation(final Rotation rotation) { + public final Rotation peekRotation(final Rotation rotation) { final Rotation prev = this.getPrevRotation(); float desiredYaw = rotation.getYaw(); @@ -211,16 +206,34 @@ public Rotation nextRotation(final Rotation rotation) { } @Override - public final IAimProcessor fork(final int ticksAdvanced) { - final AbstractAimProcessor fork = new AbstractAimProcessor(this) { + public final void tick() { + this.randomYawOffset = (this.rand.nextDouble() - 0.5) * Baritone.settings().randomLooking.value; + this.randomPitchOffset = (this.rand.nextDouble() - 0.5) * Baritone.settings().randomLooking.value; + } + + @Override + public final void advance(int ticks) { + for (int i = 0; i < ticks; i++) { + this.tick(); + } + } + + @Override + public Rotation nextRotation(final Rotation rotation) { + final Rotation actual = this.peekRotation(rotation); + this.tick(); + return actual; + } + + @Override + public final ITickableAimProcessor fork() { + return new AbstractAimProcessor(this) { private Rotation prev = AbstractAimProcessor.this.getPrevRotation(); @Override - public Rotation nextRotation(Rotation rotation) { - final Rotation actual = super.nextRotation(rotation); - this.tick(); - return (this.prev = actual); + public Rotation nextRotation(final Rotation rotation) { + return (this.prev = super.nextRotation(rotation)); } @Override @@ -228,10 +241,6 @@ protected Rotation getPrevRotation() { return this.prev; } }; - for (int i = 0; i < ticksAdvanced; i++) { - fork.tick(); - } - return fork; } protected abstract Rotation getPrevRotation(); From c9a18caf492f6ccba6cb04223573e9aeb41da7cd Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 22 Jun 2023 20:38:00 -0500 Subject: [PATCH 107/111] Register `LookBehavior` first Since there's no event priority system, this is necessary to ensure anything else listening to the PRE `TickEvent` can accurately simulate rotations. --- src/main/java/baritone/Baritone.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 776e646af..957421970 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -101,8 +101,8 @@ public class Baritone implements IBaritone { this.playerContext = new BaritonePlayerContext(this, mc); { - this.pathingBehavior = this.registerBehavior(PathingBehavior::new); this.lookBehavior = this.registerBehavior(LookBehavior::new); + this.pathingBehavior = this.registerBehavior(PathingBehavior::new); this.inventoryBehavior = this.registerBehavior(InventoryBehavior::new); this.inputOverrideHandler = this.registerBehavior(InputOverrideHandler::new); this.registerBehavior(WaypointBehavior::new); From e3a1ac85cce9605f99f2d0db97f7a852ca768f30 Mon Sep 17 00:00:00 2001 From: ZacSharp <68165024+ZacSharp@users.noreply.github.com> Date: Fri, 23 Jun 2023 02:28:52 +0200 Subject: [PATCH 108/111] Fix waiting for impossible rotations --- src/api/java/baritone/api/utils/RotationUtils.java | 3 ++- src/main/java/baritone/pathing/movement/MovementHelper.java | 3 ++- src/main/java/baritone/process/BuilderProcess.java | 5 +++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index b3b67d9ca..9fc65df9f 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -217,7 +217,8 @@ public static Optional reachable(IPlayerContext ctx, BlockPos pos, dou public static Optional reachableOffset(IPlayerContext ctx, BlockPos pos, Vec3d offsetPos, double blockReachDistance, boolean wouldSneak) { Vec3d eyes = wouldSneak ? RayTraceUtils.inferSneakingEyePosition(ctx.player()) : ctx.player().getPositionEyes(1.0F); Rotation rotation = calcRotationFromVec3d(eyes, offsetPos, ctx.playerRotations()); - RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rotation, blockReachDistance, wouldSneak); + Rotation actualRotation = BaritoneAPI.getProvider().getBaritoneForPlayer(ctx.player()).getLookBehavior().getAimProcessor().peekRotation(rotation); + RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), actualRotation, blockReachDistance, wouldSneak); //System.out.println(result); if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { if (result.getBlockPos().equals(pos)) { diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index b14b2d69c..881bb6f15 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -684,7 +684,8 @@ static PlaceResult attemptToPlaceABlock(MovementState state, IBaritone baritone, double faceY = (placeAt.getY() + against1.getY() + 0.5D) * 0.5D; double faceZ = (placeAt.getZ() + against1.getZ() + 1.0D) * 0.5D; Rotation place = RotationUtils.calcRotationFromVec3d(wouldSneak ? RayTraceUtils.inferSneakingEyePosition(ctx.player()) : ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); - RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance(), wouldSneak); + Rotation actual = baritone.getLookBehavior().getAimProcessor().peekRotation(place); + RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), actual, ctx.playerController().getBlockReachDistance(), wouldSneak); if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(placeAt)) { state.setTarget(new MovementState.MovementTarget(place, true)); found = true; diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index bd14d09a7..60066971e 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -351,9 +351,10 @@ private Optional possibleToPlace(IBlockState toPlace, int x, int y, i double placeY = placeAgainstPos.y + aabb.minY * placementMultiplier.y + aabb.maxY * (1 - placementMultiplier.y); double placeZ = placeAgainstPos.z + aabb.minZ * placementMultiplier.z + aabb.maxZ * (1 - placementMultiplier.z); Rotation rot = RotationUtils.calcRotationFromVec3d(RayTraceUtils.inferSneakingEyePosition(ctx.player()), new Vec3d(placeX, placeY, placeZ), ctx.playerRotations()); - RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot, ctx.playerController().getBlockReachDistance(), true); + Rotation actualRot = baritone.getLookBehavior().getAimProcessor().peekRotation(rot); + RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), actualRot, ctx.playerController().getBlockReachDistance(), true); if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK && result.getBlockPos().equals(placeAgainstPos) && result.sideHit == against.getOpposite()) { - OptionalInt hotbar = hasAnyItemThatWouldPlace(toPlace, result, rot); + OptionalInt hotbar = hasAnyItemThatWouldPlace(toPlace, result, actualRot); if (hotbar.isPresent()) { return Optional.of(new Placement(hotbar.getAsInt(), placeAgainstPos, against.getOpposite(), rot)); } From 15f4253b3db96b8c31ef088f4c4f7305c5ed8b0a Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 24 Jun 2023 21:48:44 -0700 Subject: [PATCH 109/111] Clamp pitch to normal range --- src/main/java/baritone/behavior/LookBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 4ea0274d7..d438e8f85 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -202,7 +202,7 @@ public final Rotation peekRotation(final Rotation rotation) { return new Rotation( this.calculateMouseMove(prev.getYaw(), desiredYaw), this.calculateMouseMove(prev.getPitch(), desiredPitch) - ); + ).clamp(); } @Override From 8211ae4af58585ca3077c558c00b480d7d72ab59 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 29 Jun 2023 21:59:31 -0700 Subject: [PATCH 110/111] memory leaks are joever --- src/api/java/baritone/api/Settings.java | 7 +++++++ src/main/java/baritone/cache/CachedWorld.java | 3 +++ 2 files changed, 10 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 824dfd7e2..a8e4ced7d 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -622,6 +622,13 @@ public final class Settings { */ public final Setting pruneRegionsFromRAM = new Setting<>(true); + /** + * The chunk packer queue can never grow to larger than this, if it does, the oldest chunks are discarded + *

+ * The newest chunks are kept, so that if you're moving in a straight line quickly then stop, your immediate render distance is still included + */ + public final Setting chunkPackerQueueMaxSize = new Setting<>(2000); + /** * Fill in blocks behind you */ diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 6b3959fe3..32112f20f 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -307,6 +307,9 @@ public void run() { try { ChunkPos pos = toPackQueue.take(); Chunk chunk = toPackMap.remove(pos); + if (toPackQueue.size() > Baritone.settings().chunkPackerQueueMaxSize.value) { + continue; + } CachedChunk cached = ChunkPacker.pack(chunk); CachedWorld.this.updateCachedChunk(cached); //System.out.println("Processed chunk at " + chunk.x + "," + chunk.z); From 6654476da435203df9f5f42ed9f41310f5560c30 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 2 Jul 2023 19:59:26 -0500 Subject: [PATCH 111/111] Make `blockFreeLook` depend on `freeLook` --- src/api/java/baritone/api/Settings.java | 3 +-- src/main/java/baritone/behavior/LookBehavior.java | 6 +++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index a8e4ced7d..da241d6ba 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -731,8 +731,7 @@ public final class Settings { public final Setting freeLook = new Setting<>(true); /** - * Break and place blocks without having to force the client-sided rotations. Having this setting enabled implies - * {@link #freeLook}. + * Break and place blocks without having to force the client-sided rotations. Requires {@link #freeLook}. */ public final Setting blockFreeLook = new Setting<>(false); diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index d438e8f85..372cf1aae 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -135,10 +135,10 @@ public void pig() { } public Optional getEffectiveRotation() { - if (Baritone.settings().freeLook.value || Baritone.settings().blockFreeLook.value) { + if (Baritone.settings().freeLook.value) { return Optional.ofNullable(this.serverRotation); } - // If neither of the freeLook settings are on, just defer to the player's actual rotations + // If freeLook isn't on, just defer to the player's actual rotations return Optional.empty(); } @@ -306,7 +306,7 @@ static Mode resolve(boolean blockInteract) { final boolean blockFreeLook = settings.blockFreeLook.value; final boolean freeLook = settings.freeLook.value; - if (!freeLook && !blockFreeLook) return CLIENT; + if (!freeLook) return CLIENT; if (!blockFreeLook && blockInteract) return CLIENT; // Regardless of if antiCheatCompatibility is enabled, if a blockInteract is requested then the player