From 251110c4f89afaac13458471a8e036509ce52bcd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 25 Dec 2018 21:07:17 -0800 Subject: [PATCH 001/682] the start of something big --- src/main/java/baritone/Baritone.java | 11 +- .../baritone/behavior/PathingBehavior.java | 31 ++- .../pathing/movement/CalculationContext.java | 25 +- .../movement/movements/MovementAscend.java | 15 +- .../movement/movements/MovementDescend.java | 2 +- .../movement/movements/MovementParkour.java | 6 +- .../movement/movements/MovementPillar.java | 11 +- .../movement/movements/MovementTraverse.java | 9 +- .../java/baritone/process/BuilderProcess.java | 229 ++++++++++++++++++ .../utils/ExampleBaritoneControl.java | 5 + src/main/java/baritone/utils/ISchematic.java | 39 +++ .../baritone/utils/PathingCommandContext.java | 32 +++ .../baritone/utils/PathingControlManager.java | 10 +- 13 files changed, 380 insertions(+), 45 deletions(-) create mode 100644 src/main/java/baritone/process/BuilderProcess.java create mode 100644 src/main/java/baritone/utils/ISchematic.java create mode 100644 src/main/java/baritone/utils/PathingCommandContext.java diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 41fa36c5..358a4f2b 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -25,10 +25,7 @@ import baritone.api.utils.IPlayerContext; import baritone.behavior.*; import baritone.cache.WorldProvider; import baritone.event.GameEventHandler; -import baritone.process.CustomGoalProcess; -import baritone.process.FollowProcess; -import baritone.process.GetToBlockProcess; -import baritone.process.MineProcess; +import baritone.process.*; import baritone.utils.BaritoneAutoTest; import baritone.utils.ExampleBaritoneControl; import baritone.utils.InputOverrideHandler; @@ -83,6 +80,7 @@ public class Baritone implements IBaritone { private MineProcess mineProcess; private GetToBlockProcess getToBlockProcess; private CustomGoalProcess customGoalProcess; + private BuilderProcess builderProcess; private PathingControlManager pathingControlManager; @@ -118,6 +116,7 @@ public class Baritone implements IBaritone { mineProcess = new MineProcess(this); customGoalProcess = new CustomGoalProcess(this); // very high iq getToBlockProcess = new GetToBlockProcess(this); + builderProcess = new BuilderProcess(this); } this.worldProvider = new WorldProvider(); @@ -171,6 +170,10 @@ public class Baritone implements IBaritone { return this.followProcess; } + public BuilderProcess getBuilderProcess() { + return this.builderProcess; + } + @Override public LookBehavior getLookBehavior() { return this.lookBehavior; diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 6f0cf32b..a7509173 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -26,6 +26,7 @@ import baritone.api.event.events.TickEvent; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; +import baritone.api.process.PathingCommand; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.PathCalculationResult; import baritone.api.utils.interfaces.IGoalRenderPos; @@ -37,9 +38,9 @@ import baritone.pathing.path.CutoffPath; import baritone.pathing.path.PathExecutor; import baritone.utils.Helper; import baritone.utils.PathRenderer; +import baritone.utils.PathingCommandContext; import baritone.utils.pathing.Favoring; import net.minecraft.util.math.BlockPos; -import net.minecraft.world.chunk.EmptyChunk; import java.util.ArrayList; import java.util.Comparator; @@ -149,7 +150,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true); + findPathInNewThread(pathStart(), true, new CalculationContext(baritone, true)); } return; } @@ -184,7 +185,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // and this path has 5 seconds or less left logDebug("Path almost over. Planning ahead..."); queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED); - findPathInNewThread(current.getPath().getDest(), false); + findPathInNewThread(current.getPath().getDest(), false, new CalculationContext(baritone, true)); } } } @@ -219,9 +220,15 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, this.goal = goal; } - public boolean secretInternalSetGoalAndPath(Goal goal) { - secretInternalSetGoal(goal); - return secretInternalPath(); + public boolean secretInternalSetGoalAndPath(PathingCommand command) { + secretInternalSetGoal(command.goal); + CalculationContext context; + if (command instanceof PathingCommandContext) { + context = ((PathingCommandContext) command).desiredCalcContext; + } else { + context = new CalculationContext(baritone, true); + } + return secretInternalPath(context); } @Override @@ -315,7 +322,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * * @return true if this call started path calculation, false if it was already calculating or executing a path */ - public boolean secretInternalPath() { + private boolean secretInternalPath(CalculationContext context) { if (goal == null) { return false; } @@ -331,7 +338,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return false; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true); + findPathInNewThread(pathStart(), true, context); return true; } } @@ -394,7 +401,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * @param start * @param talkAboutIt */ - private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt) { + private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt, CalculationContext context) { // this must be called with synchronization on pathCalcLock! // actually, we can check this, muahaha if (!Thread.holdsLock(pathCalcLock)) { @@ -404,6 +411,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, if (inProgress != null) { throw new IllegalStateException("Already doing it"); // should have been checked by caller } + if (!context.safeForThreadedUse) { + throw new IllegalStateException("Improper context thread safety level"); + } Goal goal = this.goal; if (goal == null) { logDebug("no goal"); // TODO should this be an exception too? definitely should be checked by caller @@ -418,7 +428,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, primaryTimeout = Baritone.settings().planAheadPrimaryTimeoutMS.get(); failureTimeout = Baritone.settings().planAheadFailureTimeoutMS.get(); } - CalculationContext context = new CalculationContext(baritone, true); // not safe to create on the other thread, it looks up a lot of stuff in minecraft AbstractNodeCostSearch pathfinder = createPathfinder(start, goal, current == null ? null : current.getPath(), context); if (!Objects.equals(pathfinder.getGoal(), goal)) { // will return the exact same object if simplification didn't happen logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance"); @@ -499,7 +508,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, Goal transformed = goal; if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) { BlockPos pos = ((IGoalRenderPos) goal).getGoalPos(); - if (context.world.getChunk(pos) instanceof EmptyChunk) { + if (!context.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ())) { transformed = new GoalXZ(pos.getX(), pos.getZ()); } } diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 725ab569..66ed3d93 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -34,6 +34,8 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import static baritone.api.pathing.movement.ActionCosts.COST_INF; + /** * @author Brady * @since 8/7/2018 @@ -42,6 +44,7 @@ public class CalculationContext { private static final ItemStack STACK_BUCKET_WATER = new ItemStack(Items.WATER_BUCKET); + public final boolean safeForThreadedUse; public final IBaritone baritone; public final EntityPlayerSP player; public final World world; @@ -51,7 +54,7 @@ public class CalculationContext { public final boolean hasWaterBucket; public final boolean hasThrowaway; public final boolean canSprint; - public final double placeBlockCost; + protected final double placeBlockCost; // protected because you should call the function instead public final boolean allowBreak; public final boolean allowParkour; public final boolean allowParkourPlace; @@ -71,12 +74,12 @@ public class CalculationContext { } public CalculationContext(IBaritone baritone, boolean forUseOnAnotherThread) { + this.safeForThreadedUse = forUseOnAnotherThread; this.baritone = baritone; this.player = baritone.getPlayerContext().player(); this.world = baritone.getPlayerContext().world(); this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld(); - this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); // TODO TODO TODO - // new CalculationContext() needs to happen, can't add an argument (i'll beat you), can we get the world provider from currentlyTicking? + this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); this.toolSet = new ToolSet(player); this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(baritone.getPlayerContext(), false); this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether(); @@ -125,14 +128,18 @@ public class CalculationContext { return get(x, y, z).getBlock(); } - public boolean canPlaceThrowawayAt(int x, int y, int z) { + public double costOfPlacingAt(int x, int y, int z) { if (!hasThrowaway) { // only true if allowPlace is true, see constructor - return false; + return COST_INF; } if (isPossiblyProtected(x, y, z)) { - return false; + return COST_INF; } - return worldBorder.canPlaceAt(x, z); // TODO perhaps MovementHelper.canPlaceAgainst could also use this? + if (!worldBorder.canPlaceAt(x, z)) { + // TODO perhaps MovementHelper.canPlaceAgainst could also use this? + return COST_INF; + } + return placeBlockCost; } public boolean canBreakAt(int x, int y, int z) { @@ -142,6 +149,10 @@ public class CalculationContext { return !isPossiblyProtected(x, y, z); } + public double placeBucketCost() { + return placeBlockCost; // shrug + } + public boolean isPossiblyProtected(int x, int y, int z) { // TODO more protection logic here; see #220 return false; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 9973e94b..1faa5cf5 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -58,14 +58,16 @@ public class MovementAscend extends Movement { public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) { IBlockState toPlace = context.get(destX, y, destZ); - boolean hasToPlace = false; + double additionalPlacementCost = 0; if (!MovementHelper.canWalkOn(context.bsi, destX, y, destZ, toPlace)) { - if (!context.canPlaceThrowawayAt(destX, y, destZ)) { + additionalPlacementCost = context.costOfPlacingAt(destX, y, destZ); + if (additionalPlacementCost >= COST_INF) { return COST_INF; } if (!MovementHelper.isReplacable(destX, y, destZ, toPlace, context.bsi)) { return COST_INF; } + boolean foundPlaceOption = false; for (int i = 0; i < 5; i++) { int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); int againstY = y + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getYOffset(); @@ -74,11 +76,11 @@ public class MovementAscend extends Movement { continue; } if (MovementHelper.canPlaceAgainst(context.bsi, againstX, againstY, againstZ)) { - hasToPlace = true; + foundPlaceOption = true; break; } } - if (!hasToPlace) { // didn't find a valid place =( + if (!foundPlaceOption) { // didn't find a valid place =( return COST_INF; } } @@ -129,10 +131,7 @@ public class MovementAscend extends Movement { walk += context.jumpPenalty; } - double totalCost = walk; - if (hasToPlace) { - totalCost += context.placeBlockCost; - } + double totalCost = walk + additionalPlacementCost; // start with srcUp2 since we already have its state // includeFalling isn't needed because of the falling check above -- if srcUp3 is falling we will have already exited with COST_INF if we'd actually have to break it totalCost += MovementHelper.getMiningDurationTicks(context, x, y + 2, z, srcUp2, false); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index ba915ac6..800346a1 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -181,7 +181,7 @@ public class MovementDescend extends Movement { res.x = destX; res.y = newY + 1;// this is the block we're falling onto, so dest is +1 res.z = destZ; - res.cost = tentativeCost + context.placeBlockCost; + res.cost = tentativeCost + context.placeBucketCost(); return true; } if (unprotectedFallHeight <= context.maxFallHeightNoWater + 1) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 5bc5b1db..09bdd73a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -125,9 +125,11 @@ public class MovementParkour extends Movement { if (!context.allowParkourPlace) { return; } + // time 2 pop off with that dank skynet parkour place int destX = x + 4 * xDiff; int destZ = z + 4 * zDiff; - if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { + double placeCost = context.costOfPlacingAt(destX, y - 1, destZ); + if (placeCost >= COST_INF) { return; } IBlockState toReplace = context.get(destX, y - 1, destZ); @@ -145,7 +147,7 @@ public class MovementParkour extends Movement { res.x = destX; res.y = y; res.z = destZ; - res.cost = costFromJumpDistance(4) + context.placeBlockCost + context.jumpPenalty; + res.cost = costFromJumpDistance(4) + placeCost + context.jumpPenalty; return; } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index fafba24a..81303be7 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -73,8 +73,13 @@ public class MovementPillar extends Movement { return LADDER_UP_ONE_COST; // allow ascending pillars of water, but only if we're already in one } } - if (!ladder && !context.canPlaceThrowawayAt(x, y, z)) { // we need to place a block where we started to jump on it - return COST_INF; + double placeCost = 0; + if (!ladder) { + // we need to place a block where we started to jump on it + placeCost = context.costOfPlacingAt(x, y, z); + if (placeCost >= COST_INF) { + return COST_INF; + } } if (from instanceof BlockLiquid || (fromDown.getBlock() instanceof BlockLiquid && context.assumeWalkOnWater)) { // otherwise, if we're standing in water, we cannot pillar @@ -112,7 +117,7 @@ public class MovementPillar extends Movement { if (ladder) { return LADDER_UP_ONE_COST + hardness * 5; } else { - return JUMP_ONE_BLOCK_COST + context.placeBlockCost + context.jumpPenalty + hardness; + return JUMP_ONE_BLOCK_COST + placeCost + context.jumpPenalty + hardness; } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 84e42358..b2fd416b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -114,7 +114,8 @@ public class MovementTraverse extends Movement { // this happens when assume walk on water is true and this is a traverse in water, which isn't allowed return COST_INF; } - if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { + double placeCost = context.costOfPlacingAt(destX, y - 1, destZ); + if (placeCost >= COST_INF) { return COST_INF; } double hardness1 = MovementHelper.getMiningDurationTicks(context, destX, y, destZ, pb1, false); @@ -131,18 +132,18 @@ public class MovementTraverse extends Movement { continue; } if (MovementHelper.canPlaceAgainst(context.bsi, againstX, againstY, againstZ)) { // found a side place option - return WC + context.placeBlockCost + hardness1 + hardness2; + return WC + placeCost + hardness1 + hardness2; } } // now that we've checked all possible directions to side place, we actually need to backplace if (srcDown == Blocks.SOUL_SAND || (srcDown instanceof BlockSlab && !((BlockSlab) srcDown).isDouble())) { - return COST_INF; // can't sneak and backplace against soul sand or half slabs =/ + return COST_INF; // can't sneak and backplace against soul sand or half slabs (regardless of whether it's top half or bottom half) =/ } if (srcDown == Blocks.FLOWING_WATER || srcDown == Blocks.WATER) { return COST_INF; // this is obviously impossible } WC = WC * SNEAK_ONE_BLOCK_COST / WALK_ONE_BLOCK_COST;//since we are sneak backplacing, we are sneaking lol - return WC + context.placeBlockCost + hardness1 + hardness2; + return WC + placeCost + hardness1 + hardness2; } return COST_INF; } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java new file mode 100644 index 00000000..f01f7c04 --- /dev/null +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -0,0 +1,229 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.process; + +import baritone.Baritone; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalBlock; +import baritone.api.pathing.goals.GoalComposite; +import baritone.api.pathing.goals.GoalGetToBlock; +import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.api.utils.BetterBlockPos; +import baritone.pathing.movement.CalculationContext; +import baritone.utils.BaritoneProcessHelper; +import baritone.utils.BlockStateInterface; +import baritone.utils.ISchematic; +import baritone.utils.PathingCommandContext; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.Vec3i; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +import static baritone.api.pathing.movement.ActionCosts.COST_INF; + +public class BuilderProcess extends BaritoneProcessHelper { + public BuilderProcess(Baritone baritone) { + super(baritone); + } + + private HashSet incorrectPositions; + private String name; + private ISchematic schematic; + private Vec3i origin; + + public boolean build(String schematicFile) { + File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); + NBTTagCompound tag; + try { + tag = CompressedStreamTools.read(file); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + if (tag == null) { + return false; + } + name = schematicFile; + schematic = parse(tag); + origin = ctx.playerFeet(); + return true; + } + + private static ISchematic parse(NBTTagCompound schematic) { + throw new UnsupportedOperationException("would rather die than parse " + schematic); + } + + @Override + public boolean isActive() { + return schematic != null; + } + + @Override + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + // TODO somehow tell inventorybehavior what we'd like to have on the hotbar + // perhaps take the 16 closest positions in incorrectPositions to ctx.playerFeet that aren't desired to be air, and then snag the top 4 most common block states, then request those on the hotbar + + + // this will work as is, but it'll be trashy + // need to iterate over incorrectPositions and see which ones we can "correct" from our current standing position + + // considerations: + // shouldn't break blocks that are supporting our current path segment, maybe? + // + return new PathingCommandContext(new GoalComposite(assemble()), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, new BuilderCalculationContext(schematic, origin)); + } + + private Goal[] assemble() { + BlockStateInterface bsi = new CalculationContext(baritone).bsi; + return incorrectPositions.stream().map(pos -> + bsi.get0(pos).getBlock() == Blocks.AIR ? + // it's air and it shouldn't be + new GoalBlock(pos.up()) + // it's a block and it shouldn't be + : new GoalGetToBlock(pos) // replace with GoalTwoBlocks to mine using pathfinding system only + ).toArray(Goal[]::new); + } + + @Override + public void onLostControl() { + incorrectPositions = null; + name = null; + schematic = null; + } + + @Override + public String displayName() { + return "Building " + name; + } + + /** + * Hotbar contents, if they were placed + *

+ * Always length nine, empty slots become Blocks.AIR.getDefaultState() + * + * @return + */ + public List placable() { + List result = new ArrayList<>(); + for (int i = 0; i < 9; i++) { + ItemStack stack = ctx.player().inventory.mainInventory.get(i); + if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) { + result.add(Blocks.AIR.getDefaultState()); + continue; + } + // + result.add(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(ctx.world(), ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ, stack.getItem().getMetadata(stack.getMetadata()), ctx.player())); + // + } + return result; + } + + public class BuilderCalculationContext extends CalculationContext { + private final List placable; + private final ISchematic schematic; + private final int originX; + private final int originY; + private final int originZ; + + public BuilderCalculationContext(ISchematic schematic, Vec3i schematicOrigin) { + super(BuilderProcess.this.baritone, true); // wew lad + this.placable = placable(); + this.schematic = schematic; + this.originX = schematicOrigin.getX(); + this.originY = schematicOrigin.getY(); + this.originZ = schematicOrigin.getZ(); + } + + private IBlockState getSchematic(int x, int y, int z) { + if (schematic.inSchematic(x - originX, y - originY, z - originZ)) { + return schematic.desiredState(x - originX, y - originY, z - originZ); + } else { + return null; + } + } + + @Override + public double costOfPlacingAt(int x, int y, int z) { + if (isPossiblyProtected(x, y, z) || !worldBorder.canPlaceAt(x, z)) { // make calculation fail properly if we can't build + return COST_INF; + } + IBlockState sch = getSchematic(x, y, z); + if (sch != null) { + // TODO this can return true even when allowPlace is off.... is that an issue? + if (placable.contains(sch)) { + return 0; // thats right we gonna make it FREE to place a block where it should go in a structure + // no place block penalty at all 😎 + // i'm such an idiot that i just tried to copy and paste the epic gamer moment emoji too + // get added to unicode when? + } + if (!hasThrowaway) { + return COST_INF; + } + if (sch.getBlock() == Blocks.AIR) { + // we want this to be air, but they're asking if they can place here + // this won't be a schematic block, this will be a throwaway + return placeBlockCost * 2; // we're going to have to break it eventually + } else { + // we want it to be something that we don't have + // even more of a pain to place something wrong + return placeBlockCost * 3; + } + } else { + if (hasThrowaway) { + return placeBlockCost; + } else { + return COST_INF; + } + } + } + + @Override + public boolean canBreakAt(int x, int y, int z) { + if (!allowBreak || isPossiblyProtected(x, y, z)) { + return false; + } + IBlockState sch = getSchematic(x, y, z); + if (sch != null) { + if (sch.getBlock() == Blocks.AIR) { + // it should be air + // regardless of current contents, we can break it + return true; + } + // it should be a real block + // is it already that block? + return !bsi.get0(x, y, z).equals(sch); // can break if it's wrong + // TODO do blocks in render distace only? + // TODO allow breaking blocks that we have a tool to harvest and immediately place back? + } else { + return true; // why not lol + } + } + } +} diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 508a5e1b..53b93aab 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -239,6 +239,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Queued " + count + " chunks for repacking"); return true; } + if (msg.startsWith("build")) { + String file = msg.substring(5) + ".schematic"; + logDirect("" + baritone.getBuilderProcess().build(file)); + return true; + } if (msg.equals("axis")) { customGoalProcess.setGoalAndPath(new GoalAxis()); return true; diff --git a/src/main/java/baritone/utils/ISchematic.java b/src/main/java/baritone/utils/ISchematic.java new file mode 100644 index 00000000..db494c29 --- /dev/null +++ b/src/main/java/baritone/utils/ISchematic.java @@ -0,0 +1,39 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import net.minecraft.block.state.IBlockState; + +public interface ISchematic { + /** + * Does the block at this coordinate matter to the schematic? + *

+ * Normally just a check for if the coordinate is in the cube. + *

+ * However, in the case of something like a map art, anything that's below the level of the map art doesn't matter, + * so this function should return false in that case. (i.e. it doesn't really have to be air below the art blocks) + * + * @param x + * @param y + * @param z + * @return + */ + boolean inSchematic(int x, int y, int z); + + IBlockState desiredState(int x, int y, int z); +} \ No newline at end of file diff --git a/src/main/java/baritone/utils/PathingCommandContext.java b/src/main/java/baritone/utils/PathingCommandContext.java new file mode 100644 index 00000000..1e8bfe6a --- /dev/null +++ b/src/main/java/baritone/utils/PathingCommandContext.java @@ -0,0 +1,32 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import baritone.api.pathing.goals.Goal; +import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.pathing.movement.CalculationContext; + +public class PathingCommandContext extends PathingCommand { + public final CalculationContext desiredCalcContext; + + public PathingCommandContext(Goal goal, PathingCommandType commandType, CalculationContext context) { + super(goal, commandType); + this.desiredCalcContext = context; + } +} diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index f5fff546..97685ac0 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -98,18 +98,18 @@ public class PathingControlManager implements IPathingControlManager { break; case FORCE_REVALIDATE_GOAL_AND_PATH: if (!p.isPathing() && !p.getInProgress().isPresent()) { - p.secretInternalSetGoalAndPath(command.goal); + p.secretInternalSetGoalAndPath(command); } break; case REVALIDATE_GOAL_AND_PATH: if (!p.isPathing() && !p.getInProgress().isPresent()) { - p.secretInternalSetGoalAndPath(command.goal); + p.secretInternalSetGoalAndPath(command); } break; case SET_GOAL_AND_PATH: // now this i can do if (command.goal != null) { - baritone.getPathingBehavior().secretInternalSetGoalAndPath(command.goal); + baritone.getPathingBehavior().secretInternalSetGoalAndPath(command); } break; default: @@ -132,13 +132,13 @@ public class PathingControlManager implements IPathingControlManager { // pwnage p.softCancelIfSafe(); } - p.secretInternalSetGoalAndPath(command.goal); + p.secretInternalSetGoalAndPath(command); break; case REVALIDATE_GOAL_AND_PATH: if (Baritone.settings().cancelOnGoalInvalidation.get() && (command.goal == null || revalidateGoal(command.goal))) { p.softCancelIfSafe(); } - p.secretInternalSetGoalAndPath(command.goal); + p.secretInternalSetGoalAndPath(command); break; default: } From c45cbebcce4f8ad12cd37a898af72fc10424aa68 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 27 Dec 2018 08:06:10 -1000 Subject: [PATCH 002/682] fixed --- src/main/java/baritone/process/BuilderProcess.java | 8 ++++++-- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index f01f7c04..8bb966ea 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -41,6 +41,7 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.Vec3i; import java.io.File; +import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; @@ -60,9 +61,11 @@ public class BuilderProcess extends BaritoneProcessHelper { public boolean build(String schematicFile) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); + System.out.println(file + " " + file.exists()); + NBTTagCompound tag; - try { - tag = CompressedStreamTools.read(file); + try (FileInputStream fileIn = new FileInputStream(file)) { + tag = CompressedStreamTools.readCompressed(fileIn); } catch (IOException e) { e.printStackTrace(); return false; @@ -107,6 +110,7 @@ public class BuilderProcess extends BaritoneProcessHelper { // it's air and it shouldn't be new GoalBlock(pos.up()) // it's a block and it shouldn't be + // todo disallow right above : new GoalGetToBlock(pos) // replace with GoalTwoBlocks to mine using pathfinding system only ).toArray(Goal[]::new); } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 53b93aab..55009575 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -240,7 +240,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.startsWith("build")) { - String file = msg.substring(5) + ".schematic"; + String file = msg.substring(6) + ".schematic"; logDirect("" + baritone.getBuilderProcess().build(file)); return true; } From 702b9169485010daec4b8581750595aa06f6c0b6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 8 Jan 2019 20:45:02 -0800 Subject: [PATCH 003/682] preliminary schematic stuff --- .../api/pathing/goals/GoalGetToBlock.java | 6 +- .../baritone/behavior/PathingBehavior.java | 9 +- .../pathing/movement/CalculationContext.java | 9 +- .../pathing/movement/MovementHelper.java | 4 +- .../movement/movements/MovementAscend.java | 6 + .../movement/movements/MovementPillar.java | 4 +- .../java/baritone/process/BuilderProcess.java | 200 +++++++++++++++--- src/main/java/baritone/utils/ISchematic.java | 6 + .../java/baritone/utils/MapArtSchematic.java | 52 +++++ src/main/java/baritone/utils/Schematic.java | 93 ++++++++ 10 files changed, 346 insertions(+), 43 deletions(-) create mode 100644 src/main/java/baritone/utils/MapArtSchematic.java create mode 100644 src/main/java/baritone/utils/Schematic.java diff --git a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java index c4856cdd..fb2a07aa 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java @@ -28,9 +28,9 @@ import net.minecraft.util.math.BlockPos; */ public class GoalGetToBlock implements Goal, IGoalRenderPos { - private final int x; - private final int y; - private final int z; + public final int x; + public final int y; + public final int z; public GoalGetToBlock(BlockPos pos) { this.x = pos.getX(); diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index a7509173..06020598 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -57,6 +57,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private boolean safeToCancel; private boolean pauseRequestedLastTick; + private boolean unpausedLastTick; private boolean cancelRequested; private boolean calcFailedLastTick; @@ -102,10 +103,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private void tickPath() { if (pauseRequestedLastTick && safeToCancel) { pauseRequestedLastTick = false; - baritone.getInputOverrideHandler().clearAllKeys(); - baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); + if (unpausedLastTick) { + baritone.getInputOverrideHandler().clearAllKeys(); + baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); + } + unpausedLastTick = false; return; } + unpausedLastTick = true; if (cancelRequested) { cancelRequested = false; baritone.getInputOverrideHandler().clearAllKeys(); diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 66ed3d93..4611d975 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -142,11 +142,14 @@ public class CalculationContext { return placeBlockCost; } - public boolean canBreakAt(int x, int y, int z) { + public double breakCostMultiplierAt(int x, int y, int z) { if (!allowBreak) { - return false; + return COST_INF; } - return !isPossiblyProtected(x, y, z); + if (isPossiblyProtected(x, y, z)) { + return COST_INF; + } + return 1; } public double placeBucketCost() { diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index d07f05e7..96c4a769 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -341,7 +341,8 @@ public interface MovementHelper extends ActionCosts, Helper { static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) { Block block = state.getBlock(); if (!canWalkThrough(context.bsi, x, y, z, state)) { - if (!context.canBreakAt(x, y, z)) { + double mult = context.breakCostMultiplierAt(x, y, z); + if (mult >= COST_INF) { return COST_INF; } if (avoidBreaking(context.bsi, x, y, z, state)) { @@ -358,6 +359,7 @@ public interface MovementHelper extends ActionCosts, Helper { double result = m / strVsBlock; result += context.breakBlockAdditionalCost; + result *= mult; if (includeFalling) { IBlockState above = context.get(x, y + 1, z); if (above.getBlock() instanceof BlockFalling) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 7da7ad15..5fafdeed 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -240,4 +240,10 @@ public class MovementAscend extends Movement { } return true; } + + @Override + public boolean safeToCancel(MovementState state) { + // if we had to place, don't allow pause + return state.getStatus() != MovementStatus.RUNNING || ticksWithoutPlacement == 0; + } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index dd93eeed..18a248c1 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -35,6 +35,8 @@ import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; +import java.util.Objects; + public class MovementPillar extends Movement { public MovementPillar(IBaritone baritone, BetterBlockPos start, BetterBlockPos end) { @@ -229,7 +231,7 @@ public class MovementPillar extends Movement { if (!(fr instanceof BlockAir || fr.isReplaceable(ctx.world(), src))) { state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; - } else if (ctx.player().isSneaking()) { // 1 tick after we're able to place + } else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos()))) { // 1 tick after we're able to place state.setInput(Input.CLICK_RIGHT, true); } } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 8bb966ea..27142120 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -25,11 +25,15 @@ import baritone.api.pathing.goals.GoalGetToBlock; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Rotation; +import baritone.api.utils.RotationUtils; +import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; +import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; -import baritone.utils.BlockStateInterface; import baritone.utils.ISchematic; import baritone.utils.PathingCommandContext; +import baritone.utils.Schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; @@ -38,14 +42,15 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; +import net.minecraft.util.Tuple; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; +import java.util.*; +import java.util.stream.Collectors; import static baritone.api.pathing.movement.ActionCosts.COST_INF; @@ -80,7 +85,7 @@ public class BuilderProcess extends BaritoneProcessHelper { } private static ISchematic parse(NBTTagCompound schematic) { - throw new UnsupportedOperationException("would rather die than parse " + schematic); + return new Schematic(schematic); } @Override @@ -88,6 +93,32 @@ public class BuilderProcess extends BaritoneProcessHelper { return schematic != null; } + public Optional> toBreakNearPlayer(BuilderCalculationContext bcc) { + BetterBlockPos center = ctx.playerFeet(); + for (int dx = -5; dx <= 5; dx++) { + for (int dy = 0; dy <= 5; dy++) { + for (int dz = -5; dz <= 5; dz++) { + int x = center.x + dx; + int y = center.y + dy; + int z = center.z + dz; + IBlockState desired = bcc.getSchematic(x, y, z); + if (desired == null) { + continue; // irrelevant + } + IBlockState curr = bcc.bsi.get0(x, y, z); + if (curr.getBlock() != Blocks.AIR && !valid(curr, desired)) { + BetterBlockPos pos = new BetterBlockPos(x, y, z); + Optional rot = RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()); + if (rot.isPresent()) { + return Optional.of(new Tuple<>(pos, rot.get())); + } + } + } + } + } + return Optional.empty(); + } + @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { // TODO somehow tell inventorybehavior what we'd like to have on the hotbar @@ -97,22 +128,113 @@ public class BuilderProcess extends BaritoneProcessHelper { // this will work as is, but it'll be trashy // need to iterate over incorrectPositions and see which ones we can "correct" from our current standing position - // considerations: - // shouldn't break blocks that are supporting our current path segment, maybe? - // - return new PathingCommandContext(new GoalComposite(assemble()), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, new BuilderCalculationContext(schematic, origin)); + + BuilderCalculationContext bcc = new BuilderCalculationContext(schematic, origin); + if (!recalc(bcc)) { + logDirect("Done building"); + onLostControl(); + return null; + } + Optional> toBreak = toBreakNearPlayer(bcc); + baritone.getInputOverrideHandler().clearAllKeys(); + if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) { + // we'd like to pause to break this block + // only change look direction if it's safe (don't want to fuck up an in progress parkour for example + Rotation rot = toBreak.get().getSecond(); + BetterBlockPos pos = toBreak.get().getFirst(); + baritone.getLookBehavior().updateTarget(rot, true); + MovementHelper.switchToBestToolFor(ctx, bcc.get(pos)); + if (Objects.equals(ctx.objectMouseOver().getBlockPos(), rot) || ctx.playerRotations().isReallyCloseTo(rot)) { + baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); + } + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + + Goal[] goals = assemble(bcc); + if (goals.length == 0) { + logDirect("Unable to do it =("); + onLostControl(); + return null; + } + return new PathingCommandContext(new GoalComposite(goals), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc); } - private Goal[] assemble() { - BlockStateInterface bsi = new CalculationContext(baritone).bsi; - return incorrectPositions.stream().map(pos -> - bsi.get0(pos).getBlock() == Blocks.AIR ? - // it's air and it shouldn't be - new GoalBlock(pos.up()) - // it's a block and it shouldn't be - // todo disallow right above - : new GoalGetToBlock(pos) // replace with GoalTwoBlocks to mine using pathfinding system only - ).toArray(Goal[]::new); + public boolean recalc(BuilderCalculationContext bcc) { + if (incorrectPositions == null) { + incorrectPositions = new HashSet<>(); + fullRecalc(bcc); + if (incorrectPositions.isEmpty()) { + return false; + } + } + recalcNearby(bcc); + if (incorrectPositions.isEmpty()) { + fullRecalc(bcc); + } + return !incorrectPositions.isEmpty(); + } + + public void recalcNearby(BuilderCalculationContext bcc) { + BetterBlockPos center = ctx.playerFeet(); + for (int dx = -5; dx <= 5; dx++) { + for (int dy = -5; dy <= 5; dy++) { + for (int dz = -5; dz <= 5; dz++) { + int x = center.x + dx; + int y = center.y + dy; + int z = center.z + dz; + IBlockState desired = bcc.getSchematic(x, y, z); + if (desired != null) { + // we care about this position + if (valid(bcc.bsi.get0(x, y, z), desired)) { + incorrectPositions.remove(new BetterBlockPos(x, y, z)); + } else { + incorrectPositions.add(new BetterBlockPos(x, y, z)); + } + } + } + } + } + } + + public void fullRecalc(BuilderCalculationContext bcc) { + incorrectPositions = new HashSet<>(); + for (int y = 0; y < schematic.heightY(); y++) { + for (int z = 0; z < schematic.lengthZ(); z++) { + for (int x = 0; x < schematic.widthX(); x++) { + if (schematic.inSchematic(x, y, z)) { + if (!valid(bcc.bsi.get0(x + origin.getX(), y + origin.getY(), z + origin.getZ()), schematic.desiredState(x, y, z))) { + incorrectPositions.add(new BetterBlockPos(x + origin.getX(), y + origin.getY(), z + origin.getZ())); + } + } + } + } + } + } + + private Goal[] assemble(BuilderCalculationContext bcc) { + List approxPlacable = placable(); + List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); + if (!placable.isEmpty()) { + return placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(BetterBlockPos::up).map(GoalBlock::new).toArray(Goal[]::new); + } + return incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); + } + + public static class GoalBreak extends GoalGetToBlock { + + public GoalBreak(BlockPos pos) { + super(pos); + } + + @Override + public boolean isInGoal(int x, int y, int z) { + // can't stand right on top of a block, that might not work (what if it's unsupported, can't break then) + if (x == this.x && y == this.y + 1 && z == this.z) { + return false; + } + // but any other adjacent works for breaking, including inside or below + return super.isInGoal(x, y, z); + } } @Override @@ -149,6 +271,11 @@ public class BuilderProcess extends BaritoneProcessHelper { return result; } + public boolean valid(IBlockState current, IBlockState desired) { + // TODO more complicated comparison logic I guess + return desired == null || current.equals(desired); + } + public class BuilderCalculationContext extends CalculationContext { private final List placable; private final ISchematic schematic; @@ -181,6 +308,11 @@ public class BuilderProcess extends BaritoneProcessHelper { IBlockState sch = getSchematic(x, y, z); if (sch != null) { // TODO this can return true even when allowPlace is off.... is that an issue? + if (sch.getBlock() == Blocks.AIR) { + // we want this to be air, but they're asking if they can place here + // this won't be a schematic block, this will be a throwaway + return placeBlockCost * 2; // we're going to have to break it eventually + } if (placable.contains(sch)) { return 0; // thats right we gonna make it FREE to place a block where it should go in a structure // no place block penalty at all 😎 @@ -190,15 +322,9 @@ public class BuilderProcess extends BaritoneProcessHelper { if (!hasThrowaway) { return COST_INF; } - if (sch.getBlock() == Blocks.AIR) { - // we want this to be air, but they're asking if they can place here - // this won't be a schematic block, this will be a throwaway - return placeBlockCost * 2; // we're going to have to break it eventually - } else { - // we want it to be something that we don't have - // even more of a pain to place something wrong - return placeBlockCost * 3; - } + // we want it to be something that we don't have + // even more of a pain to place something wrong + return placeBlockCost * 3; } else { if (hasThrowaway) { return placeBlockCost; @@ -209,24 +335,32 @@ public class BuilderProcess extends BaritoneProcessHelper { } @Override - public boolean canBreakAt(int x, int y, int z) { + public double breakCostMultiplierAt(int x, int y, int z) { if (!allowBreak || isPossiblyProtected(x, y, z)) { - return false; + return COST_INF; } IBlockState sch = getSchematic(x, y, z); if (sch != null) { if (sch.getBlock() == Blocks.AIR) { // it should be air // regardless of current contents, we can break it - return true; + return 1; } // it should be a real block // is it already that block? - return !bsi.get0(x, y, z).equals(sch); // can break if it's wrong + if (valid(bsi.get0(x, y, z), sch)) { + return 3; + } else { + // can break if it's wrong + // would be great to return less than 1 here, but that would actually make the cost calculation messed up + // since we're breaking a block, if we underestimate the cost, then it'll fail when it really takes the correct amount of time + return 1; + + } // TODO do blocks in render distace only? // TODO allow breaking blocks that we have a tool to harvest and immediately place back? } else { - return true; // why not lol + return 1; // why not lol } } } diff --git a/src/main/java/baritone/utils/ISchematic.java b/src/main/java/baritone/utils/ISchematic.java index db494c29..b68f1a1c 100644 --- a/src/main/java/baritone/utils/ISchematic.java +++ b/src/main/java/baritone/utils/ISchematic.java @@ -36,4 +36,10 @@ public interface ISchematic { boolean inSchematic(int x, int y, int z); IBlockState desiredState(int x, int y, int z); + + int widthX(); + + int heightY(); + + int lengthZ(); } \ No newline at end of file diff --git a/src/main/java/baritone/utils/MapArtSchematic.java b/src/main/java/baritone/utils/MapArtSchematic.java new file mode 100644 index 00000000..9813b637 --- /dev/null +++ b/src/main/java/baritone/utils/MapArtSchematic.java @@ -0,0 +1,52 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.nbt.NBTTagCompound; + +public class MapArtSchematic extends Schematic { + private final int[][] heightMap; + + public MapArtSchematic(NBTTagCompound schematic) { + super(schematic); + heightMap = new int[widthX][lengthZ]; + for (int x = 0; x < widthX; x++) { + https: + for (int z = 0; z < lengthZ; z++) { + IBlockState[] column = states[x][z]; + for (int y = heightY - 1; y >= 0; y--) { + if (column[y].getBlock() != Blocks.AIR) { + heightMap[x][z] = y; + continue https; + } + } + System.out.println("Column " + x + "," + z + " has no blocks, but it's apparently map art? wtf"); + System.out.println("Letting it be whatever"); + heightMap[x][z] = 256; + } + } + } + + @Override + public boolean inSchematic(int x, int y, int z) { + // in map art, we only care about coordinates in or above the art + return super.inSchematic(x, y, z) && y >= heightMap[x][z]; + } +} diff --git a/src/main/java/baritone/utils/Schematic.java b/src/main/java/baritone/utils/Schematic.java new file mode 100644 index 00000000..dbc80a73 --- /dev/null +++ b/src/main/java/baritone/utils/Schematic.java @@ -0,0 +1,93 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.nbt.NBTTagCompound; + +public class Schematic implements ISchematic { + public final int widthX; + public final int heightY; + public final int lengthZ; + protected final IBlockState[][][] states; + + public Schematic(NBTTagCompound schematic) { + String type = schematic.getString("Materials"); + if (!type.equals("Alpha")) { + throw new IllegalStateException("bad schematic " + type); + } + widthX = schematic.getInteger("Width"); + heightY = schematic.getInteger("Height"); + lengthZ = schematic.getInteger("Length"); + byte[] blocks = schematic.getByteArray("Blocks"); + byte[] metadata = schematic.getByteArray("Data"); + + byte[] additional = null; + if (schematic.hasKey("AddBlocks")) { + byte[] addBlocks = schematic.getByteArray("AddBlocks"); + additional = new byte[addBlocks.length * 2]; + for (int i = 0; i < addBlocks.length; i++) { + additional[i * 2 + 0] = (byte) ((addBlocks[i] >> 4) & 0xF); // lower nibble + additional[i * 2 + 1] = (byte) ((addBlocks[i] >> 0) & 0xF); // upper nibble + } + } + states = new IBlockState[widthX][lengthZ][heightY]; + for (int y = 0; y < heightY; y++) { + for (int z = 0; z < lengthZ; z++) { + for (int x = 0; x < widthX; x++) { + int blockInd = (y * lengthZ + z) * widthX + x; + + int blockID = blocks[blockInd] & 0xFF; + if (additional != null) { + // additional is 0 through 15 inclusive since it's & 0xF above + blockID |= additional[blockInd] << 8; + } + Block block = Block.REGISTRY.getObjectById(blockID); + int meta = metadata[blockInd] & 0xFF; + states[x][z][y] = block.getStateFromMeta(meta); + } + } + } + } + + @Override + public boolean inSchematic(int x, int y, int z) { + return x >= 0 && x < widthX && y >= 0 && y < heightY && z >= 0 && z < lengthZ; + } + + @Override + public IBlockState desiredState(int x, int y, int z) { + return states[x][z][y]; + } + + @Override + public int widthX() { + return widthX; + } + + @Override + public int heightY() { + return heightY; + } + + @Override + public int lengthZ() { + return lengthZ; + } +} From c74c01271d54a48c52826c0be7361c40c0cc7ff8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 9 Jan 2019 14:36:44 -0800 Subject: [PATCH 004/682] better strategy --- .../baritone/api/pathing/goals/GoalBlock.java | 6 +++--- .../pathing/movement/CalculationContext.java | 2 +- .../movement/movements/MovementTraverse.java | 14 ++++++++++++-- .../java/baritone/process/BuilderProcess.java | 17 +++++++++++++++-- 4 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalBlock.java b/src/api/java/baritone/api/pathing/goals/GoalBlock.java index e0a60b59..89dd6304 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalBlock.java @@ -30,17 +30,17 @@ public class GoalBlock implements Goal, IGoalRenderPos { /** * The X block position of this goal */ - private final int x; + public final int x; /** * The Y block position of this goal */ - private final int y; + public final int y; /** * The Z block position of this goal */ - private final int z; + public final int z; public GoalBlock(BlockPos pos) { this(pos.getX(), pos.getY(), pos.getZ()); diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 4611d975..95887efd 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -65,7 +65,7 @@ public class CalculationContext { public final int maxFallHeightBucket; public final double waterWalkSpeed; public final double breakBlockAdditionalCost; - public final double jumpPenalty; + public double jumpPenalty; public final double walkOnWaterOnePenalty; public final BetterWorldBorder worldBorder; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 9f7c0fdf..57bc333c 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -275,14 +275,24 @@ public class MovementTraverse extends Movement { double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + against1.getY()) * 0.5D; double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true)); + Rotation rot = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); + state.setTarget(new MovementState.MovementTarget(rot, true)); EnumFacing side = ctx.objectMouseOver().sideHit; if (Objects.equals(ctx.getSelectedBlock().orElse(null), against1) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && ctx.getSelectedBlock().get().offset(side).equals(positionToPlace)) { return state.setInput(Input.CLICK_RIGHT, true); } + if (ctx.playerRotations().isReallyCloseTo(rot)) { + double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); + if (dist > 0.83) { + // might need to go forward a bit + return state.setInput(Input.MOVE_FORWARD, true); + } + // don't left click for one tick + return state.setInput(Input.CLICK_LEFT, true); + } + return state; //System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); - return state.setInput(Input.CLICK_LEFT, true); } } if (!Baritone.settings().assumeSafeWalk.get()) { diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 27142120..b4b13725 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -215,7 +215,7 @@ public class BuilderProcess extends BaritoneProcessHelper { List approxPlacable = placable(); List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); if (!placable.isEmpty()) { - return placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(BetterBlockPos::up).map(GoalBlock::new).toArray(Goal[]::new); + return placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(GoalPlace::new).toArray(Goal[]::new); } return incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); } @@ -229,7 +229,7 @@ public class BuilderProcess extends BaritoneProcessHelper { @Override public boolean isInGoal(int x, int y, int z) { // can't stand right on top of a block, that might not work (what if it's unsupported, can't break then) - if (x == this.x && y == this.y + 1 && z == this.z) { + if (y > this.y) { return false; } // but any other adjacent works for breaking, including inside or below @@ -237,6 +237,17 @@ public class BuilderProcess extends BaritoneProcessHelper { } } + public static class GoalPlace extends GoalBlock { + public GoalPlace(BlockPos placeAt) { + super(placeAt.up()); + } + + public double heuristic(int x, int y, int z) { + // prioritize lower y coordinates + return this.y * 100 + super.heuristic(x, y, z); + } + } + @Override public void onLostControl() { incorrectPositions = null; @@ -290,6 +301,8 @@ public class BuilderProcess extends BaritoneProcessHelper { this.originX = schematicOrigin.getX(); this.originY = schematicOrigin.getY(); this.originZ = schematicOrigin.getZ(); + + this.jumpPenalty += 10; } private IBlockState getSchematic(int x, int y, int z) { From b109fc742093ccb9e2a1bf05afa9de7ce9fbef03 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 9 Jan 2019 15:07:06 -0800 Subject: [PATCH 005/682] fun =) --- .../movement/movements/MovementTraverse.java | 2 +- .../java/baritone/process/BuilderProcess.java | 41 +++++++++++++++---- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 57bc333c..1c5c4f2e 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -279,7 +279,7 @@ public class MovementTraverse extends Movement { state.setTarget(new MovementState.MovementTarget(rot, true)); EnumFacing side = ctx.objectMouseOver().sideHit; - if (Objects.equals(ctx.getSelectedBlock().orElse(null), against1) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && ctx.getSelectedBlock().get().offset(side).equals(positionToPlace)) { + if ((Objects.equals(ctx.getSelectedBlock(), dest.down()) || (Objects.equals(ctx.getSelectedBlock().orElse(null), against1) && ctx.getSelectedBlock().get().offset(side).equals(positionToPlace))) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get())) { return state.setInput(Input.CLICK_RIGHT, true); } if (ctx.playerRotations().isReallyCloseTo(rot)) { diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index b4b13725..e64a6627 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -150,13 +150,13 @@ public class BuilderProcess extends BaritoneProcessHelper { return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } - Goal[] goals = assemble(bcc); - if (goals.length == 0) { + Goal goal = assemble(bcc); + if (goal == null) { logDirect("Unable to do it =("); onLostControl(); return null; } - return new PathingCommandContext(new GoalComposite(goals), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc); + return new PathingCommandContext(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc); } public boolean recalc(BuilderCalculationContext bcc) { @@ -211,13 +211,40 @@ public class BuilderProcess extends BaritoneProcessHelper { } } - private Goal[] assemble(BuilderCalculationContext bcc) { + private Goal assemble(BuilderCalculationContext bcc) { List approxPlacable = placable(); List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); - if (!placable.isEmpty()) { - return placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(GoalPlace::new).toArray(Goal[]::new); + Goal[] toBreak = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); + Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(GoalPlace::new).toArray(Goal[]::new); + + if (toPlace.length != 0) { + return new JankyGoalComposite(new GoalComposite(toPlace), new GoalComposite(toBreak)); + } + if (toBreak.length == 0) { + return null; + } + return new GoalComposite(toBreak); + } + + public static class JankyGoalComposite implements Goal { + private final Goal primary; + private final Goal fallback; + + public JankyGoalComposite(Goal primary, Goal fallback) { + this.primary = primary; + this.fallback = fallback; + } + + + @Override + public boolean isInGoal(int x, int y, int z) { + return primary.isInGoal(x, y, z) || fallback.isInGoal(x, y, z); + } + + @Override + public double heuristic(int x, int y, int z) { + return primary.heuristic(x, y, z); } - return incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); } public static class GoalBreak extends GoalGetToBlock { From 1dca02517e412565071ef95d0a1a5fe19dd99bbd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 9 Jan 2019 15:42:49 -0800 Subject: [PATCH 006/682] disable backtrack cost favoring while building --- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- .../baritone/pathing/movement/CalculationContext.java | 2 ++ src/main/java/baritone/process/BuilderProcess.java | 1 + src/main/java/baritone/utils/pathing/Favoring.java | 10 +++++----- .../baritone/utils/pathing/SegmentedCalculator.java | 2 +- 5 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 06020598..b789b096 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -517,7 +517,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, transformed = new GoalXZ(pos.getX(), pos.getZ()); } } - Favoring favoring = new Favoring(context.getBaritone().getPlayerContext(), previous); + Favoring favoring = new Favoring(context.getBaritone().getPlayerContext(), previous, context); return new AStarPathFinder(start.getX(), start.getY(), start.getZ(), transformed, favoring, context); } diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 95887efd..03fa6ddb 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -65,6 +65,7 @@ public class CalculationContext { public final int maxFallHeightBucket; public final double waterWalkSpeed; public final double breakBlockAdditionalCost; + public double backtrackCostFavoringCoefficient; public double jumpPenalty; public final double walkOnWaterOnePenalty; public final BetterWorldBorder worldBorder; @@ -100,6 +101,7 @@ public class CalculationContext { float mult = depth / 3.0F; this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - mult) + ActionCosts.WALK_ONE_BLOCK_COST * mult; this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.get(); + this.backtrackCostFavoringCoefficient = Baritone.settings().backtrackCostFavoringCoefficient.get(); this.jumpPenalty = Baritone.settings().jumpPenalty.get(); this.walkOnWaterOnePenalty = Baritone.settings().walkOnWaterOnePenalty.get(); // why cache these things here, why not let the movements just get directly from settings? diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index e64a6627..a679c028 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -330,6 +330,7 @@ public class BuilderProcess extends BaritoneProcessHelper { this.originZ = schematicOrigin.getZ(); this.jumpPenalty += 10; + this.backtrackCostFavoringCoefficient = 1; } private IBlockState getSchematic(int x, int y, int z) { diff --git a/src/main/java/baritone/utils/pathing/Favoring.java b/src/main/java/baritone/utils/pathing/Favoring.java index 7ffe49ff..8a601758 100644 --- a/src/main/java/baritone/utils/pathing/Favoring.java +++ b/src/main/java/baritone/utils/pathing/Favoring.java @@ -17,27 +17,27 @@ package baritone.utils.pathing; -import baritone.Baritone; import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.IPlayerContext; +import baritone.pathing.movement.CalculationContext; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; public final class Favoring { private final Long2DoubleOpenHashMap favorings; - public Favoring(IPlayerContext ctx, IPath previous) { - this(previous); + public Favoring(IPlayerContext ctx, IPath previous, CalculationContext context) { + this(previous, context); for (Avoidance avoid : Avoidance.create(ctx)) { avoid.applySpherical(favorings); } System.out.println("Favoring size: " + favorings.size()); } - public Favoring(IPath previous) { // create one just from previous path, no mob avoidances + public Favoring(IPath previous, CalculationContext context) { // create one just from previous path, no mob avoidances favorings = new Long2DoubleOpenHashMap(); favorings.defaultReturnValue(1.0D); - double coeff = Baritone.settings().backtrackCostFavoringCoefficient.get(); + double coeff = context.backtrackCostFavoringCoefficient; if (coeff != 1D && previous != null) { previous.positions().forEach(pos -> favorings.put(BetterBlockPos.longHash(pos), coeff)); } diff --git a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java index e1d6dd10..523825ab 100644 --- a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java +++ b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java @@ -87,7 +87,7 @@ public class SegmentedCalculator { private PathCalculationResult segment(Optional previous) { BetterBlockPos segmentStart = previous.map(IPath::getDest).orElse(start); // <-- e p i c - AbstractNodeCostSearch search = new AStarPathFinder(segmentStart.x, segmentStart.y, segmentStart.z, goal, new Favoring(previous.orElse(null)), context); // this is on another thread, so cannot include mob avoidances. + AbstractNodeCostSearch search = new AStarPathFinder(segmentStart.x, segmentStart.y, segmentStart.z, goal, new Favoring(previous.orElse(null), context), context); // this is on another thread, so cannot include mob avoidances. return search.calculate(Baritone.settings().primaryTimeoutMS.get(), Baritone.settings().failureTimeoutMS.get()); // use normal time settings, not the plan ahead settings, so as to not overwhelm the computer } From 1381d8d94c07629c807c76e8e238522b1638b458 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 10 Jan 2019 13:50:53 -0800 Subject: [PATCH 007/682] two small tweaks --- .../baritone/pathing/movement/movements/MovementPillar.java | 3 +++ src/main/java/baritone/utils/PathingControlManager.java | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 18a248c1..92ac6cbe 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -82,6 +82,9 @@ public class MovementPillar extends Movement { if (placeCost >= COST_INF) { return COST_INF; } + if (fromDown.getBlock() == Blocks.AIR) { + placeCost += 0.1; // slightly (1/200th of a second) penalize pillaring on what's currently air + } } if (from instanceof BlockLiquid || (fromDown.getBlock() instanceof BlockLiquid && context.assumeWalkOnWater)) { // otherwise, if we're standing in water, we cannot pillar diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 1368658b..d9879088 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -82,11 +82,12 @@ public class PathingControlManager implements IPathingControlManager { public void preTick() { inControlLastTick = inControlThisTick; + PathingBehavior p = baritone.getPathingBehavior(); command = doTheStuff(); if (command == null) { + p.cancelSegmentIfSafe(); return; } - PathingBehavior p = baritone.getPathingBehavior(); switch (command.commandType) { case REQUEST_PAUSE: p.requestPause(); From 81786f7a7cb73b1064c7fdd4a7677519049abb0e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 10 Jan 2019 13:51:26 -0800 Subject: [PATCH 008/682] reuse calculationcontext for planning ahead next segment --- .../baritone/behavior/PathingBehavior.java | 54 ++++++++----------- 1 file changed, 23 insertions(+), 31 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index b789b096..767de6b8 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -54,6 +54,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private PathExecutor next; private Goal goal; + private CalculationContext context; private boolean safeToCancel; private boolean pauseRequestedLastTick; @@ -155,7 +156,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true, new CalculationContext(baritone, true)); + findPathInNewThread(pathStart(), true, context); } return; } @@ -190,7 +191,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // and this path has 5 seconds or less left logDebug("Path almost over. Planning ahead..."); queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED); - findPathInNewThread(current.getPath().getDest(), false, new CalculationContext(baritone, true)); + findPathInNewThread(current.getPath().getDest(), false, context); } } } @@ -227,13 +228,31 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, public boolean secretInternalSetGoalAndPath(PathingCommand command) { secretInternalSetGoal(command.goal); - CalculationContext context; if (command instanceof PathingCommandContext) { context = ((PathingCommandContext) command).desiredCalcContext; } else { context = new CalculationContext(baritone, true); } - return secretInternalPath(context); + if (goal == null) { + return false; + } + BlockPos pathStart = pathStart(); + if (goal.isInGoal(ctx.playerFeet()) || goal.isInGoal(pathStart)) { + return false; + } + synchronized (pathPlanLock) { + if (current != null) { + return false; + } + synchronized (pathCalcLock) { + if (inProgress != null) { + return false; + } + queuePathEvent(PathEvent.CALC_STARTED); + findPathInNewThread(pathStart, true, context); + return true; + } + } } @Override @@ -322,33 +341,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, inProgress = null; } - /** - * Start calculating a path if we aren't already - * - * @return true if this call started path calculation, false if it was already calculating or executing a path - */ - private boolean secretInternalPath(CalculationContext context) { - if (goal == null) { - return false; - } - if (goal.isInGoal(ctx.playerFeet())) { - return false; - } - synchronized (pathPlanLock) { - if (current != null) { - return false; - } - synchronized (pathCalcLock) { - if (inProgress != null) { - return false; - } - queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true, context); - return true; - } - } - } - public void secretCursedFunctionDoNotCall(IPath path) { synchronized (pathPlanLock) { current = new PathExecutor(this, path); From f95dc40f4c7c970861afd60b2f9e3267178c4dab Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 10 Jan 2019 17:23:20 -0800 Subject: [PATCH 009/682] consolidate triple duplicated placement code --- .../baritone/behavior/PathingBehavior.java | 4 +- .../pathing/movement/MovementHelper.java | 47 ++++++++++ .../movement/movements/MovementAscend.java | 57 +++--------- .../movement/movements/MovementParkour.java | 38 +------- .../movement/movements/MovementTraverse.java | 86 +++++++------------ 5 files changed, 97 insertions(+), 135 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 767de6b8..283033fa 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -375,7 +375,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } if (MovementHelper.canWalkOn(ctx, possibleSupport.down()) && MovementHelper.canWalkThrough(ctx, possibleSupport) && MovementHelper.canWalkThrough(ctx, possibleSupport.up())) { // this is plausible - logDebug("Faking path start assuming player is standing off the edge of a block"); + //logDebug("Faking path start assuming player is standing off the edge of a block"); return possibleSupport; } } @@ -384,7 +384,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // !onGround // we're in the middle of a jump if (MovementHelper.canWalkOn(ctx, feet.down().down())) { - logDebug("Faking path start assuming player is midair and falling"); + //logDebug("Faking path start assuming player is midair and falling"); return feet.down(); } } diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 96c4a769..790144f9 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -19,6 +19,7 @@ package baritone.pathing.movement; import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.*; import baritone.api.utils.input.Input; import baritone.pathing.movement.MovementState.MovementTarget; @@ -35,6 +36,10 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; + +import static baritone.pathing.movement.Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP; /** * Static helpers for cost calculation @@ -487,4 +492,46 @@ public interface MovementHelper extends ActionCosts, Helper { return state.getBlock() instanceof BlockLiquid && state.getValue(BlockLiquid.LEVEL) != 0; } + + static PlaceResult attemptToPlaceABlock(MovementState state, IPlayerContext ctx, BlockPos placeAt, boolean preferDown) { + boolean found = false; + for (int i = 0; i < 5; i++) { + BlockPos against1 = placeAt.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); + if (MovementHelper.canPlaceAgainst(ctx, against1)) { + if (!MovementHelper.throwaway(ctx, true)) { // get ready to place a throwaway block + Helper.HELPER.logDebug("bb pls get me some blocks. dirt or cobble"); + state.setStatus(MovementStatus.UNREACHABLE); + return PlaceResult.NO_OPTION; + } + double faceX = (placeAt.getX() + against1.getX() + 1.0D) * 0.5D; + double faceY = (placeAt.getY() + against1.getY() + 1.0D) * 0.5D; + double faceZ = (placeAt.getZ() + against1.getZ() + 1.0D) * 0.5D; + Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); + RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance()); + 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; + + if (!preferDown) { + // if preferDown is true, we want the last option + // if preferDown is false, we want the first + break; + } + } + } + } + if (ctx.getSelectedBlock().isPresent()) { + BlockPos selectedBlock = ctx.getSelectedBlock().get(); + EnumFacing side = ctx.objectMouseOver().sideHit; + // only way for selectedBlock.equals(placeAt) to be true is if it's replacable + if (selectedBlock.equals(placeAt) || (MovementHelper.canPlaceAgainst(ctx, selectedBlock) && selectedBlock.offset(side).equals(placeAt))) { + return PlaceResult.READY_TO_PLACE; + } + } + return found ? PlaceResult.ATTEMPTING : PlaceResult.NO_OPTION; + } + + enum PlaceResult { + READY_TO_PLACE, ATTEMPTING, NO_OPTION; + } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 5fafdeed..8508e776 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -21,7 +21,6 @@ import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -32,10 +31,6 @@ import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; - -import java.util.Objects; public class MovementAscend extends Movement { @@ -161,55 +156,29 @@ public class MovementAscend extends Movement { IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace); if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) { - for (int i = 0; i < 5; i++) { - BlockPos anAgainst = positionToPlace.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); - if (anAgainst.equals(src)) { - continue; - } - if (MovementHelper.canPlaceAgainst(ctx, anAgainst)) { - if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block - return state.setStatus(MovementStatus.UNREACHABLE); - } - double faceX = (dest.getX() + anAgainst.getX() + 1.0D) * 0.5D; - double faceY = (dest.getY() + anAgainst.getY()) * 0.5D; - double faceZ = (dest.getZ() + anAgainst.getZ() + 1.0D) * 0.5D; - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true)); - EnumFacing side = ctx.objectMouseOver().sideHit; - - ctx.getSelectedBlock().ifPresent(selectedBlock -> { - if (Objects.equals(selectedBlock, anAgainst) && selectedBlock.offset(side).equals(positionToPlace)) { - ticksWithoutPlacement++; - state.setInput(Input.SNEAK, true); - if (ctx.player().isSneaking()) { - state.setInput(Input.CLICK_RIGHT, true); - } - if (ticksWithoutPlacement > 10) { - // After 10 ticks without placement, we might be standing in the way, move back - state.setInput(Input.MOVE_BACK, true); - } - } else { - state.setInput(Input.CLICK_LEFT, true); // break whatever replaceable block is in the way - } - //System.out.println("Trying to look at " + anAgainst + ", actually looking at" + selectedBlock); - }); - return state; + ticksWithoutPlacement++; + if (MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false) == PlaceResult.READY_TO_PLACE) { + state.setInput(Input.SNEAK, true); + if (ctx.player().isSneaking()) { + state.setInput(Input.CLICK_RIGHT, true); } } - return state.setStatus(MovementStatus.UNREACHABLE); + if (ticksWithoutPlacement > 10) { + // After 10 ticks without placement, we might be standing in the way, move back + state.setInput(Input.MOVE_BACK, true); + } + + return state; } MovementHelper.moveTowards(ctx, state, dest); if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(BlockStateInterface.get(ctx, src.down()))) { return state; // don't jump while walking from a non double slab into a bottom slab } - - if (Baritone.settings().assumeStep.get()) { + if (Baritone.settings().assumeStep.get() || ctx.playerFeet().equals(src.up())) { + // no need to hit space if we're already jumping return state; } - if (ctx.playerFeet().equals(src.up())) { - return state; // no need to hit space if we're already jumping - } - if (headBonkClear()) { return state.setInput(Input.JUMP, true); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 7c4ca19a..2d668bfb 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -20,9 +20,6 @@ package baritone.pathing.movement.movements; import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.RayTraceUtils; -import baritone.api.utils.Rotation; -import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -35,9 +32,6 @@ import net.minecraft.block.BlockStairs; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; public class MovementParkour extends Movement { @@ -211,35 +205,9 @@ public class MovementParkour extends Movement { } } else if (!ctx.playerFeet().equals(src)) { if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - ctx.playerFeet().getY() > 0.0001) { - - if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround) { - BlockPos positionToPlace = dest.down(); - for (int i = 4; i >= 0; i--) { // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory - BlockPos against1 = positionToPlace.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); - if (against1.up().equals(src.offset(direction, 3))) { // we can't turn around that fast - continue; - } - if (MovementHelper.canPlaceAgainst(ctx, against1)) { - if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block - return state.setStatus(MovementStatus.UNREACHABLE); - } - double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; - double faceY = (dest.getY() + against1.getY()) * 0.5D; - double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; - Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); - RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance()); - if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(dest.down())) { - state.setTarget(new MovementState.MovementTarget(place, true)); - break; - } - } - } - ctx.getSelectedBlock().ifPresent(selectedBlock -> { - EnumFacing side = ctx.objectMouseOver().sideHit; - if (MovementHelper.canPlaceAgainst(ctx, selectedBlock) && selectedBlock.offset(side).equals(dest.down())) { - state.setInput(Input.CLICK_RIGHT, true); - } - }); + if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), true) == PlaceResult.READY_TO_PLACE) { + // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory + state.setInput(Input.CLICK_RIGHT, true); } if (dist == 3) { // this is a 2 block gap, dest = src + direction * 3 double xDiff = (src.x + 0.5) - ctx.player().posX; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 1c5c4f2e..6c78e7d3 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -36,7 +36,6 @@ import net.minecraft.block.BlockFenceGate; import net.minecraft.block.BlockSlab; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; -import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; @@ -248,63 +247,40 @@ public class MovementTraverse extends Movement { return state; } else { wasTheBridgeBlockAlwaysThere = false; - for (int i = 0; i < 5; i++) { - BlockPos against1 = dest.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); - if (against1.equals(src)) { - continue; - } - against1 = against1.down(); - if (MovementHelper.canPlaceAgainst(ctx, against1)) { - if (!MovementHelper.throwaway(ctx, true)) { // get ready to place a throwaway block - logDebug("bb pls get me some blocks. dirt or cobble"); - return state.setStatus(MovementStatus.UNREACHABLE); - } - if (!Baritone.settings().assumeSafeWalk.get()) { - state.setInput(Input.SNEAK, true); - } - Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock(); - if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 - double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); - if (dist < 0.85) { // 0.5 + 0.3 + epsilon - MovementHelper.moveTowards(ctx, state, dest); - return state.setInput(Input.MOVE_FORWARD, false) - .setInput(Input.MOVE_BACK, true); - } - } - state.setInput(Input.MOVE_BACK, false); - double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; - double faceY = (dest.getY() + against1.getY()) * 0.5D; - double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; - Rotation rot = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); - state.setTarget(new MovementState.MovementTarget(rot, true)); - - EnumFacing side = ctx.objectMouseOver().sideHit; - if ((Objects.equals(ctx.getSelectedBlock(), dest.down()) || (Objects.equals(ctx.getSelectedBlock().orElse(null), against1) && ctx.getSelectedBlock().get().offset(side).equals(positionToPlace))) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get())) { - return state.setInput(Input.CLICK_RIGHT, true); - } - if (ctx.playerRotations().isReallyCloseTo(rot)) { - double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); - if (dist > 0.83) { - // might need to go forward a bit - return state.setInput(Input.MOVE_FORWARD, true); - } - // don't left click for one tick - return state.setInput(Input.CLICK_LEFT, true); - } - return state; - //System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); - } - } if (!Baritone.settings().assumeSafeWalk.get()) { state.setInput(Input.SNEAK, true); } + Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock(); + if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 + double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); + if (dist < 0.85) { // 0.5 + 0.3 + epsilon + MovementHelper.moveTowards(ctx, state, dest); + return state.setInput(Input.MOVE_FORWARD, false) + .setInput(Input.MOVE_BACK, true); + } + } + state.setInput(Input.MOVE_BACK, false); + switch (MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false)) { + case READY_TO_PLACE: + if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) { + state.setInput(Input.CLICK_RIGHT, true); + } + return state; + case ATTEMPTING: + double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); + if (dist > 0.83) { + // might need to go forward a bit + return state.setInput(Input.MOVE_FORWARD, true); + } else if (ctx.playerRotations().isReallyCloseTo(state.getGoal().rotation)) { + // well i guess theres something in the way + return state.setInput(Input.CLICK_LEFT, true); + } + case NO_OPTION: + break; + } if (whereAmI.equals(dest)) { // If we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of // Out.log(from + " " + to + " " + faceX + "," + faceY + "," + faceZ + " " + whereAmI); - if (!MovementHelper.throwaway(ctx, true)) {// get ready to place a throwaway block - logDebug("bb pls get me some blocks. dirt or cobble"); - return state.setStatus(MovementStatus.UNREACHABLE); - } double faceX = (dest.getX() + src.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + src.getY() - 1.0D) * 0.5D; double faceZ = (dest.getZ() + src.getZ() + 1.0D) * 0.5D; @@ -321,12 +297,14 @@ public class MovementTraverse extends Movement { } else { state.setTarget(new MovementState.MovementTarget(backToFace, true)); } - state.setInput(Input.SNEAK, true); if (Objects.equals(ctx.getSelectedBlock().orElse(null), goalLook)) { return state.setInput(Input.CLICK_RIGHT, true); // wait to right click until we are able to place } // Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt()); - return state.setInput(Input.CLICK_LEFT, true); + if (ctx.playerRotations().isReallyCloseTo(state.getGoal().rotation)) { + state.setInput(Input.CLICK_LEFT, true); + } + return state; } else { MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); return state; From 863ae447b9d36fb272d303c7e5babd2c361b8f49 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 10 Jan 2019 18:15:05 -0800 Subject: [PATCH 010/682] except we actually make it work --- .../movement/movements/MovementTraverse.java | 44 ++++++++++--------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 6c78e7d3..fa892291 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -247,9 +247,6 @@ public class MovementTraverse extends Movement { return state; } else { wasTheBridgeBlockAlwaysThere = false; - if (!Baritone.settings().assumeSafeWalk.get()) { - state.setInput(Input.SNEAK, true); - } Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock(); if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); @@ -259,24 +256,32 @@ public class MovementTraverse extends Movement { .setInput(Input.MOVE_BACK, true); } } - state.setInput(Input.MOVE_BACK, false); - switch (MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false)) { - case READY_TO_PLACE: + double dist1 = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); + PlaceResult p = MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false); + if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.get()) { + state.setInput(Input.SNEAK, true); + } + switch (p) { + case READY_TO_PLACE: { if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) { state.setInput(Input.CLICK_RIGHT, true); } return state; - case ATTEMPTING: - double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); - if (dist > 0.83) { + } + case ATTEMPTING: { + if (dist1 > 0.83) { // might need to go forward a bit - return state.setInput(Input.MOVE_FORWARD, true); - } else if (ctx.playerRotations().isReallyCloseTo(state.getGoal().rotation)) { + float yaw = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()).getYaw(); + if (Math.abs(state.getTarget().rotation.getYaw() - yaw) < 0.1) { + // but only if our attempted place is straight ahead + return state.setInput(Input.MOVE_FORWARD, true); + } + } else if (ctx.playerRotations().isReallyCloseTo(state.getTarget().rotation)) { // well i guess theres something in the way return state.setInput(Input.CLICK_LEFT, true); } - case NO_OPTION: - break; + return state; + } } if (whereAmI.equals(dest)) { // If we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of @@ -289,8 +294,8 @@ public class MovementTraverse extends Movement { Rotation backToFace = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); float pitch = backToFace.getPitch(); - double dist = Math.max(Math.abs(ctx.player().posX - faceX), Math.abs(ctx.player().posZ - faceZ)); - if (dist < 0.29) { + double dist2 = Math.max(Math.abs(ctx.player().posX - faceX), Math.abs(ctx.player().posZ - faceZ)); + if (dist2 < 0.29) { // see issue #208 float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), ctx.playerHead(), ctx.playerRotations()).getYaw(); state.setTarget(new MovementState.MovementTarget(new Rotation(yaw, pitch), true)); state.setInput(Input.MOVE_BACK, true); @@ -301,15 +306,14 @@ public class MovementTraverse extends Movement { return state.setInput(Input.CLICK_RIGHT, true); // wait to right click until we are able to place } // Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt()); - if (ctx.playerRotations().isReallyCloseTo(state.getGoal().rotation)) { + if (ctx.playerRotations().isReallyCloseTo(state.getTarget().rotation)) { state.setInput(Input.CLICK_LEFT, true); } return state; - } else { - MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); - return state; - // TODO MovementManager.moveTowardsBlock(to); // move towards not look at because if we are bridging for a couple blocks in a row, it is faster if we dont spin around and walk forwards then spin around and place backwards for every block } + MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); + return state; + // TODO MovementManager.moveTowardsBlock(to); // move towards not look at because if we are bridging for a couple blocks in a row, it is faster if we dont spin around and walk forwards then spin around and place backwards for every block } } From a965859095b71f312a051146e745c428bf53477a Mon Sep 17 00:00:00 2001 From: babbaj Date: Fri, 11 Jan 2019 01:13:14 -0500 Subject: [PATCH 011/682] make code easy to understand --- .../java/baritone/utils/MapArtSchematic.java | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/main/java/baritone/utils/MapArtSchematic.java b/src/main/java/baritone/utils/MapArtSchematic.java index 9813b637..5ff16f3f 100644 --- a/src/main/java/baritone/utils/MapArtSchematic.java +++ b/src/main/java/baritone/utils/MapArtSchematic.java @@ -17,6 +17,8 @@ package baritone.utils; +import java.util.OptionalInt; +import java.util.function.Predicate; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; @@ -27,23 +29,33 @@ public class MapArtSchematic extends Schematic { public MapArtSchematic(NBTTagCompound schematic) { super(schematic); heightMap = new int[widthX][lengthZ]; + for (int x = 0; x < widthX; x++) { - https: for (int z = 0; z < lengthZ; z++) { IBlockState[] column = states[x][z]; - for (int y = heightY - 1; y >= 0; y--) { - if (column[y].getBlock() != Blocks.AIR) { - heightMap[x][z] = y; - continue https; - } + + OptionalInt lowestBlockY = getLowest(column, block -> block != Blocks.AIR); + if (lowestBlockY.isPresent()) { + heightMap[x][z] = lowestBlockY.getAsInt(); + } else { + System.out.println("Column " + x + "," + z + " has no blocks, but it's apparently map art? wtf"); + System.out.println("Letting it be whatever"); + heightMap[x][z] = 256; } - System.out.println("Column " + x + "," + z + " has no blocks, but it's apparently map art? wtf"); - System.out.println("Letting it be whatever"); - heightMap[x][z] = 256; + } } } + private static OptionalInt getLowest(T[] arr, Predicate predicate) { + for (int y = arr.length - 1; y >= 0; y--) { + if (predicate.test(arr[y])) { + return OptionalInt.of(y); + } + } + return OptionalInt.empty(); + } + @Override public boolean inSchematic(int x, int y, int z) { // in map art, we only care about coordinates in or above the art From 14bc65468a9e5995448725a4183a376018946300 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 11 Jan 2019 10:02:21 -0800 Subject: [PATCH 012/682] tweaks --- src/main/java/baritone/utils/MapArtSchematic.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/utils/MapArtSchematic.java b/src/main/java/baritone/utils/MapArtSchematic.java index 5ff16f3f..711a4ed8 100644 --- a/src/main/java/baritone/utils/MapArtSchematic.java +++ b/src/main/java/baritone/utils/MapArtSchematic.java @@ -17,12 +17,13 @@ package baritone.utils; -import java.util.OptionalInt; -import java.util.function.Predicate; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; +import java.util.OptionalInt; +import java.util.function.Predicate; + public class MapArtSchematic extends Schematic { private final int[][] heightMap; @@ -34,7 +35,7 @@ public class MapArtSchematic extends Schematic { for (int z = 0; z < lengthZ; z++) { IBlockState[] column = states[x][z]; - OptionalInt lowestBlockY = getLowest(column, block -> block != Blocks.AIR); + OptionalInt lowestBlockY = lastIndexMatching(column, block -> block != Blocks.AIR); if (lowestBlockY.isPresent()) { heightMap[x][z] = lowestBlockY.getAsInt(); } else { @@ -47,7 +48,7 @@ public class MapArtSchematic extends Schematic { } } - private static OptionalInt getLowest(T[] arr, Predicate predicate) { + private static OptionalInt lastIndexMatching(T[] arr, Predicate predicate) { for (int y = arr.length - 1; y >= 0; y--) { if (predicate.test(arr[y])) { return OptionalInt.of(y); From a6ce4694fcb2020529a339c452a27cdc37d88464 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 12 Jan 2019 19:51:21 -0800 Subject: [PATCH 013/682] hotbar selection uwu --- src/main/java/baritone/Baritone.java | 7 ++- .../baritone/behavior/InventoryBehavior.java | 60 +++++++++++++++++++ .../pathing/movement/CalculationContext.java | 2 +- .../pathing/movement/MovementHelper.java | 45 ++------------ .../movement/movements/MovementAscend.java | 2 +- .../movement/movements/MovementParkour.java | 2 +- .../movement/movements/MovementPillar.java | 3 +- .../movement/movements/MovementTraverse.java | 2 +- .../java/baritone/process/BuilderProcess.java | 28 +++++++-- 9 files changed, 98 insertions(+), 53 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 358a4f2b..8a3bf8c3 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -74,6 +74,7 @@ public class Baritone implements IBaritone { private PathingBehavior pathingBehavior; private LookBehavior lookBehavior; private MemoryBehavior memoryBehavior; + private InventoryBehavior inventoryBehavior; private InputOverrideHandler inputOverrideHandler; private FollowProcess followProcess; @@ -105,7 +106,7 @@ public class Baritone implements IBaritone { pathingBehavior = new PathingBehavior(this); lookBehavior = new LookBehavior(this); memoryBehavior = new MemoryBehavior(this); - new InventoryBehavior(this); + inventoryBehavior = new InventoryBehavior(this); inputOverrideHandler = new InputOverrideHandler(this); new ExampleBaritoneControl(this); } @@ -174,6 +175,10 @@ public class Baritone implements IBaritone { return this.builderProcess; } + public InventoryBehavior getInventoryBehavior() { + return this.inventoryBehavior; + } + @Override public LookBehavior getLookBehavior() { return this.lookBehavior; diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index a49cbb7d..29e45a96 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -21,8 +21,10 @@ import baritone.Baritone; import baritone.api.event.events.TickEvent; import baritone.utils.ToolSet; import net.minecraft.block.Block; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.init.Blocks; import net.minecraft.inventory.ClickType; +import net.minecraft.item.Item; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; @@ -87,4 +89,62 @@ public class InventoryBehavior extends Behavior { } return bestInd; } + + public boolean hasGenericThrowaway() { + for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { + if (throwaway(false, item)) { + return true; + } + } + return false; + } + + public boolean selectThrowawayForLocation(int x, int y, int z) { + Item maybe = baritone.getBuilderProcess().placeAt(x, y, z); + if (maybe != null && throwaway(true, maybe)) { + return true; // gotem + } + for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { + if (throwaway(true, item)) { + return true; + } + } + return false; + } + + private boolean throwaway(boolean select, Item desired) { + EntityPlayerSP p = ctx.player(); + NonNullList inv = p.inventory.mainInventory; + for (byte i = 0; i < 9; i++) { + ItemStack item = inv.get(i); + // this usage of settings() is okay because it's only called once during pathing + // (while creating the CalculationContext at the very beginning) + // and then it's called during execution + // since this function is never called during cost calculation, we don't need to migrate + // acceptableThrowawayItems to the CalculationContext + if (desired.equals(item.getItem())) { + if (select) { + p.inventory.currentItem = i; + } + return true; + } + } + if (desired.equals(p.inventory.offHandInventory.get(0).getItem())) { + // main hand takes precedence over off hand + // that means that if we have block A selected in main hand and block B in off hand, right clicking places block B + // we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem + // so we need to select in the main hand something that doesn't right click + // so not a shovel, not a hoe, not a block, etc + for (byte i = 0; i < 9; i++) { + ItemStack item = inv.get(i); + if (item.isEmpty() || item.getItem() instanceof ItemPickaxe) { + if (select) { + p.inventory.currentItem = i; + } + return true; + } + } + } + return false; + } } diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 6af1dae9..ebca5f19 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -81,7 +81,7 @@ public class CalculationContext { this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld(); this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); this.toolSet = new ToolSet(player); - this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(baritone.getPlayerContext(), false); + this.hasThrowaway = Baritone.settings().allowPlace.get() && ((Baritone) baritone).getInventoryBehavior().hasGenericThrowaway(); this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether(); this.canSprint = Baritone.settings().allowSprint.get() && player.getFoodStats().getFoodLevel() > 6; this.placeBlockCost = Baritone.settings().blockPlacementPenalty.get(); diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 790144f9..9bfebcc2 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -18,6 +18,7 @@ package baritone.pathing.movement; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.*; @@ -31,10 +32,7 @@ import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.IBlockState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.init.Blocks; -import net.minecraft.item.ItemPickaxe; -import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; -import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; @@ -403,42 +401,6 @@ public interface MovementHelper extends ActionCosts, Helper { ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock()); } - static boolean throwaway(IPlayerContext ctx, boolean select) { - EntityPlayerSP p = ctx.player(); - NonNullList inv = p.inventory.mainInventory; - for (byte i = 0; i < 9; i++) { - ItemStack item = inv.get(i); - // this usage of settings() is okay because it's only called once during pathing - // (while creating the CalculationContext at the very beginning) - // and then it's called during execution - // since this function is never called during cost calculation, we don't need to migrate - // acceptableThrowawayItems to the CalculationContext - if (Baritone.settings().acceptableThrowawayItems.get().contains(item.getItem())) { - if (select) { - p.inventory.currentItem = i; - } - return true; - } - } - if (Baritone.settings().acceptableThrowawayItems.get().contains(p.inventory.offHandInventory.get(0).getItem())) { - // main hand takes precedence over off hand - // that means that if we have block A selected in main hand and block B in off hand, right clicking places block B - // we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem - // so we need to select in the main hand something that doesn't right click - // so not a shovel, not a hoe, not a block, etc - for (byte i = 0; i < 9; i++) { - ItemStack item = inv.get(i); - if (item.isEmpty() || item.getItem() instanceof ItemPickaxe) { - if (select) { - p.inventory.currentItem = i; - } - return true; - } - } - } - return false; - } - static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) { EntityPlayerSP player = ctx.player(); state.setTarget(new MovementTarget( @@ -493,12 +455,13 @@ public interface MovementHelper extends ActionCosts, Helper { && state.getValue(BlockLiquid.LEVEL) != 0; } - static PlaceResult attemptToPlaceABlock(MovementState state, IPlayerContext ctx, BlockPos placeAt, boolean preferDown) { + static PlaceResult attemptToPlaceABlock(MovementState state, IBaritone baritone, BlockPos placeAt, boolean preferDown) { + IPlayerContext ctx = baritone.getPlayerContext(); boolean found = false; for (int i = 0; i < 5; i++) { BlockPos against1 = placeAt.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); if (MovementHelper.canPlaceAgainst(ctx, against1)) { - if (!MovementHelper.throwaway(ctx, true)) { // get ready to place a throwaway block + if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(placeAt.getX(), placeAt.getY(), placeAt.getZ())) { // get ready to place a throwaway block Helper.HELPER.logDebug("bb pls get me some blocks. dirt or cobble"); state.setStatus(MovementStatus.UNREACHABLE); return PlaceResult.NO_OPTION; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 8508e776..d937cc8f 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -157,7 +157,7 @@ public class MovementAscend extends Movement { IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace); if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) { ticksWithoutPlacement++; - if (MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false) == PlaceResult.READY_TO_PLACE) { + if (MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false) == PlaceResult.READY_TO_PLACE) { state.setInput(Input.SNEAK, true); if (ctx.player().isSneaking()) { state.setInput(Input.CLICK_RIGHT, true); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 2d668bfb..98898690 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -205,7 +205,7 @@ public class MovementParkour extends Movement { } } else if (!ctx.playerFeet().equals(src)) { if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - ctx.playerFeet().getY() > 0.0001) { - if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), true) == PlaceResult.READY_TO_PLACE) { + if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), true) == PlaceResult.READY_TO_PLACE) { // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory state.setInput(Input.CLICK_RIGHT, true); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 92ac6cbe..a9d1e20e 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -17,6 +17,7 @@ package baritone.pathing.movement.movements; +import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; @@ -202,7 +203,7 @@ public class MovementPillar extends Movement { return state; } else { // Get ready to place a throwaway block - if (!MovementHelper.throwaway(ctx, true)) { + if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(src.x, src.y, src.z)) { return state.setStatus(MovementStatus.UNREACHABLE); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index fa892291..40597e97 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -257,7 +257,7 @@ public class MovementTraverse extends Movement { } } double dist1 = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); - PlaceResult p = MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false); + PlaceResult p = MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false); if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.get()) { state.setInput(Input.SNEAK, true); } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index a679c028..875fa81b 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -37,6 +37,7 @@ import baritone.utils.Schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; +import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; @@ -93,6 +94,21 @@ public class BuilderProcess extends BaritoneProcessHelper { return schematic != null; } + public Item placeAt(int x, int y, int z) { + if (!isActive()) { + return null; + } + if (!schematic.inSchematic(x - origin.getX(), y - origin.getY(), z - origin.getZ())) { + return null; + } + IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ()); + if (state.getBlock() == Blocks.AIR) { + return null; + } + return new ItemBlock(state.getBlock()); + } + + public Optional> toBreakNearPlayer(BuilderCalculationContext bcc) { BetterBlockPos center = ctx.playerFeet(); for (int dx = -5; dx <= 5; dx++) { @@ -129,7 +145,7 @@ public class BuilderProcess extends BaritoneProcessHelper { // need to iterate over incorrectPositions and see which ones we can "correct" from our current standing position - BuilderCalculationContext bcc = new BuilderCalculationContext(schematic, origin); + BuilderCalculationContext bcc = new BuilderCalculationContext(); if (!recalc(bcc)) { logDirect("Done building"); onLostControl(); @@ -321,13 +337,13 @@ public class BuilderProcess extends BaritoneProcessHelper { private final int originY; private final int originZ; - public BuilderCalculationContext(ISchematic schematic, Vec3i schematicOrigin) { + public BuilderCalculationContext() { super(BuilderProcess.this.baritone, true); // wew lad this.placable = placable(); - this.schematic = schematic; - this.originX = schematicOrigin.getX(); - this.originY = schematicOrigin.getY(); - this.originZ = schematicOrigin.getZ(); + this.schematic = BuilderProcess.this.schematic; + this.originX = origin.getX(); + this.originY = origin.getY(); + this.originZ = origin.getZ(); this.jumpPenalty += 10; this.backtrackCostFavoringCoefficient = 1; From e2cdd6a7f90b710109c662793e7fc9c72c2c7133 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 14 Jan 2019 19:49:26 -0800 Subject: [PATCH 014/682] builder with multiple materials --- .../baritone/behavior/InventoryBehavior.java | 22 +++++++++---------- .../java/baritone/process/BuilderProcess.java | 5 ++--- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 29e45a96..231f577e 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -21,15 +21,15 @@ import baritone.Baritone; import baritone.api.event.events.TickEvent; import baritone.utils.ToolSet; import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.init.Blocks; import net.minecraft.inventory.ClickType; -import net.minecraft.item.Item; -import net.minecraft.item.ItemPickaxe; -import net.minecraft.item.ItemStack; -import net.minecraft.item.ItemTool; +import net.minecraft.item.*; import net.minecraft.util.NonNullList; +import java.util.function.Predicate; + public class InventoryBehavior extends Behavior { public InventoryBehavior(Baritone baritone) { super(baritone); @@ -92,7 +92,7 @@ public class InventoryBehavior extends Behavior { public boolean hasGenericThrowaway() { for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { - if (throwaway(false, item)) { + if (throwaway(false, item::equals)) { return true; } } @@ -100,19 +100,19 @@ public class InventoryBehavior extends Behavior { } public boolean selectThrowawayForLocation(int x, int y, int z) { - Item maybe = baritone.getBuilderProcess().placeAt(x, y, z); - if (maybe != null && throwaway(true, maybe)) { + IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z); + if (maybe != null && throwaway(true, item -> item instanceof ItemBlock && ((ItemBlock) item).getBlock().equals(maybe.getBlock()))) { return true; // gotem } for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { - if (throwaway(true, item)) { + if (throwaway(true, item::equals)) { return true; } } return false; } - private boolean throwaway(boolean select, Item desired) { + private boolean throwaway(boolean select, Predicate desired) { EntityPlayerSP p = ctx.player(); NonNullList inv = p.inventory.mainInventory; for (byte i = 0; i < 9; i++) { @@ -122,14 +122,14 @@ public class InventoryBehavior extends Behavior { // and then it's called during execution // since this function is never called during cost calculation, we don't need to migrate // acceptableThrowawayItems to the CalculationContext - if (desired.equals(item.getItem())) { + if (desired.test(item.getItem())) { if (select) { p.inventory.currentItem = i; } return true; } } - if (desired.equals(p.inventory.offHandInventory.get(0).getItem())) { + if (desired.test(p.inventory.offHandInventory.get(0).getItem())) { // main hand takes precedence over off hand // that means that if we have block A selected in main hand and block B in off hand, right clicking places block B // we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 875fa81b..0b34fb07 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -37,7 +37,6 @@ import baritone.utils.Schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; -import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; @@ -94,7 +93,7 @@ public class BuilderProcess extends BaritoneProcessHelper { return schematic != null; } - public Item placeAt(int x, int y, int z) { + public IBlockState placeAt(int x, int y, int z) { if (!isActive()) { return null; } @@ -105,7 +104,7 @@ public class BuilderProcess extends BaritoneProcessHelper { if (state.getBlock() == Blocks.AIR) { return null; } - return new ItemBlock(state.getBlock()); + return state; } From d5b393d6bdd9ca265e61f3e8833854b145467040 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 14 Jan 2019 21:41:40 -0800 Subject: [PATCH 015/682] area clear --- .../java/baritone/process/BuilderProcess.java | 10 ++-- .../java/baritone/utils/AirSchematic.java | 53 +++++++++++++++++++ .../utils/ExampleBaritoneControl.java | 30 +++++++++++ src/main/java/baritone/utils/ISchematic.java | 4 +- src/main/java/baritone/utils/Schematic.java | 5 -- 5 files changed, 93 insertions(+), 9 deletions(-) create mode 100644 src/main/java/baritone/utils/AirSchematic.java diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 0b34fb07..1ac201e1 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -78,12 +78,16 @@ public class BuilderProcess extends BaritoneProcessHelper { if (tag == null) { return false; } - name = schematicFile; - schematic = parse(tag); - origin = ctx.playerFeet(); + build(schematicFile, parse(tag), ctx.playerFeet()); return true; } + public void build(String name, ISchematic schematic, Vec3i origin) { + this.name = name; + this.schematic = schematic; + this.origin = origin; + } + private static ISchematic parse(NBTTagCompound schematic) { return new Schematic(schematic); } diff --git a/src/main/java/baritone/utils/AirSchematic.java b/src/main/java/baritone/utils/AirSchematic.java new file mode 100644 index 00000000..bced26e7 --- /dev/null +++ b/src/main/java/baritone/utils/AirSchematic.java @@ -0,0 +1,53 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; + +public class AirSchematic implements ISchematic { + public final int widthX; + public final int heightY; + public final int lengthZ; + + public AirSchematic(int widthX, int heightY, int lengthZ) { + this.widthX = widthX; + this.heightY = heightY; + this.lengthZ = lengthZ; + } + + @Override + public IBlockState desiredState(int x, int y, int z) { + return Blocks.AIR.getDefaultState(); + } + + @Override + public int widthX() { + return widthX; + } + + @Override + public int heightY() { + return heightY; + } + + @Override + public int lengthZ() { + return lengthZ; + } +} diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 55009575..6e65c087 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -284,6 +284,36 @@ public class ExampleBaritoneControl extends Behavior implements Helper { }); return true; } + if (msg.startsWith("cleararea")) { + String suffix = msg.substring("cleararea".length()); + BlockPos corner1; + BlockPos corner2; + if (suffix.isEmpty()) { + // clear the area from the current goal to here + Goal goal = baritone.getPathingBehavior().getGoal(); + if (goal == null || !(goal instanceof GoalBlock)) { + logDirect("Need to specify goal of opposite corner"); + return true; + } + corner1 = ((GoalBlock) goal).getGoalPos(); + corner2 = ctx.playerFeet(); + } else { + try { + String[] spl = suffix.split(" "); + corner1 = ctx.playerFeet(); + corner2 = new BlockPos(Integer.parseInt(spl[0]), Integer.parseInt(spl[1]), Integer.parseInt(spl[2])); + } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) { + logDirect("unable to parse"); + return true; + } + } + BlockPos origin = new BlockPos(Math.min(corner1.getX(), corner2.getX()), Math.min(corner1.getY(), corner2.getY()), Math.min(corner1.getZ(), corner2.getZ())); + int widthX = Math.abs(corner1.getX() - corner2.getX()) + 1; + int heightY = Math.abs(corner1.getY() - corner2.getY()) + 1; + int lengthZ = Math.abs(corner1.getZ() - corner2.getZ()) + 1; + baritone.getBuilderProcess().build("clear area", new AirSchematic(widthX, heightY, lengthZ), origin); + return true; + } if (msg.equals("reset")) { Baritone.settings().reset(); logDirect("Baritone settings reset"); diff --git a/src/main/java/baritone/utils/ISchematic.java b/src/main/java/baritone/utils/ISchematic.java index b68f1a1c..77ba8634 100644 --- a/src/main/java/baritone/utils/ISchematic.java +++ b/src/main/java/baritone/utils/ISchematic.java @@ -33,7 +33,9 @@ public interface ISchematic { * @param z * @return */ - boolean inSchematic(int x, int y, int z); + default boolean inSchematic(int x, int y, int z) { + return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ(); + } IBlockState desiredState(int x, int y, int z); diff --git a/src/main/java/baritone/utils/Schematic.java b/src/main/java/baritone/utils/Schematic.java index dbc80a73..3fef4b1e 100644 --- a/src/main/java/baritone/utils/Schematic.java +++ b/src/main/java/baritone/utils/Schematic.java @@ -66,11 +66,6 @@ public class Schematic implements ISchematic { } } - @Override - public boolean inSchematic(int x, int y, int z) { - return x >= 0 && x < widthX && y >= 0 && y < heightY && z >= 0 && z < lengthZ; - } - @Override public IBlockState desiredState(int x, int y, int z) { return states[x][z][y]; From ceda14096c0a27ae69a9104197effdbde8d69a30 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 15 Jan 2019 22:07:06 -0600 Subject: [PATCH 016/682] Builder Process API exposure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Professional style 💪 --- src/api/java/baritone/api/IBaritone.java | 11 +++-- .../baritone/api/process/IBuilderProcess.java | 49 +++++++++++++++++++ .../java/baritone/api}/utils/ISchematic.java | 34 +++++++++++-- src/main/java/baritone/Baritone.java | 1 + .../java/baritone/process/BuilderProcess.java | 27 ++++++---- .../java/baritone/utils/AirSchematic.java | 1 + src/main/java/baritone/utils/Schematic.java | 1 + 7 files changed, 105 insertions(+), 19 deletions(-) create mode 100644 src/api/java/baritone/api/process/IBuilderProcess.java rename src/{main/java/baritone => api/java/baritone/api}/utils/ISchematic.java (56%) diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index 6bdb7d10..a2f414e7 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -22,10 +22,7 @@ import baritone.api.behavior.IPathingBehavior; import baritone.api.cache.IWorldProvider; import baritone.api.event.listener.IEventBus; import baritone.api.pathing.calc.IPathingControlManager; -import baritone.api.process.ICustomGoalProcess; -import baritone.api.process.IFollowProcess; -import baritone.api.process.IGetToBlockProcess; -import baritone.api.process.IMineProcess; +import baritone.api.process.*; import baritone.api.utils.IInputOverrideHandler; import baritone.api.utils.IPlayerContext; @@ -53,6 +50,12 @@ public interface IBaritone { */ IMineProcess getMineProcess(); + /** + * @return The {@link IBuilderProcess} instance + * @see IBuilderProcess + */ + IBuilderProcess getBuilderProcess(); + /** * @return The {@link IPathingBehavior} instance * @see IPathingBehavior diff --git a/src/api/java/baritone/api/process/IBuilderProcess.java b/src/api/java/baritone/api/process/IBuilderProcess.java new file mode 100644 index 00000000..694c8752 --- /dev/null +++ b/src/api/java/baritone/api/process/IBuilderProcess.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.process; + +import baritone.api.utils.ISchematic; +import net.minecraft.util.math.Vec3i; + +import java.io.File; + +/** + * @author Brady + * @since 1/15/2019 + */ +public interface IBuilderProcess extends IBaritoneProcess { + + /** + * Requests a build for the specified schematic, labeled as specified, with the specified origin. + * + * @param name A user-friendly name for the schematic + * @param schematic The object representation of the schematic + * @param origin The origin position of the schematic being built + */ + void build(String name, ISchematic schematic, Vec3i origin); + + /** + * Requests a build for the specified schematic, labeled as specified, with the specified origin. + * + * @param name A user-friendly name for the schematic + * @param schematic The file path of the schematic + * @param origin The origin position of the schematic being built + * @return Whether or not the schematic was able to load from file + */ + boolean build(String name, File schematic, Vec3i origin); +} diff --git a/src/main/java/baritone/utils/ISchematic.java b/src/api/java/baritone/api/utils/ISchematic.java similarity index 56% rename from src/main/java/baritone/utils/ISchematic.java rename to src/api/java/baritone/api/utils/ISchematic.java index 77ba8634..1f2cd874 100644 --- a/src/main/java/baritone/utils/ISchematic.java +++ b/src/api/java/baritone/api/utils/ISchematic.java @@ -15,11 +15,18 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.api.utils; import net.minecraft.block.state.IBlockState; +/** + * Basic representation of a schematic. Provides the dimensions and + * the desired statefor a given position relative to the origin. + * + * @author leijurv + */ public interface ISchematic { + /** * Does the block at this coordinate matter to the schematic? *

@@ -28,20 +35,37 @@ public interface ISchematic { * However, in the case of something like a map art, anything that's below the level of the map art doesn't matter, * so this function should return false in that case. (i.e. it doesn't really have to be air below the art blocks) * - * @param x - * @param y - * @param z - * @return + * @param x The x position of the block, relative to the origin + * @param y The y position of the block, relative to the origin + * @param z The z position of the block, relative to the origin + * @return Whether or not the specified position is within the bounds of this schematic */ default boolean inSchematic(int x, int y, int z) { return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ(); } + /** + * Returns the desired block state at a given (X, Y, Z) position relative to the origin (0, 0, 0). + * + * @param x The x position of the block, relative to the origin + * @param y The y position of the block, relative to the origin + * @param z The z position of the block, relative to the origin + * @return The desired block state at the specified position + */ IBlockState desiredState(int x, int y, int z); + /** + * @return The width (X axis length) of this schematic + */ int widthX(); + /** + * @return The height (Y axis length) of this schematic + */ int heightY(); + /** + * @return The length (Z axis length) of this schematic + */ int lengthZ(); } \ No newline at end of file diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index ec745a27..18f61f7a 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -172,6 +172,7 @@ public class Baritone implements IBaritone { return this.followProcess; } + @Override public BuilderProcess getBuilderProcess() { return this.builderProcess; } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 1ac201e1..cafbeee0 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -22,16 +22,17 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalGetToBlock; +import baritone.api.process.IBuilderProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.ISchematic; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; -import baritone.utils.ISchematic; import baritone.utils.PathingCommandContext; import baritone.utils.Schematic; import net.minecraft.block.state.IBlockState; @@ -54,7 +55,8 @@ import java.util.stream.Collectors; import static baritone.api.pathing.movement.ActionCosts.COST_INF; -public class BuilderProcess extends BaritoneProcessHelper { +public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { + public BuilderProcess(Baritone baritone) { super(baritone); } @@ -67,9 +69,20 @@ public class BuilderProcess extends BaritoneProcessHelper { public boolean build(String schematicFile) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); System.out.println(file + " " + file.exists()); + return build(schematicFile, file, ctx.playerFeet()); + } + @Override + public void build(String name, ISchematic schematic, Vec3i origin) { + this.name = name; + this.schematic = schematic; + this.origin = origin; + } + + @Override + public boolean build(String name, File schematic, Vec3i origin) { NBTTagCompound tag; - try (FileInputStream fileIn = new FileInputStream(file)) { + try (FileInputStream fileIn = new FileInputStream(schematic)) { tag = CompressedStreamTools.readCompressed(fileIn); } catch (IOException e) { e.printStackTrace(); @@ -78,16 +91,10 @@ public class BuilderProcess extends BaritoneProcessHelper { if (tag == null) { return false; } - build(schematicFile, parse(tag), ctx.playerFeet()); + build(name, parse(tag), origin); return true; } - public void build(String name, ISchematic schematic, Vec3i origin) { - this.name = name; - this.schematic = schematic; - this.origin = origin; - } - private static ISchematic parse(NBTTagCompound schematic) { return new Schematic(schematic); } diff --git a/src/main/java/baritone/utils/AirSchematic.java b/src/main/java/baritone/utils/AirSchematic.java index bced26e7..3d70f1b1 100644 --- a/src/main/java/baritone/utils/AirSchematic.java +++ b/src/main/java/baritone/utils/AirSchematic.java @@ -17,6 +17,7 @@ package baritone.utils; +import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; diff --git a/src/main/java/baritone/utils/Schematic.java b/src/main/java/baritone/utils/Schematic.java index 3fef4b1e..0cae99ca 100644 --- a/src/main/java/baritone/utils/Schematic.java +++ b/src/main/java/baritone/utils/Schematic.java @@ -17,6 +17,7 @@ package baritone.utils; +import baritone.api.utils.ISchematic; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; From 0c0bbeff27d0745abe17e9dd328858b193944638 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 16 Jan 2019 12:39:15 -0600 Subject: [PATCH 017/682] Minor AirSchematic access modifier change --- src/main/java/baritone/utils/AirSchematic.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/utils/AirSchematic.java b/src/main/java/baritone/utils/AirSchematic.java index 3d70f1b1..6580b4f8 100644 --- a/src/main/java/baritone/utils/AirSchematic.java +++ b/src/main/java/baritone/utils/AirSchematic.java @@ -22,9 +22,10 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; public class AirSchematic implements ISchematic { - public final int widthX; - public final int heightY; - public final int lengthZ; + + private final int widthX; + private final int heightY; + private final int lengthZ; public AirSchematic(int widthX, int heightY, int lengthZ) { this.widthX = widthX; From aa3833915b3dd6a75649536ffde8e56401178b8d Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 16 Jan 2019 13:45:32 -0600 Subject: [PATCH 018/682] Repackage schematic implementations --- src/main/java/baritone/process/BuilderProcess.java | 2 +- src/main/java/baritone/utils/ExampleBaritoneControl.java | 1 + src/main/java/baritone/utils/{ => schematic}/AirSchematic.java | 2 +- .../java/baritone/utils/{ => schematic}/MapArtSchematic.java | 3 ++- src/main/java/baritone/utils/{ => schematic}/Schematic.java | 2 +- 5 files changed, 6 insertions(+), 4 deletions(-) rename src/main/java/baritone/utils/{ => schematic}/AirSchematic.java (97%) rename src/main/java/baritone/utils/{ => schematic}/MapArtSchematic.java (98%) rename src/main/java/baritone/utils/{ => schematic}/Schematic.java (98%) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index cafbeee0..2d0a157a 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -34,7 +34,7 @@ import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.PathingCommandContext; -import baritone.utils.Schematic; +import baritone.utils.schematic.Schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 6e65c087..d7c3fd71 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -34,6 +34,7 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; import baritone.utils.pathing.SegmentedCalculator; +import baritone.utils.schematic.AirSchematic; import net.minecraft.block.Block; import net.minecraft.client.multiplayer.ChunkProviderClient; import net.minecraft.entity.Entity; diff --git a/src/main/java/baritone/utils/AirSchematic.java b/src/main/java/baritone/utils/schematic/AirSchematic.java similarity index 97% rename from src/main/java/baritone/utils/AirSchematic.java rename to src/main/java/baritone/utils/schematic/AirSchematic.java index 6580b4f8..fd253105 100644 --- a/src/main/java/baritone/utils/AirSchematic.java +++ b/src/main/java/baritone/utils/schematic/AirSchematic.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.utils.schematic; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; diff --git a/src/main/java/baritone/utils/MapArtSchematic.java b/src/main/java/baritone/utils/schematic/MapArtSchematic.java similarity index 98% rename from src/main/java/baritone/utils/MapArtSchematic.java rename to src/main/java/baritone/utils/schematic/MapArtSchematic.java index 711a4ed8..69a46762 100644 --- a/src/main/java/baritone/utils/MapArtSchematic.java +++ b/src/main/java/baritone/utils/schematic/MapArtSchematic.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.utils.schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -25,6 +25,7 @@ import java.util.OptionalInt; import java.util.function.Predicate; public class MapArtSchematic extends Schematic { + private final int[][] heightMap; public MapArtSchematic(NBTTagCompound schematic) { diff --git a/src/main/java/baritone/utils/Schematic.java b/src/main/java/baritone/utils/schematic/Schematic.java similarity index 98% rename from src/main/java/baritone/utils/Schematic.java rename to src/main/java/baritone/utils/schematic/Schematic.java index 0cae99ca..55dfb619 100644 --- a/src/main/java/baritone/utils/Schematic.java +++ b/src/main/java/baritone/utils/schematic/Schematic.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.utils.schematic; import baritone.api.utils.ISchematic; import net.minecraft.block.Block; From cef88cde20793340852dc1d24907dc9e82d85586 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 17 Jan 2019 12:25:48 -0800 Subject: [PATCH 019/682] epic super --- src/main/java/baritone/utils/schematic/MapArtSchematic.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/schematic/MapArtSchematic.java b/src/main/java/baritone/utils/schematic/MapArtSchematic.java index 69a46762..1be13195 100644 --- a/src/main/java/baritone/utils/schematic/MapArtSchematic.java +++ b/src/main/java/baritone/utils/schematic/MapArtSchematic.java @@ -49,7 +49,7 @@ public class MapArtSchematic extends Schematic { } } - private static OptionalInt lastIndexMatching(T[] arr, Predicate predicate) { + private static OptionalInt lastIndexMatching(T[] arr, Predicate predicate) { for (int y = arr.length - 1; y >= 0; y--) { if (predicate.test(arr[y])) { return OptionalInt.of(y); From b005ce8e6b18036802cd0233902194fff504f36c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 17 Jan 2019 18:54:37 -0800 Subject: [PATCH 020/682] mega cancer render cached chunks --- .../launch/mixins/MixinChunkCache.java | 46 +++++++++++++++++++ src/launch/resources/mixins.baritone.json | 1 + src/main/java/baritone/Baritone.java | 7 ++- .../java/baritone/event/GameEventHandler.java | 4 ++ 4 files changed, 54 insertions(+), 4 deletions(-) create mode 100644 src/launch/java/baritone/launch/mixins/MixinChunkCache.java diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkCache.java b/src/launch/java/baritone/launch/mixins/MixinChunkCache.java new file mode 100644 index 00000000..17fefb6d --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinChunkCache.java @@ -0,0 +1,46 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.utils.IPlayerContext; +import net.minecraft.block.state.IBlockState; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.ChunkCache; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(ChunkCache.class) +public class MixinChunkCache { + @Inject( + method = "getBlockState", + at = @At("HEAD"), + cancellable = true + ) + private void getBlockState(BlockPos pos, CallbackInfoReturnable ci) { + Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); + IPlayerContext ctx = baritone.getPlayerContext(); + if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { + ci.setReturnValue(baritone.bsi.get0(pos)); + //ci.setReturnValue(Blocks.DIRT.getDefaultState()); + } + } +} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index 09ebbafd..eab28fdb 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -10,6 +10,7 @@ "client": [ "MixinAnvilChunkLoader", "MixinBlockPos", + "MixinChunkCache", "MixinChunkProviderClient", "MixinChunkProviderServer", "MixinEntity", diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index c3a8e272..3414fdf3 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -29,10 +29,7 @@ import baritone.process.CustomGoalProcess; import baritone.process.FollowProcess; import baritone.process.GetToBlockProcess; import baritone.process.MineProcess; -import baritone.utils.BaritoneAutoTest; -import baritone.utils.ExampleBaritoneControl; -import baritone.utils.InputOverrideHandler; -import baritone.utils.PathingControlManager; +import baritone.utils.*; import baritone.utils.player.PrimaryPlayerContext; import net.minecraft.client.Minecraft; @@ -89,6 +86,8 @@ public class Baritone implements IBaritone { private IPlayerContext playerContext; private WorldProvider worldProvider; + public BlockStateInterface bsi; + Baritone() { this.gameEventHandler = new GameEventHandler(this); } diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index e85c46de..55bf21b7 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -23,6 +23,7 @@ import baritone.api.event.events.type.EventState; import baritone.api.event.listener.IEventBus; import baritone.api.event.listener.IGameEventListener; import baritone.cache.WorldProvider; +import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; @@ -46,6 +47,9 @@ public final class GameEventHandler implements IEventBus, Helper { @Override public final void onTick(TickEvent event) { + try { + baritone.bsi = new BlockStateInterface(baritone.getPlayerContext(), true); + } catch (Exception ex) {} listeners.forEach(l -> l.onTick(event)); } From bc651cb774e20e7b398805348d786f0f5a6099b0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 18 Jan 2019 20:12:40 -0800 Subject: [PATCH 021/682] add todo --- src/main/java/baritone/behavior/MemoryBehavior.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 696e107d..661c5712 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -48,6 +48,8 @@ import java.nio.file.Path; import java.util.*; /** + * doesn't work for horse inventories :^) + * * @author Brady * @since 8/6/2018 */ From aa2e6805682ae25597132d074ff444edff7e844a Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 19 Jan 2019 12:10:21 -0600 Subject: [PATCH 022/682] Remove ManagedPlayerEvent --- .../baritone/api/event/events/ChatEvent.java | 8 +-- .../api/event/events/PlayerUpdateEvent.java | 7 +-- .../api/event/events/RotationMoveEvent.java | 7 +-- .../event/events/type/ManagedPlayerEvent.java | 61 ------------------- .../baritone/launch/mixins/MixinEntity.java | 2 +- .../launch/mixins/MixinEntityLivingBase.java | 2 +- .../launch/mixins/MixinEntityPlayerSP.java | 6 +- 7 files changed, 12 insertions(+), 81 deletions(-) delete mode 100644 src/api/java/baritone/api/event/events/type/ManagedPlayerEvent.java diff --git a/src/api/java/baritone/api/event/events/ChatEvent.java b/src/api/java/baritone/api/event/events/ChatEvent.java index 5ab9f5bb..d91e87b0 100644 --- a/src/api/java/baritone/api/event/events/ChatEvent.java +++ b/src/api/java/baritone/api/event/events/ChatEvent.java @@ -17,22 +17,20 @@ package baritone.api.event.events; -import baritone.api.event.events.type.ManagedPlayerEvent; -import net.minecraft.client.entity.EntityPlayerSP; +import baritone.api.event.events.type.Cancellable; /** * @author Brady * @since 8/1/2018 */ -public final class ChatEvent extends ManagedPlayerEvent.Cancellable { +public final class ChatEvent extends Cancellable { /** * The message being sent */ private final String message; - public ChatEvent(EntityPlayerSP player, String message) { - super(player); + public ChatEvent(String message) { this.message = message; } diff --git a/src/api/java/baritone/api/event/events/PlayerUpdateEvent.java b/src/api/java/baritone/api/event/events/PlayerUpdateEvent.java index 99370552..6ac08bdd 100644 --- a/src/api/java/baritone/api/event/events/PlayerUpdateEvent.java +++ b/src/api/java/baritone/api/event/events/PlayerUpdateEvent.java @@ -18,22 +18,19 @@ package baritone.api.event.events; import baritone.api.event.events.type.EventState; -import baritone.api.event.events.type.ManagedPlayerEvent; -import net.minecraft.client.entity.EntityPlayerSP; /** * @author Brady * @since 8/21/2018 */ -public final class PlayerUpdateEvent extends ManagedPlayerEvent { +public final class PlayerUpdateEvent { /** * The state of the event */ private final EventState state; - public PlayerUpdateEvent(EntityPlayerSP player, EventState state) { - super(player); + public PlayerUpdateEvent(EventState state) { this.state = state; } diff --git a/src/api/java/baritone/api/event/events/RotationMoveEvent.java b/src/api/java/baritone/api/event/events/RotationMoveEvent.java index 790318e0..109061c7 100644 --- a/src/api/java/baritone/api/event/events/RotationMoveEvent.java +++ b/src/api/java/baritone/api/event/events/RotationMoveEvent.java @@ -17,8 +17,6 @@ package baritone.api.event.events; -import baritone.api.event.events.type.ManagedPlayerEvent; -import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -26,7 +24,7 @@ import net.minecraft.entity.EntityLivingBase; * @author Brady * @since 8/21/2018 */ -public final class RotationMoveEvent extends ManagedPlayerEvent { +public final class RotationMoveEvent { /** * The type of event @@ -38,8 +36,7 @@ public final class RotationMoveEvent extends ManagedPlayerEvent { */ private float yaw; - public RotationMoveEvent(EntityPlayerSP player, Type type, float yaw) { - super(player); + public RotationMoveEvent(Type type, float yaw) { this.type = type; this.yaw = yaw; } diff --git a/src/api/java/baritone/api/event/events/type/ManagedPlayerEvent.java b/src/api/java/baritone/api/event/events/type/ManagedPlayerEvent.java deleted file mode 100644 index a3487a67..00000000 --- a/src/api/java/baritone/api/event/events/type/ManagedPlayerEvent.java +++ /dev/null @@ -1,61 +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.event.events.type; - -import net.minecraft.client.entity.EntityPlayerSP; - -/** - * An event that has a reference to a locally managed player. - * - * @author Brady - * @since 10/11/2018 - */ -public class ManagedPlayerEvent { - - protected final EntityPlayerSP player; - - public ManagedPlayerEvent(EntityPlayerSP player) { - this.player = player; - } - - public final EntityPlayerSP getPlayer() { - return this.player; - } - - public static class Cancellable extends ManagedPlayerEvent implements ICancellable { - - /** - * Whether or not this event has been cancelled - */ - private boolean cancelled; - - public Cancellable(EntityPlayerSP player) { - super(player); - } - - @Override - public final void cancel() { - this.cancelled = true; - } - - @Override - public final boolean isCancelled() { - return this.cancelled; - } - } -} diff --git a/src/launch/java/baritone/launch/mixins/MixinEntity.java b/src/launch/java/baritone/launch/mixins/MixinEntity.java index fe498202..83655783 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntity.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntity.java @@ -52,7 +52,7 @@ public class MixinEntity { private void preMoveRelative(float strafe, float up, float forward, float friction, CallbackInfo ci) { // noinspection ConstantConditions if (EntityPlayerSP.class.isInstance(this)) { - this.motionUpdateRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw); + this.motionUpdateRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw); BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.motionUpdateRotationEvent); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java index 1a7d298f..c6d76634 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -55,7 +55,7 @@ public abstract class MixinEntityLivingBase extends Entity { private void preMoveRelative(CallbackInfo ci) { // noinspection ConstantConditions if (EntityPlayerSP.class.isInstance(this)) { - this.jumpRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.JUMP, this.rotationYaw); + this.jumpRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.JUMP, this.rotationYaw); BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index 2f87b72d..5ca3c839 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -45,7 +45,7 @@ public class MixinEntityPlayerSP { cancellable = true ) private void sendChatMessage(String msg, CallbackInfo ci) { - ChatEvent event = new ChatEvent((EntityPlayerSP) (Object) this, msg); + ChatEvent event = new ChatEvent(msg); BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onSendChatMessage(event); if (event.isCancelled()) { ci.cancel(); @@ -62,7 +62,7 @@ public class MixinEntityPlayerSP { ) ) private void onPreUpdate(CallbackInfo ci) { - BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.PRE)); + BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.PRE)); } @Inject( @@ -75,7 +75,7 @@ public class MixinEntityPlayerSP { ) ) private void onPostUpdate(CallbackInfo ci) { - BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST)); + BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST)); } @Redirect( From f5446cc415789cde2d77a5992c1d62f9635d73e0 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 19 Jan 2019 12:12:26 -0600 Subject: [PATCH 023/682] Fix SprintStateEvent --- .../java/baritone/api/event/events/SprintStateEvent.java | 9 +-------- .../java/baritone/launch/mixins/MixinEntityPlayerSP.java | 5 ++--- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/src/api/java/baritone/api/event/events/SprintStateEvent.java b/src/api/java/baritone/api/event/events/SprintStateEvent.java index e7b8d193..6027c79e 100644 --- a/src/api/java/baritone/api/event/events/SprintStateEvent.java +++ b/src/api/java/baritone/api/event/events/SprintStateEvent.java @@ -17,21 +17,14 @@ package baritone.api.event.events; -import baritone.api.event.events.type.ManagedPlayerEvent; -import net.minecraft.client.entity.EntityPlayerSP; - /** * @author Brady * @since 1/18/2019 */ -public class SprintStateEvent extends ManagedPlayerEvent { +public class SprintStateEvent { private Boolean state; - public SprintStateEvent(EntityPlayerSP player) { - super(player); - } - public final void setState(boolean state) { this.state = state; } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index 5ca3c839..48ac8c94 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -98,9 +98,8 @@ public class MixinEntityPlayerSP { ) ) private boolean isKeyDown(KeyBinding keyBinding) { - EntityPlayerSP self = (EntityPlayerSP) (Object) this; - SprintStateEvent event = new SprintStateEvent(self); - BaritoneAPI.getProvider().getBaritoneForPlayer(self).getGameEventHandler().onPlayerSprintState(event); + SprintStateEvent event = new SprintStateEvent(); + BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerSprintState(event); return event.getState() == null ? keyBinding.isKeyDown() : event.getState(); } } From 38c7f226cb4f6ffabfc90aceed289a4ddd4fd208 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 19 Jan 2019 16:36:24 -0800 Subject: [PATCH 024/682] brady is rart --- src/main/java/baritone/behavior/MemoryBehavior.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 661c5712..d371116c 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -109,7 +109,6 @@ public final class MemoryBehavior extends Behavior { } if (p instanceof CPacketCloseWindow) { - updateInventory(); getCurrent().save(); } } @@ -144,7 +143,6 @@ public final class MemoryBehavior extends Behavior { } if (p instanceof SPacketCloseWindow) { - updateInventory(); getCurrent().save(); } } From 1c1fbe83ec68fd365c73aea1713a350b87f2ce2f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 19 Jan 2019 22:12:54 -0800 Subject: [PATCH 025/682] idk lol --- src/main/java/baritone/process/BuilderProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 2d0a157a..cadb5416 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -58,7 +58,7 @@ import static baritone.api.pathing.movement.ActionCosts.COST_INF; public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { public BuilderProcess(Baritone baritone) { - super(baritone); + super(baritone, 0); } private HashSet incorrectPositions; From 39c6d81b9ec59355afaa9e34c7655a17254e9ccd Mon Sep 17 00:00:00 2001 From: babbaj Date: Sun, 20 Jan 2019 06:20:49 -0500 Subject: [PATCH 026/682] Never send chat message when using prefix --- .../utils/ExampleBaritoneControl.java | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 508a5e1b..a207faf8 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -77,6 +77,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { "costs - (debug) all movement costs from current location\n" + "damn - Daniel "; + private static final String COMMAND_PREFIX = "#"; + public ExampleBaritoneControl(Baritone baritone) { super(baritone); } @@ -87,14 +89,17 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return; } String msg = event.getMessage(); - if (Baritone.settings().prefix.get()) { - if (!msg.startsWith("#")) { - return; + if (Baritone.settings().prefix.get()) { + if (msg.startsWith(COMMAND_PREFIX)) { + if (!runCommand(msg.substring(COMMAND_PREFIX.length()))) { + logDirect("Invalid command"); + } + event.cancel(); // always cancel if using prefix + } + } else { + if (runCommand(msg)) { + event.cancel(); } - msg = msg.substring(1); - } - if (runCommand(msg)) { - event.cancel(); } } @@ -121,7 +126,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { for (String line : HELP_MSG.split("\n")) { logDirect(line); } - return false; + return true; } if (msg.contains(" ")) { String[] data = msg.split(" "); From 5ab0bb3c0d32ffc12a7dcc621c42fcbd8cd2de38 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 20 Jan 2019 13:53:55 -0800 Subject: [PATCH 027/682] nice round number --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6bffdc24..f34b651d 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ A Minecraft pathfinder bot. Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), -the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). +the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). Here are some links to help to get started: From 30e30189663490e461d119a56309cbd18107d31b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 20 Jan 2019 15:31:30 -0800 Subject: [PATCH 028/682] trigger brady --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f34b651d..ca5f995b 100644 --- a/README.md +++ b/README.md @@ -7,10 +7,11 @@ [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) -[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.0.0--hotfix--4-brightgreen.svg)](https://impactdevelopment.github.io/) +[![Asuna integration](https://img.shields.io/badge/Asuna%20integration-builder%20branch-brightgreen.svg)](https://github.com/EmotionalLove/Asuna/) +[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.0.0--hotfix--4-green.svg)](https://impactdevelopment.github.io/) [![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-orange.svg)](https://github.com/zeroeightysix/KAMI/) -[![Asuna integration](https://img.shields.io/badge/Asuna%20integration-v1.0.0-orange.svg)](https://github.com/EmotionalLove/Asuna/) -[![Future integration](https://img.shields.io/badge/Future%20integration-%3F%3F%3F-red.svg)](https://futureclient.net/) +[![WWE integration](https://img.shields.io/badge/WWE%20integration-v1.0.0%3F%3F-orange.svg)](https://wweclient.com/) +[![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) A Minecraft pathfinder bot. From 3c6c640f50cafc46a29164befe768fe7e816e125 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 20 Jan 2019 15:41:36 -0800 Subject: [PATCH 029/682] unused --- src/main/java/baritone/behavior/PathingBehavior.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 92eb242e..74cc46ee 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -36,7 +36,6 @@ import baritone.utils.Helper; import baritone.utils.PathRenderer; import baritone.utils.pathing.Favoring; import net.minecraft.util.math.BlockPos; -import net.minecraft.world.chunk.EmptyChunk; import java.util.ArrayList; import java.util.Comparator; From eceba131642d502ef360523c98b465bd28067597 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 20 Jan 2019 16:26:23 -0800 Subject: [PATCH 030/682] diss wwe --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ca5f995b..173ee74a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ [![Asuna integration](https://img.shields.io/badge/Asuna%20integration-builder%20branch-brightgreen.svg)](https://github.com/EmotionalLove/Asuna/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.0.0--hotfix--4-green.svg)](https://impactdevelopment.github.io/) [![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-orange.svg)](https://github.com/zeroeightysix/KAMI/) -[![WWE integration](https://img.shields.io/badge/WWE%20integration-v1.0.0%3F%3F-orange.svg)](https://wweclient.com/) +[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-v1.0.0%3F%3F%20smh%20license%20violations-orange.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) A Minecraft pathfinder bot. From 1753bc18c1f0e2122012985b01b39f2a1be45916 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 21 Jan 2019 23:32:41 -0800 Subject: [PATCH 031/682] forgehax --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 173ee74a..fb096630 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ [![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-orange.svg)](https://github.com/zeroeightysix/KAMI/) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-v1.0.0%3F%3F%20smh%20license%20violations-orange.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) +[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soonâ„¢-red.svg)](https://github.com/fr1kin/ForgeHax) A Minecraft pathfinder bot. From 253d67ce784f2f5a0481c2a5dc440b77470ffeea Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 22 Jan 2019 12:01:06 -0600 Subject: [PATCH 032/682] final final final final --- src/api/java/baritone/api/event/events/SprintStateEvent.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/event/events/SprintStateEvent.java b/src/api/java/baritone/api/event/events/SprintStateEvent.java index 6027c79e..60672801 100644 --- a/src/api/java/baritone/api/event/events/SprintStateEvent.java +++ b/src/api/java/baritone/api/event/events/SprintStateEvent.java @@ -21,7 +21,7 @@ package baritone.api.event.events; * @author Brady * @since 1/18/2019 */ -public class SprintStateEvent { +public final class SprintStateEvent { private Boolean state; From b75f4bf9a922b3d214dad526229d42185139136a Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 22 Jan 2019 13:32:37 -0600 Subject: [PATCH 033/682] Reformat --- src/api/java/baritone/api/process/IBaritoneProcess.java | 4 ++-- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/process/IBaritoneProcess.java b/src/api/java/baritone/api/process/IBaritoneProcess.java index c2eb2f49..01e833c0 100644 --- a/src/api/java/baritone/api/process/IBaritoneProcess.java +++ b/src/api/java/baritone/api/process/IBaritoneProcess.java @@ -25,8 +25,8 @@ import baritone.api.event.events.PathEvent; *

* Differences between a baritone process and a behavior: *

    - *
  • Only one baritone process can be active at a time
  • - *
  • PathingBehavior can only be controlled by a process
  • + *
  • Only one baritone process can be active at a time
  • + *
  • PathingBehavior can only be controlled by a process
  • *
*

* That's it actually diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index a207faf8..245b4e9b 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -89,7 +89,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return; } String msg = event.getMessage(); - if (Baritone.settings().prefix.get()) { + if (Baritone.settings().prefix.get()) { if (msg.startsWith(COMMAND_PREFIX)) { if (!runCommand(msg.substring(COMMAND_PREFIX.length()))) { logDirect("Invalid command"); From 314f2804005785eab4d4685966cc8e4efe11c53c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 22 Jan 2019 17:25:53 -0800 Subject: [PATCH 034/682] pigs --- .../baritone/launch/mixins/MixinEntityPlayerSP.java | 11 +++++++++++ src/main/java/baritone/behavior/LookBehavior.java | 6 ++++++ 2 files changed, 17 insertions(+) diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index 48ac8c94..bbf92011 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -23,6 +23,7 @@ import baritone.api.event.events.ChatEvent; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.SprintStateEvent; import baritone.api.event.events.type.EventState; +import baritone.behavior.LookBehavior; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.player.PlayerCapabilities; @@ -102,4 +103,14 @@ public class MixinEntityPlayerSP { BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerSprintState(event); return event.getState() == null ? keyBinding.isKeyDown() : event.getState(); } + + @Inject( + method = "updateRidden", + at = @At( + value = "HEAD" + ) + ) + private void updateRidden(CallbackInfo cb) { + ((LookBehavior) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getLookBehavior()).pig(); + } } diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 31e76913..c2d0326c 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -95,6 +95,12 @@ public final class LookBehavior extends Behavior implements ILookBehavior { } } + public void pig() { + if (this.target != null) { + ctx.player().rotationYaw = this.target.getYaw(); + } + } + @Override public void onPlayerRotationMove(RotationMoveEvent event) { if (this.target != null && !this.force) { From 863471b5f193e07ed6bff03f97cd8e0cbfd3b355 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 23 Jan 2019 21:25:38 -0800 Subject: [PATCH 035/682] don't create a new bsi for every selection box every tick --- src/main/java/baritone/utils/PathRenderer.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index deca0951..9f07efdf 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -216,8 +216,9 @@ public final class PathRenderer implements Helper { double renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks; double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; + BlockStateInterface bsi = new BlockStateInterface(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext()); // TODO this assumes same dimension between primary baritone and render view? is this safe? positions.forEach(pos -> { - IBlockState state = BlockStateInterface.get(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext(), pos); + IBlockState state = bsi.get0(pos); AxisAlignedBB toDraw; if (state.getBlock().equals(Blocks.AIR)) { toDraw = Blocks.DIRT.getDefaultState().getSelectedBoundingBox(player.world, pos); From 82ab79e915860f848018a53e6dd883a953df468a Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 24 Jan 2019 14:34:18 -0600 Subject: [PATCH 036/682] CLI setup --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index fb096630..4f386e00 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,13 @@ Here are some links to help to get started: ## Command Line On Mac OSX and Linux, use `./gradlew` instead of `gradlew`. +Setting up the Environment: + +``` +$ gradlew setupDecompWorkspace +$ gradlew --refresh-dependencies +``` + Running Baritone: ``` From 6b6f8cadb28835efb5528442d166772d430effa3 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 24 Jan 2019 15:06:01 -0600 Subject: [PATCH 037/682] Image tutorial epic haha --- README.md | 62 ++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 54 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 4f386e00..8877ddf5 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,12 @@ Here are some links to help to get started: # Setup +- Clone or download Baritone + + ![Image](https://i.imgur.com/kbqBtoN.png) + - If you choose to download, make sure you extract the ZIP archive. +- Follow one of the instruction sets below, based on your preference + ## Command Line On Mac OSX and Linux, use `./gradlew` instead of `gradlew`. @@ -45,19 +51,59 @@ Running Baritone: $ gradlew runClient ``` -Building Baritone: +For information on how to build baritone, see [Building Baritone](#building-baritone) + +## 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) + +# Building + +## Command Line + ``` $ gradlew build ``` -To replace out Impact 4.4's Baritone build with a customized one, switch to the `impact4.4-compat` branch, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). +## IntelliJ -## IntelliJ's Gradle UI -- Open the project in IntelliJ as a Gradle project -- Run the Gradle tasks `setupDecompWorkspace` then `genIntellijRuns` -- Refresh the Gradle project (or, to be safe, just restart IntelliJ) -- Select the "Minecraft Client" launch config -- In `Edit Configurations...` you may need to select `baritone_launch` for `Use classpath of module:`. +- Navigate to the gradle tasks on the right tab as follows + + ![Image](https://i.imgur.com/PE6r9iN.png) + +- Right click on **build** and press **Run** + +## Artifacts + +Building Baritone will result in 3 artifacts created in the ``dist`` directory. + +- **API**: Only the non-api packages are obfuscated. This should be used in environments where other mods would like to use Baritone's features. +- **Standalone**: Everything is obfuscated. This should be used in environments where there are no other mods present that would like to use Baritone's features. +- **Unoptimized**: Nothing is obfuscated. This shouldn't be used ever in production. + +## More Info +To replace out Impact 4.4's Baritone build with a customized one, switch to the `impact4.4-compat` branch, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). # Chat control [Defined Here](src/main/java/baritone/utils/ExampleBaritoneControl.java) From 772d5fb0ccf332f2d52ada6d094601825f0a3723 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 24 Jan 2019 15:09:04 -0600 Subject: [PATCH 038/682] SETUP.md --- README.md | 76 +----------------------------------------------------- SETUP.md | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 75 deletions(-) create mode 100644 SETUP.md diff --git a/README.md b/README.md index 8877ddf5..c24681e0 100644 --- a/README.md +++ b/README.md @@ -29,81 +29,7 @@ Here are some links to help to get started: # Setup -- Clone or download Baritone - - ![Image](https://i.imgur.com/kbqBtoN.png) - - If you choose to download, make sure you extract the ZIP archive. -- Follow one of the instruction sets below, based on your preference - -## Command Line -On Mac OSX and Linux, use `./gradlew` instead of `gradlew`. - -Setting up the Environment: - -``` -$ gradlew setupDecompWorkspace -$ gradlew --refresh-dependencies -``` - -Running Baritone: - -``` -$ gradlew runClient -``` - -For information on how to build baritone, see [Building Baritone](#building-baritone) - -## 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) - -# Building - -## Command Line - -``` -$ gradlew build -``` - -## IntelliJ - -- Navigate to the gradle tasks on the right tab as follows - - ![Image](https://i.imgur.com/PE6r9iN.png) - -- Right click on **build** and press **Run** - -## Artifacts - -Building Baritone will result in 3 artifacts created in the ``dist`` directory. - -- **API**: Only the non-api packages are obfuscated. This should be used in environments where other mods would like to use Baritone's features. -- **Standalone**: Everything is obfuscated. This should be used in environments where there are no other mods present that would like to use Baritone's features. -- **Unoptimized**: Nothing is obfuscated. This shouldn't be used ever in production. - -## More Info -To replace out Impact 4.4's Baritone build with a customized one, switch to the `impact4.4-compat` branch, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). +Information on how to setup baritone can be found [here](SETUP.md). # Chat control [Defined Here](src/main/java/baritone/utils/ExampleBaritoneControl.java) diff --git a/SETUP.md b/SETUP.md new file mode 100644 index 00000000..777b34da --- /dev/null +++ b/SETUP.md @@ -0,0 +1,77 @@ +# Setup + +- Clone or download Baritone + + ![Image](https://i.imgur.com/kbqBtoN.png) + - If you choose to download, make sure you extract the ZIP archive. +- Follow one of the instruction sets below, based on your preference + +## Command Line +On Mac OSX and Linux, use `./gradlew` instead of `gradlew`. + +Setting up the Environment: + +``` +$ gradlew setupDecompWorkspace +$ gradlew --refresh-dependencies +``` + +Running Baritone: + +``` +$ gradlew runClient +``` + +For information on how to build baritone, see [Building Baritone](#building-baritone) + +## 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) + +# Building + +## Command Line + +``` +$ gradlew build +``` + +## IntelliJ + +- Navigate to the gradle tasks on the right tab as follows + + ![Image](https://i.imgur.com/PE6r9iN.png) + +- Right click on **build** and press **Run** + +## Artifacts + +Building Baritone will result in 3 artifacts created in the ``dist`` directory. + +- **API**: Only the non-api packages are obfuscated. This should be used in environments where other mods would like to use Baritone's features. +- **Standalone**: Everything is obfuscated. This should be used in environments where there are no other mods present that would like to use Baritone's features. +- **Unoptimized**: Nothing is obfuscated. This shouldn't be used ever in production. + +## More Info +To replace out Impact 4.4's Baritone build with a customized one, switch to the `impact4.4-compat` branch, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). From aba48cca53a2007934fa6066270b6bf422cb6960 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 24 Jan 2019 15:21:16 -0600 Subject: [PATCH 039/682] Organize some markdown files --- IMPACT.md | 1 - INSTALL.md | 12 ++---------- README.md | 6 ++---- SETUP.md | 2 ++ 4 files changed, 6 insertions(+), 15 deletions(-) delete mode 100644 IMPACT.md diff --git a/IMPACT.md b/IMPACT.md deleted file mode 100644 index cc12252e..00000000 --- a/IMPACT.md +++ /dev/null @@ -1 +0,0 @@ -Impact 4.4 is out. See INSTALL.md \ No newline at end of file diff --git a/INSTALL.md b/INSTALL.md index 9df3d6bf..f05e0280 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,11 +1,10 @@ # Integration between Baritone and Impact Impact 4.4 has Baritone included. -These instructions apply to Impact 4.3 (and potentially other hacked clients). +These instructions apply to Impact 4.3 (and potentially other "hacked clients"). To run Baritone on Vanilla, just follow the instructions in the README (it's `./gradlew runClient`). - ## An Introduction There are some basic steps to getting Baritone setup with Impact. - Acquiring a build of Baritone @@ -26,14 +25,7 @@ Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMe The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone . && docker run --rm cabaletta/baritone cat /code/dist/checksums.txt` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). ### Building Baritone yourself -There are a few steps to this -- Clone this repository -- Setup the project as instructed in the README -- Run the ``build`` gradle task. You can either do this using IntelliJ's gradle UI or through a -command line - - Windows: ``gradlew build`` - - Mac/Linux: ``./gradlew build`` -- The build should be exported into ``/build/libs/baritone-X.Y.Z.jar`` +You can either build Baritone through a command line or through IntelliJ's UI, information on that can be found [here](SETUP.md#building). ## Placing Baritone in the libraries directory ``/libraries`` is a neat directory in your Minecraft Installation Directory diff --git a/README.md b/README.md index c24681e0..df1422cc 100644 --- a/README.md +++ b/README.md @@ -25,12 +25,10 @@ Here are some links to help to get started: - [Features](FEATURES.md) +- [Setup](SETUP.md) + - [Installation](INSTALL.md) -# Setup - -Information on how to setup baritone can be found [here](SETUP.md). - # Chat control [Defined Here](src/main/java/baritone/utils/ExampleBaritoneControl.java) diff --git a/SETUP.md b/SETUP.md index 777b34da..6400990d 100644 --- a/SETUP.md +++ b/SETUP.md @@ -51,6 +51,8 @@ For information on how to build baritone, see [Building Baritone](#building-bari # Building +Make sure that you have properly [setup](#setup) the environment before trying to build it. + ## Command Line ``` From b1452c714ae4cd4ef94f92cfef36193b1d9b4f20 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 24 Jan 2019 16:06:53 -0800 Subject: [PATCH 040/682] b a d g e s --- FEATURES.md | 2 +- README.md | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/FEATURES.md b/FEATURES.md index cd2a90fe..e3714a8c 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -11,6 +11,7 @@ - **Avoiding dangerous blocks** Obviously, it knows not to walk through fire or on magma, not to corner over lava (that deals some damage), not to break any blocks touching a liquid (it might drown), etc. - **Parkour** Sprint jumping over 1, 2, or 3 block gaps - **Parkour place** Sprint jumping over a 3 block gap and placing the block to land on while executing the jump. It's really cool. +- **Pigs** It can sort of control pigs. I wouldn't rely on it though. # Pathing method Baritone uses A*, with some modifications: @@ -46,7 +47,6 @@ Things it doesn't have yet See issues for more. Things it may not ever have, from most likely to least likely =( -- Pigs - Boats - Horses (2x3 path instead of 1x2) - Elytra diff --git a/README.md b/README.md index df1422cc..d017113b 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,12 @@ [![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) +[![Issues](https://img.shields.io/github/issues/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues/) +[![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/) +![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg) [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) +[![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) +[![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Asuna integration](https://img.shields.io/badge/Asuna%20integration-builder%20branch-brightgreen.svg)](https://github.com/EmotionalLove/Asuna/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.0.0--hotfix--4-green.svg)](https://impactdevelopment.github.io/) [![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-orange.svg)](https://github.com/zeroeightysix/KAMI/) From 4f355ed4a25798f6862b62c54c5fdd093fea2ace Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 24 Jan 2019 16:10:21 -0800 Subject: [PATCH 041/682] two more --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index d017113b..ebca5b20 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,9 @@ [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-v1.0.0%3F%3F%20smh%20license%20violations-orange.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soonâ„¢-red.svg)](https://github.com/fr1kin/ForgeHax) +[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com) +[![forthebadge](https://forthebadge.com/images/badges/mom-made-pizza-rolls.svg)](http://forthebadge.com) + A Minecraft pathfinder bot. From fca5457ab93a040cbcfaa584e606c663395aba4d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 24 Jan 2019 16:25:35 -0800 Subject: [PATCH 042/682] gotta have closed issues too --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ebca5b20..df2f9394 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) [![Issues](https://img.shields.io/github/issues/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues/) +[![GitHub issues-closed](https://img.shields.io/github/issues-closed/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues?q=is%3Aissue+is%3Aclosed) [![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/) ![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg) [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) From bb4188307046c0daf54688196cd7d7a45d5733e4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 24 Jan 2019 16:31:12 -0800 Subject: [PATCH 043/682] did someone say add another badge --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index df2f9394..8fa78e8c 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ [![Issues](https://img.shields.io/github/issues/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues/) [![GitHub issues-closed](https://img.shields.io/github/issues-closed/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues?q=is%3Aissue+is%3Aclosed) [![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/) +![Code size](https://img.shields.io/github/languages/code-size/cabaletta/baritone.svg) ![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg) [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) From f274f5a0eface7f29bdab3ecf7d7c2c5836902e4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 24 Jan 2019 21:00:44 -0800 Subject: [PATCH 044/682] windows is epic gamer --- src/main/java/baritone/cache/WorldProvider.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index 83cf460d..fe2efa4e 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -24,6 +24,7 @@ import baritone.utils.accessor.IAnvilChunkLoader; import baritone.utils.accessor.IChunkProviderServer; import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.world.WorldServer; +import org.apache.commons.lang3.SystemUtils; import java.io.File; import java.io.FileOutputStream; @@ -76,7 +77,11 @@ public class WorldProvider implements IWorldProvider, Helper { directory = new File(directory, "baritone"); readme = directory; } else { // Otherwise, the server must be remote... - directory = new File(Baritone.getDir(), mc.getCurrentServerData().serverIP); + String folderName = mc.getCurrentServerData().serverIP; + if (SystemUtils.IS_OS_WINDOWS) { + folderName = folderName.replace(":", "_"); + } + directory = new File(Baritone.getDir(), folderName); readme = Baritone.getDir(); } From 2a244f1e538353a889d50d7f4cfee80e1383d8e7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 25 Jan 2019 11:51:54 -0800 Subject: [PATCH 045/682] those were a little over the top --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 8fa78e8c..b4b7187d 100644 --- a/README.md +++ b/README.md @@ -20,8 +20,6 @@ [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-v1.0.0%3F%3F%20smh%20license%20violations-orange.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soonâ„¢-red.svg)](https://github.com/fr1kin/ForgeHax) -[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com) -[![forthebadge](https://forthebadge.com/images/badges/mom-made-pizza-rolls.svg)](http://forthebadge.com) A Minecraft pathfinder bot. From 396eaa148caf22703d633d0fc150534b16e8c2bd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 26 Jan 2019 21:33:41 -0800 Subject: [PATCH 046/682] remove extra newline --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index b4b7187d..555c2c07 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,6 @@ [![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soonâ„¢-red.svg)](https://github.com/fr1kin/ForgeHax) - A Minecraft pathfinder bot. Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. From 8d7841b069cbc0638cc3e8b8b6862419fb73b6c6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 27 Jan 2019 19:34:12 -0800 Subject: [PATCH 047/682] privatize --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 245b4e9b..e26a352f 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -103,7 +103,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } - public boolean runCommand(String msg0) { + private boolean runCommand(String msg0) { String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL PathingBehavior pathingBehavior = baritone.getPathingBehavior(); CustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); From bf78a4dfad337a0966918302b78e81e9de77b07f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 10:32:28 -0800 Subject: [PATCH 048/682] whoops forgot that --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index e26a352f..281351bd 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -103,7 +103,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } - private boolean runCommand(String msg0) { + public boolean runCommand(String msg0) { // you may think this can be private, but impcat calls it from .b =) String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL PathingBehavior pathingBehavior = baritone.getPathingBehavior(); CustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); From b0c475239726a68ad14ab739b7831efeaf0e5b70 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 10:41:28 -0800 Subject: [PATCH 049/682] finalize all settings --- src/api/java/baritone/api/Settings.java | 188 ++++++++++++------------ 1 file changed, 94 insertions(+), 94 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 89716a38..a069d76b 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -33,67 +33,67 @@ import java.util.function.Consumer; * * @author leijurv */ -public class Settings { +public final class Settings { /** * Allow Baritone to break blocks */ - public Setting allowBreak = new Setting<>(true); + public final Setting allowBreak = new Setting<>(true); /** * Allow Baritone to sprint */ - public Setting allowSprint = new Setting<>(true); + public final Setting allowSprint = new Setting<>(true); /** * Allow Baritone to place blocks */ - public Setting allowPlace = new Setting<>(true); + public final Setting allowPlace = new Setting<>(true); /** * Allow Baritone to move items in your inventory to your hotbar */ - public Setting allowInventory = new Setting<>(false); + public final Setting allowInventory = new Setting<>(false); /** * It doesn't actually take twenty ticks to place a block, this cost is so high * because we want to generally conserve blocks which might be limited */ - public Setting blockPlacementPenalty = new Setting<>(20D); + public final Setting blockPlacementPenalty = new Setting<>(20D); /** * This is just a tiebreaker to make it less likely to break blocks if it can avoid it. * For example, fire has a break cost of 0, this makes it nonzero, so all else being equal * it will take an otherwise equivalent route that doesn't require it to put out fire. */ - public Setting blockBreakAdditionalPenalty = new Setting<>(2D); + public final Setting blockBreakAdditionalPenalty = new Setting<>(2D); /** * Additional penalty for hitting the space bar (ascend, pillar, or parkour) beacuse it uses hunger */ - public Setting jumpPenalty = new Setting<>(2D); + public final Setting jumpPenalty = new Setting<>(2D); /** * Walking on water uses up hunger really quick, so penalize it */ - public Setting walkOnWaterOnePenalty = new Setting<>(5D); + public final Setting walkOnWaterOnePenalty = new Setting<>(5D); /** * Allow Baritone to fall arbitrary distances and place a water bucket beneath it. * Reliability: questionable. */ - public Setting allowWaterBucketFall = new Setting<>(true); + public final Setting allowWaterBucketFall = new Setting<>(true); /** * Allow Baritone to assume it can walk on still water just like any other block. * This functionality is assumed to be provided by a separate library that might have imported Baritone. */ - public Setting assumeWalkOnWater = new Setting<>(false); + public final Setting assumeWalkOnWater = new Setting<>(false); /** * Assume step functionality; don't jump on an Ascend. */ - public Setting assumeStep = new Setting<>(false); + public final Setting assumeStep = new Setting<>(false); /** * Assume safe walk functionality; don't sneak on a backplace traverse. @@ -102,14 +102,14 @@ public class Settings { * it won't sneak right click, it'll just right click, which means it'll open the chest instead of placing * against it. That's why this defaults to off. */ - public Setting assumeSafeWalk = new Setting<>(false); + public final Setting assumeSafeWalk = new Setting<>(false); /** * If true, parkour is allowed to make jumps when standing on blocks at the maximum height, so player feet is y=256 *

* Defaults to false because this fails on NCP */ - public Setting allowJumpAt256 = new Setting<>(false); + public final Setting allowJumpAt256 = new Setting<>(false); /** * Allow descending diagonally @@ -118,12 +118,12 @@ public class Settings { *

* For a generic "take some risks" mode I'd turn on this one, parkour, and parkour place. */ - public Setting allowDiagonalDescend = new Setting<>(false); + public final Setting allowDiagonalDescend = new Setting<>(false); /** * Blocks that Baritone is allowed to place (as throwaway, for sneak bridging, pillaring, etc.) */ - public Setting> acceptableThrowawayItems = new Setting<>(new ArrayList<>(Arrays.asList( + public final Setting> acceptableThrowawayItems = new Setting<>(new ArrayList<>(Arrays.asList( Item.getItemFromBlock(Blocks.DIRT), Item.getItemFromBlock(Blocks.COBBLESTONE), Item.getItemFromBlock(Blocks.NETHERRACK) @@ -133,30 +133,30 @@ public class Settings { * Enables some more advanced vine features. They're honestly just gimmicks and won't ever be needed in real * pathing scenarios. And they can cause Baritone to get trapped indefinitely in a strange scenario. */ - public Setting allowVines = new Setting<>(false); + public final Setting allowVines = new Setting<>(false); /** * Slab behavior is complicated, disable this for higher path reliability. Leave enabled if you have bottom slabs * everywhere in your base. */ - public Setting allowWalkOnBottomSlab = new Setting<>(true); + public final Setting allowWalkOnBottomSlab = new Setting<>(true); /** * You know what it is *

* But it's very unreliable and falls off when cornering like all the time so. */ - public Setting allowParkour = new Setting<>(false); + public final Setting allowParkour = new Setting<>(false); /** * Like parkour, but even more unreliable! */ - public Setting allowParkourPlace = new Setting<>(false); + public final Setting allowParkourPlace = new Setting<>(false); /** * For example, if you have Mining Fatigue or Haste, adjust the costs of breaking blocks accordingly. */ - public Setting considerPotionEffects = new Setting<>(true); + public final Setting considerPotionEffects = new Setting<>(true); /** * This is the big A* setting. @@ -173,63 +173,63 @@ public class Settings { *

* Finding the optimal path is worth it, so it's the default. */ - public Setting costHeuristic = new Setting<>(3.563); + public final Setting costHeuristic = new Setting<>(3.563); // a bunch of obscure internal A* settings that you probably don't want to change /** * The maximum number of times it will fetch outside loaded or cached chunks before assuming that * pathing has reached the end of the known area, and should therefore stop. */ - public Setting pathingMaxChunkBorderFetch = new Setting<>(50); + public final Setting pathingMaxChunkBorderFetch = new Setting<>(50); /** * Set to 1.0 to effectively disable this feature * * @see Issue #18 */ - public Setting backtrackCostFavoringCoefficient = new Setting<>(0.5); + public final Setting backtrackCostFavoringCoefficient = new Setting<>(0.5); /** * Toggle the following 4 settings *

* They have a noticable performance impact, so they default off */ - public Setting avoidance = new Setting<>(false); + public final Setting avoidance = new Setting<>(false); /** * Set to 1.0 to effectively disable this feature *

* Set below 1.0 to go out of your way to walk near mob spawners */ - public Setting mobSpawnerAvoidanceCoefficient = new Setting<>(2.0); + public final Setting mobSpawnerAvoidanceCoefficient = new Setting<>(2.0); - public Setting mobSpawnerAvoidanceRadius = new Setting<>(16); + public final Setting mobSpawnerAvoidanceRadius = new Setting<>(16); /** * Set to 1.0 to effectively disable this feature *

* Set below 1.0 to go out of your way to walk near mobs */ - public Setting mobAvoidanceCoefficient = new Setting<>(1.5); + public final Setting mobAvoidanceCoefficient = new Setting<>(1.5); - public Setting mobAvoidanceRadius = new Setting<>(8); + public final Setting mobAvoidanceRadius = new Setting<>(8); /** * When running a goto towards a container block (chest, ender chest, furnace, etc), * right click and open it once you arrive. */ - public Setting rightClickContainerOnArrival = new Setting<>(true); + public final Setting rightClickContainerOnArrival = new Setting<>(true); /** * When running a goto towards a nether portal block, walk all the way into the portal * instead of stopping one block before. */ - public Setting enterPortal = new Setting<>(true); + public final Setting enterPortal = new Setting<>(true); /** * Don't repropagate cost improvements below 0.01 ticks. They're all just floating point inaccuracies, * and there's no point. */ - public Setting minimumImprovementRepropagation = new Setting<>(true); + public final Setting minimumImprovementRepropagation = new Setting<>(true); /** * After calculating a path (potentially through cached chunks), artificially cut it off to just the part that is @@ -237,67 +237,67 @@ public class Settings { * * @see Issue #144 */ - public Setting cutoffAtLoadBoundary = new Setting<>(false); + public final Setting cutoffAtLoadBoundary = new Setting<>(false); /** * If a movement's cost increases by more than this amount between calculation and execution (due to changes * in the environment / world), cancel and recalculate */ - public Setting maxCostIncrease = new Setting<>(10D); + public final Setting maxCostIncrease = new Setting<>(10D); /** * Stop 5 movements before anything that made the path COST_INF. * For example, if lava has spread across the path, don't walk right up to it then recalculate, it might * still be spreading lol */ - public Setting costVerificationLookahead = new Setting<>(5); + public final Setting costVerificationLookahead = new Setting<>(5); /** * Static cutoff factor. 0.9 means cut off the last 10% of all paths, regardless of chunk load state */ - public Setting pathCutoffFactor = new Setting<>(0.9); + public final Setting pathCutoffFactor = new Setting<>(0.9); /** * Only apply static cutoff for paths of at least this length (in terms of number of movements) */ - public Setting pathCutoffMinimumLength = new Setting<>(30); + public final Setting pathCutoffMinimumLength = new Setting<>(30); /** * Start planning the next path once the remaining movements tick estimates sum up to less than this value */ - public Setting planningTickLookAhead = new Setting<>(150); + public final Setting planningTickLookAhead = new Setting<>(150); /** * Default size of the Long2ObjectOpenHashMap used in pathing */ - public Setting pathingMapDefaultSize = new Setting<>(1024); + public final Setting pathingMapDefaultSize = new Setting<>(1024); /** * Load factor coefficient for the Long2ObjectOpenHashMap used in pathing *

* Decrease for faster map operations, but higher memory usage */ - public Setting pathingMapLoadFactor = new Setting<>(0.75f); + public final Setting pathingMapLoadFactor = new Setting<>(0.75f); /** * How far are you allowed to fall onto solid ground (without a water bucket)? * 3 won't deal any damage. But if you just want to get down the mountain quickly and you have * Feather Falling IV, you might set it a bit higher, like 4 or 5. */ - public Setting maxFallHeightNoWater = new Setting<>(3); + public final Setting maxFallHeightNoWater = new Setting<>(3); /** * How far are you allowed to fall onto solid ground (with a water bucket)? * It's not that reliable, so I've set it below what would kill an unarmored player (23) */ - public Setting maxFallHeightBucket = new Setting<>(20); + public final Setting maxFallHeightBucket = new Setting<>(20); /** * Is it okay to sprint through a descend followed by a diagonal? * The player overshoots the landing, but not enough to fall off. And the diagonal ensures that there isn't * lava or anything that's !canWalkInto in that space, so it's technically safe, just a little sketchy. */ - public Setting allowOvershootDiagonalDescend = new Setting<>(true); + public final Setting allowOvershootDiagonalDescend = new Setting<>(true); /** * If your goal is a GoalBlock in an unloaded chunk, assume it's far enough away that the Y coord @@ -306,131 +306,131 @@ public class Settings { * of considering the Y coord. The reasoning is that if your X and Z are 10,000 blocks away, * your Y coordinate's accuracy doesn't matter at all until you get much much closer. */ - public Setting simplifyUnloadedYCoord = new Setting<>(true); + public final Setting simplifyUnloadedYCoord = new Setting<>(true); /** * If a movement takes this many ticks more than its initial cost estimate, cancel it */ - public Setting movementTimeoutTicks = new Setting<>(100); + public final Setting movementTimeoutTicks = new Setting<>(100); /** * Pathing ends after this amount of time, but only if a path has been found *

* If no valid path (length above the minimum) has been found, pathing continues up until the failure timeout */ - public Setting primaryTimeoutMS = new Setting<>(500L); + public final Setting primaryTimeoutMS = new Setting<>(500L); /** * Pathing can never take longer than this, even if that means failing to find any path at all */ - public Setting failureTimeoutMS = new Setting<>(2000L); + public final Setting failureTimeoutMS = new Setting<>(2000L); /** * Planning ahead while executing a segment ends after this amount of time, but only if a path has been found *

* If no valid path (length above the minimum) has been found, pathing continues up until the failure timeout */ - public Setting planAheadPrimaryTimeoutMS = new Setting<>(4000L); + public final Setting planAheadPrimaryTimeoutMS = new Setting<>(4000L); /** * Planning ahead while executing a segment can never take longer than this, even if that means failing to find any path at all */ - public Setting planAheadFailureTimeoutMS = new Setting<>(5000L); + public final Setting planAheadFailureTimeoutMS = new Setting<>(5000L); /** * For debugging, consider nodes much much slower */ - public Setting slowPath = new Setting<>(false); + public final Setting slowPath = new Setting<>(false); /** * Milliseconds between each node */ - public Setting slowPathTimeDelayMS = new Setting<>(100L); + public final Setting slowPathTimeDelayMS = new Setting<>(100L); /** * The alternative timeout number when slowPath is on */ - public Setting slowPathTimeoutMS = new Setting<>(40000L); + public final Setting slowPathTimeoutMS = new Setting<>(40000L); /** * The big one. Download all chunks in simplified 2-bit format and save them for better very-long-distance pathing. */ - public Setting chunkCaching = new Setting<>(true); + public final Setting chunkCaching = new Setting<>(true); /** * On save, delete from RAM any cached regions that are more than 1024 blocks away from the player *

* Temporarily disabled, see issue #248 */ - public Setting pruneRegionsFromRAM = new Setting<>(false); + public final Setting pruneRegionsFromRAM = new Setting<>(false); /** * Print all the debug messages to chat */ - public Setting chatDebug = new Setting<>(true); + public final Setting chatDebug = new Setting<>(true); /** * Allow chat based control of Baritone. Most likely should be disabled when Baritone is imported for use in * something else */ - public Setting chatControl = new Setting<>(true); + public final Setting chatControl = new Setting<>(true); /** * A second override over chatControl to force it on */ - public Setting removePrefix = new Setting<>(false); + public final Setting removePrefix = new Setting<>(false); /** * Render the path */ - public Setting renderPath = new Setting<>(true); + public final Setting renderPath = new Setting<>(true); /** * Render the goal */ - public Setting renderGoal = new Setting<>(true); + public final Setting renderGoal = new Setting<>(true); /** * Ignore depth when rendering the goal */ - public Setting renderGoalIgnoreDepth = new Setting<>(true); + public final Setting renderGoalIgnoreDepth = new Setting<>(true); /** * Renders X/Z type Goals with the vanilla beacon beam effect. Combining this with * {@link #renderGoalIgnoreDepth} will cause strange render clipping. */ - public Setting renderGoalXZBeacon = new Setting<>(false); + public final Setting renderGoalXZBeacon = new Setting<>(false); /** * Ignore depth when rendering the selection boxes (to break, to place, to walk into) */ - public Setting renderSelectionBoxesIgnoreDepth = new Setting<>(true); + public final Setting renderSelectionBoxesIgnoreDepth = new Setting<>(true); /** * Ignore depth when rendering the path */ - public Setting renderPathIgnoreDepth = new Setting<>(true); + public final Setting renderPathIgnoreDepth = new Setting<>(true); /** * Line width of the path when rendered, in pixels */ - public Setting pathRenderLineWidthPixels = new Setting<>(5F); + public final Setting pathRenderLineWidthPixels = new Setting<>(5F); /** * Line width of the goal when rendered, in pixels */ - public Setting goalRenderLineWidthPixels = new Setting<>(3F); + public final Setting goalRenderLineWidthPixels = new Setting<>(3F); /** * Start fading out the path at 20 movements ahead, and stop rendering it entirely 30 movements ahead. * Improves FPS. */ - public Setting fadePath = new Setting<>(false); + public final Setting fadePath = new Setting<>(false); /** * Move without having to force the client-sided rotations */ - public Setting freeLook = new Setting<>(true); + public final Setting freeLook = new Setting<>(true); /** * Will cause some minor behavioral differences to ensure that Baritone works on anticheats. @@ -438,43 +438,43 @@ public class Settings { * At the moment this will silently set the player's rotations when using freeLook so you're not sprinting in * directions other than forward, which is picken up by more "advanced" anticheats like AAC, but not NCP. */ - public Setting antiCheatCompatibility = new Setting<>(true); + public final Setting antiCheatCompatibility = new Setting<>(true); /** * Exclusively use cached chunks for pathing */ - public Setting pathThroughCachedOnly = new Setting<>(false); + public final Setting pathThroughCachedOnly = new Setting<>(false); /** * Whether or not to use the "#" command prefix */ - public Setting prefix = new Setting<>(false); + public final Setting prefix = new Setting<>(false); /** * Don't stop walking forward when you need to break blocks in your way */ - public Setting walkWhileBreaking = new Setting<>(true); + public final Setting walkWhileBreaking = new Setting<>(true); /** * If we are more than 500 movements into the current path, discard the oldest segments, as they are no longer useful */ - public Setting maxPathHistoryLength = new Setting<>(300); + public final Setting maxPathHistoryLength = new Setting<>(300); /** * If the current path is too long, cut off this many movements from the beginning. */ - public Setting pathHistoryCutoffAmount = new Setting<>(50); + public final Setting pathHistoryCutoffAmount = new Setting<>(50); /** * Rescan for the goal once every 5 ticks. * Set to 0 to disable. */ - public Setting mineGoalUpdateInterval = new Setting<>(5); + public final Setting mineGoalUpdateInterval = new Setting<>(5); /** * While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)? */ - public Setting mineScanDroppedItems = new Setting<>(true); + public final Setting mineScanDroppedItems = new Setting<>(true); /** * Cancel the current path if the goal has changed, and the path originally ended in the goal but doesn't anymore. @@ -489,54 +489,54 @@ public class Settings { *

* Also on cosmic prisons this should be set to true since you don't actually mine the ore it just gets replaced with stone. */ - public Setting cancelOnGoalInvalidation = new Setting<>(true); + public final Setting cancelOnGoalInvalidation = new Setting<>(true); /** * The "axis" command (aka GoalAxis) will go to a axis, or diagonal axis, at this Y level. */ - public Setting axisHeight = new Setting<>(120); + public final Setting axisHeight = new Setting<>(120); /** * Allow MineBehavior to use X-Ray to see where the ores are. Turn this option off to force it to mine "legit" * where it will only mine an ore once it can actually see it, so it won't do or know anything that a normal player * couldn't. If you don't want it to look like you're X-Raying, turn this off */ - public Setting legitMine = new Setting<>(false); + public final Setting legitMine = new Setting<>(false); /** * What Y level to go to for legit strip mining */ - public Setting legitMineYLevel = new Setting<>(11); + public final Setting legitMineYLevel = new Setting<>(11); /** * When mining block of a certain type, try to mine two at once instead of one. * If the block above is also a goal block, set GoalBlock instead of GoalTwoBlocks * If the block below is also a goal block, set GoalBlock to the position one down instead of GoalTwoBlocks */ - public Setting forceInternalMining = new Setting<>(true); + public final Setting forceInternalMining = new Setting<>(true); /** * Modification to the previous setting, only has effect if forceInternalMining is true * If true, only apply the previous setting if the block adjacent to the goal isn't air. */ - public Setting internalMiningAirException = new Setting<>(true); + public final Setting internalMiningAirException = new Setting<>(true); /** * The actual GoalNear is set this distance away from the entity you're following *

* For example, set followOffsetDistance to 5 and followRadius to 0 to always stay precisely 5 blocks north of your follow target. */ - public Setting followOffsetDistance = new Setting<>(0D); + public final Setting followOffsetDistance = new Setting<>(0D); /** * The actual GoalNear is set in this direction from the entity you're following. This value is in degrees. */ - public Setting followOffsetDirection = new Setting<>(0F); + public final Setting followOffsetDirection = new Setting<>(0F); /** * The radius (for the GoalNear) of how close to your target position you actually have to be */ - public Setting followRadius = new Setting<>(3); + public final Setting followRadius = new Setting<>(3); /** * Cached chunks (regardless of if they're in RAM or saved to disk) expire and are deleted after this number of seconds @@ -558,54 +558,54 @@ public class Settings { * has to build up that cache from scratch. But after it's gone through an area just once, the next time will have zero * backtracking, since the entire area is now known and cached. */ - public Setting cachedChunksExpirySeconds = new Setting<>(-1L); + public final Setting cachedChunksExpirySeconds = new Setting<>(-1L); /** * The function that is called when Baritone will log to chat. This function can be added to * via {@link Consumer#andThen(Consumer)} or it can completely be overriden via setting * {@link Setting#value}; */ - public Setting> logger = new Setting<>(Minecraft.getMinecraft().ingameGUI.getChatGUI()::printChatMessage); + public final Setting> logger = new Setting<>(Minecraft.getMinecraft().ingameGUI.getChatGUI()::printChatMessage); /** * The color of the current path */ - public Setting colorCurrentPath = new Setting<>(Color.RED); + public final Setting colorCurrentPath = new Setting<>(Color.RED); /** * The color of the next path */ - public Setting colorNextPath = new Setting<>(Color.MAGENTA); + public final Setting colorNextPath = new Setting<>(Color.MAGENTA); /** * The color of the blocks to break */ - public Setting colorBlocksToBreak = new Setting<>(Color.RED); + public final Setting colorBlocksToBreak = new Setting<>(Color.RED); /** * The color of the blocks to place */ - public Setting colorBlocksToPlace = new Setting<>(Color.GREEN); + public final Setting colorBlocksToPlace = new Setting<>(Color.GREEN); /** * The color of the blocks to walk into */ - public Setting colorBlocksToWalkInto = new Setting<>(Color.MAGENTA); + public final Setting colorBlocksToWalkInto = new Setting<>(Color.MAGENTA); /** * The color of the best path so far */ - public Setting colorBestPathSoFar = new Setting<>(Color.BLUE); + public final Setting colorBestPathSoFar = new Setting<>(Color.BLUE); /** * The color of the path to the most recent considered node */ - public Setting colorMostRecentConsidered = new Setting<>(Color.CYAN); + public final Setting colorMostRecentConsidered = new Setting<>(Color.CYAN); /** * The color of the goal box */ - public Setting colorGoalBox = new Setting<>(Color.GREEN); + public final Setting colorGoalBox = new Setting<>(Color.GREEN); /** * A map of lowercase setting field names to their respective setting From b4a622d3196b6f8f5afecdda677e8af9a0e9124c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 10:59:08 -0800 Subject: [PATCH 050/682] editing settings --- README.md | 2 +- src/api/java/baritone/api/Settings.java | 33 ++++++++++++++++++------- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 555c2c07..224281c7 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ Quick start example: `thisway 1000` or `goal 70` to set the goal, `path` to actu ``` BaritoneAPI.getSettings().allowSprint.value = true; -BaritoneAPI.getSettings().pathTimeoutMS.value = 2000L; +BaritoneAPI.getSettings().primaryTimeoutMS.value = 2000L; BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalXZ(10000, 20000)); ``` diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index a069d76b..14cf6814 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -69,7 +69,7 @@ public final class Settings { public final Setting blockBreakAdditionalPenalty = new Setting<>(2D); /** - * Additional penalty for hitting the space bar (ascend, pillar, or parkour) beacuse it uses hunger + * Additional penalty for hitting the space bar (ascend, pillar, or parkour) because it uses hunger */ public final Setting jumpPenalty = new Setting<>(2D); @@ -107,7 +107,7 @@ public final class Settings { /** * If true, parkour is allowed to make jumps when standing on blocks at the maximum height, so player feet is y=256 *

- * Defaults to false because this fails on NCP + * Defaults to false because this fails on constantiam */ public final Setting allowJumpAt256 = new Setting<>(false); @@ -132,6 +132,8 @@ public final class Settings { /** * Enables some more advanced vine features. They're honestly just gimmicks and won't ever be needed in real * pathing scenarios. And they can cause Baritone to get trapped indefinitely in a strange scenario. + *

+ * Never turn this on lol */ public final Setting allowVines = new Setting<>(false); @@ -145,11 +147,15 @@ public final class Settings { * You know what it is *

* But it's very unreliable and falls off when cornering like all the time so. + *

+ * It also overshoots the landing pretty much always (making contact with the next block over), so be careful */ public final Setting allowParkour = new Setting<>(false); /** - * Like parkour, but even more unreliable! + * Actually pretty reliable. + *

+ * Doesn't make it any more dangerous compared to just normal allowParkour th */ public final Setting allowParkourPlace = new Setting<>(false); @@ -192,9 +198,13 @@ public final class Settings { /** * Toggle the following 4 settings *

- * They have a noticable performance impact, so they default off + * They have a noticeable performance impact, so they default off + *

+ * Specifically, building up the avoidance map on the main thread before pathing starts actually takes a noticeable + * amount of time, especially when there are a lot of mobs around, and your game jitters for like 200ms while doing so */ public final Setting avoidance = new Setting<>(false); + /** * Set to 1.0 to effectively disable this feature *

@@ -234,8 +244,10 @@ public final class Settings { /** * After calculating a path (potentially through cached chunks), artificially cut it off to just the part that is * entirely within currently loaded chunks. Improves path safety because cached chunks are heavily simplified. + *

+ * This is much safer to leave off now, and makes pathing more efficient. More explanation in the issue. * - * @see Issue #144 + * @see Issue #114 */ public final Setting cutoffAtLoadBoundary = new Setting<>(false); @@ -360,7 +372,9 @@ public final class Settings { /** * On save, delete from RAM any cached regions that are more than 1024 blocks away from the player *

- * Temporarily disabled, see issue #248 + * Temporarily disabled + * + * @see Issue #248 */ public final Setting pruneRegionsFromRAM = new Setting<>(false); @@ -456,7 +470,7 @@ public final class Settings { public final Setting walkWhileBreaking = new Setting<>(true); /** - * If we are more than 500 movements into the current path, discard the oldest segments, as they are no longer useful + * If we are more than 300 movements into the current path, discard the oldest segments, as they are no longer useful */ public final Setting maxPathHistoryLength = new Setting<>(300); @@ -497,9 +511,9 @@ public final class Settings { public final Setting axisHeight = new Setting<>(120); /** - * Allow MineBehavior to use X-Ray to see where the ores are. Turn this option off to force it to mine "legit" + * Disallow MineBehavior from using X-Ray to see where the ores are. Turn this option on to force it to mine "legit" * where it will only mine an ore once it can actually see it, so it won't do or know anything that a normal player - * couldn't. If you don't want it to look like you're X-Raying, turn this off + * couldn't. If you don't want it to look like you're X-Raying, turn this on */ public final Setting legitMine = new Setting<>(false); @@ -607,6 +621,7 @@ public final class Settings { */ public final Setting colorGoalBox = new Setting<>(Color.GREEN); + /** * A map of lowercase setting field names to their respective setting */ From 742256c1301922b3181a9c5346b7dde161800169 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 11:30:33 -0800 Subject: [PATCH 051/682] more fun javadocs --- build.gradle | 4 ++-- src/main/java/baritone/utils/ToolSet.java | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 99a17a3b..ea265016 100755 --- a/build.gradle +++ b/build.gradle @@ -99,8 +99,8 @@ mixin { } javadoc { - source = sourceSets.api.allJava - classpath = sourceSets.api.compileClasspath + source += sourceSets.api.allJava + classpath += sourceSets.api.compileClasspath } jar { diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index fa71a6b0..bfa4e251 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -135,6 +135,7 @@ public class ToolSet { * Calculates how long would it take to mine the specified block given the best tool * in this toolset is used. A negative value is returned if the specified block is unbreakable. * + * @param item the item to mine it with * @param state the blockstate to be mined * @return how long it would take in ticks */ From f5f2e4970ef0fb9cf3d53bb15c2eb7f12e713581 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 11:37:02 -0800 Subject: [PATCH 052/682] make travis fail when javadoc doesn't compile --- .travis.yml | 1 + src/main/java/baritone/utils/ToolSet.java | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a8344ba0..88fa7cf5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,6 +9,7 @@ install: - travis_retry docker build -t cabaletta/baritone . script: +- docker run cabaletta/baritone ./gradlew javadoc - docker run --name baritone cabaletta/baritone /bin/sh -c "set -e; /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 128x128x24 -ac +extension GLX +render; DISPLAY=:99 BARITONE_AUTO_TEST=true ./gradlew runClient" - docker cp baritone:/code/dist dist - ls dist diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index bfa4e251..a05d838d 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -137,7 +137,7 @@ public class ToolSet { * * @param item the item to mine it with * @param state the blockstate to be mined - * @return how long it would take in ticks + * @rturn how long it would take in ticks */ public static double calculateSpeedVsBlock(ItemStack item, IBlockState state) { float hardness = state.getBlockHardness(null, null); From 96360ddb24eaa63a8524e9886448e72736cc29c4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 11:49:52 -0800 Subject: [PATCH 053/682] perhaps --- build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/build.gradle b/build.gradle index ea265016..5c711493 100755 --- a/build.gradle +++ b/build.gradle @@ -99,6 +99,7 @@ mixin { } javadoc { + options.addStringOption('Xwerror', '-quiet') source += sourceSets.api.allJava classpath += sourceSets.api.compileClasspath } From 177f5de2bdab38cbb8a7b07f0f150c166a982995 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 11:56:44 -0800 Subject: [PATCH 054/682] yay travis checks javadocs now --- build.gradle | 2 +- src/main/java/baritone/utils/ToolSet.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 5c711493..c291b950 100755 --- a/build.gradle +++ b/build.gradle @@ -99,7 +99,7 @@ mixin { } javadoc { - options.addStringOption('Xwerror', '-quiet') + options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error source += sourceSets.api.allJava classpath += sourceSets.api.compileClasspath } diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index a05d838d..bfa4e251 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -137,7 +137,7 @@ public class ToolSet { * * @param item the item to mine it with * @param state the blockstate to be mined - * @rturn how long it would take in ticks + * @return how long it would take in ticks */ public static double calculateSpeedVsBlock(ItemStack item, IBlockState state) { float hardness = state.getBlockHardness(null, null); From 49148dfb7a869a0413f8e0c8f70c33a78934c542 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 11:57:58 -0800 Subject: [PATCH 055/682] add javadocs link --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 224281c7..7782651a 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,8 @@ Here are some links to help to get started: - [Installation](INSTALL.md) +- [Javadocs](https://baritone.leijurv.com/) + # Chat control [Defined Here](src/main/java/baritone/utils/ExampleBaritoneControl.java) From c15f1e8276ee4e119fe31d55c1993477ff4717b4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 12:06:26 -0800 Subject: [PATCH 056/682] link source is cool --- build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/build.gradle b/build.gradle index c291b950..8583642d 100755 --- a/build.gradle +++ b/build.gradle @@ -100,6 +100,7 @@ mixin { javadoc { options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error + options.linkSource true source += sourceSets.api.allJava classpath += sourceSets.api.compileClasspath } From a87772c98c41478e502e5aac118b11f6b6b65626 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 12:16:45 -0800 Subject: [PATCH 057/682] remove that image once done --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 88fa7cf5..371639be 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,7 +9,7 @@ install: - travis_retry docker build -t cabaletta/baritone . script: -- docker run cabaletta/baritone ./gradlew javadoc +- docker run --rm cabaletta/baritone ./gradlew javadoc - docker run --name baritone cabaletta/baritone /bin/sh -c "set -e; /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 128x128x24 -ac +extension GLX +render; DISPLAY=:99 BARITONE_AUTO_TEST=true ./gradlew runClient" - docker cp baritone:/code/dist dist - ls dist From 840b7e6987185f17c69439d8ce3db3557ab1efdf Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 15:59:53 -0800 Subject: [PATCH 058/682] misc fixes #315 --- .../baritone/pathing/movement/Movement.java | 2 +- .../movement/movements/MovementDescend.java | 17 +++++---- .../movement/movements/MovementFall.java | 10 +++--- .../baritone/pathing/path/PathExecutor.java | 35 +++++++++++-------- 4 files changed, 36 insertions(+), 28 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index ce78c231..4599637a 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -123,7 +123,7 @@ public abstract class Movement implements IMovement, MovementHelper { baritone.getLookBehavior().updateTarget( rotation, currentState.getTarget().hasToForceRotations())); - + baritone.getInputOverrideHandler().clearAllKeys(); currentState.getInputStates().forEach((input, forced) -> { baritone.getInputOverrideHandler().setInputForceState(input, forced); }); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index d2d2c282..d54ffc51 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -177,13 +177,6 @@ public class MovementDescend extends Movement { if (MovementHelper.isBottomSlab(ontoBlock)) { return false; // falling onto a half slab is really glitchy, and can cause more fall damage than we'd expect } - if (context.hasWaterBucket && unprotectedFallHeight <= context.maxFallHeightBucket + 1) { - res.x = destX; - res.y = newY + 1;// this is the block we're falling onto, so dest is +1 - res.z = destZ; - res.cost = tentativeCost + context.placeBlockCost; - return true; - } if (unprotectedFallHeight <= context.maxFallHeightNoWater + 1) { // fallHeight = 4 means onto.up() is 3 blocks down, which is the max res.x = destX; @@ -191,6 +184,13 @@ public class MovementDescend extends Movement { res.z = destZ; res.cost = tentativeCost; return false; + } + if (context.hasWaterBucket && unprotectedFallHeight <= context.maxFallHeightBucket + 1) { + res.x = destX; + res.y = newY + 1;// this is the block we're falling onto, so dest is +1 + res.z = destZ; + res.cost = tentativeCost + context.placeBlockCost; + return true; } else { return false; } @@ -235,8 +235,7 @@ public class MovementDescend extends Movement { if (numTicks++ < 20) { MovementHelper.moveTowards(ctx, state, fakeDest); if (fromStart > 1.25) { - state.setInput(Input.MOVE_FORWARD, false); - state.setInput(Input.MOVE_BACK, true); + state.getTarget().rotation = new Rotation(state.getTarget().rotation.getYaw() + 180F, state.getTarget().rotation.getPitch()); } } else { MovementHelper.moveTowards(ctx, state, dest); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 6442d7d9..a82ad110 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -30,6 +30,7 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.pathing.MutableMoveResult; +import net.minecraft.block.Block; import net.minecraft.block.BlockLadder; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.InventoryPlayer; @@ -79,7 +80,8 @@ public class MovementFall extends Movement { BlockPos playerFeet = ctx.playerFeet(); Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)); Rotation targetRotation = null; - if (!MovementHelper.isWater(ctx, dest) && willPlaceBucket() && !playerFeet.equals(dest)) { + Block destBlock = ctx.world().getBlockState(dest).getBlock(); + if (destBlock != Blocks.WATER && destBlock != Blocks.FLOWING_WATER && willPlaceBucket() && !playerFeet.equals(dest)) { if (!InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER)) || ctx.world().provider.isNether()) { return state.setStatus(MovementStatus.UNREACHABLE); } @@ -100,8 +102,8 @@ public class MovementFall extends Movement { } else { state.setTarget(new MovementTarget(toDest, false)); } - if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || MovementHelper.isWater(ctx, dest))) { // 0.094 because lilypads - if (MovementHelper.isWater(ctx, dest)) { + if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || destBlock == Blocks.WATER)) { // 0.094 because lilypads + if (destBlock == Blocks.WATER) { // only match water, not flowing water (which we cannot pick up with a bucket) if (InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) { ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY); if (ctx.player().motionY >= 0) { @@ -132,7 +134,7 @@ public class MovementFall extends Movement { double dist = Math.abs(avoid.getX() * (destCenter.x - avoid.getX() / 2.0 - ctx.player().posX)) + Math.abs(avoid.getZ() * (destCenter.z - avoid.getZ() / 2.0 - ctx.player().posZ)); if (dist < 0.6) { state.setInput(Input.MOVE_FORWARD, true); - } else { + } else if (!ctx.player().onGround) { state.setInput(Input.SNEAK, false); } } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index ef856f42..b5b621e8 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -272,6 +272,9 @@ public class PathExecutor implements IPathExecutor, Helper { return true; } else { sprintNextTick = shouldSprintNextTick(); + if (!sprintNextTick) { + ctx.player().setSprinting(false); // letting go of control doesn't make you stop sprinting actually + } ticksOnCurrent++; if (ticksOnCurrent > currentMovementOriginalCostEstimate + Baritone.settings().movementTimeoutTicks.get()) { // only cancel if the total time has exceeded the initial estimate @@ -391,29 +394,33 @@ public class PathExecutor implements IPathExecutor, Helper { // however, descend doesn't request sprinting, beceause it doesn't know the context of what movement comes after it IMovement current = path.movements().get(pathPosition); - if (current instanceof MovementDescend && pathPosition < path.length() - 2) { + if (current instanceof MovementDescend) { if (((MovementDescend) current).safeMode()) { logDebug("Sprinting would be unsafe"); return false; } - IMovement next = path.movements().get(pathPosition + 1); - if (next instanceof MovementAscend && current.getDirection().up().equals(next.getDirection().down())) { - // a descend then an ascend in the same direction - pathPosition++; - // okay to skip clearKeys and / or onChangeInPathPosition here since this isn't possible to repeat, since it's asymmetric - logDebug("Skipping descend to straight ascend"); - return true; - } - if (canSprintInto(ctx, current, next)) { - if (ctx.playerFeet().equals(current.getDest())) { + if (pathPosition < path.length() - 2) { + IMovement next = path.movements().get(pathPosition + 1); + if (next instanceof MovementAscend && current.getDirection().up().equals(next.getDirection().down())) { + // a descend then an ascend in the same direction pathPosition++; - onChangeInPathPosition(); + // okay to skip clearKeys and / or onChangeInPathPosition here since this isn't possible to repeat, since it's asymmetric + logDebug("Skipping descend to straight ascend"); + return true; } - return true; + if (canSprintInto(ctx, current, next)) { + if (ctx.playerFeet().equals(current.getDest())) { + pathPosition++; + onChangeInPathPosition(); + logDirect("skip lol"); + onTick(); + } + return true; + } + //logDebug("Turning off sprinting " + movement + " " + next + " " + movement.getDirection() + " " + next.getDirection().down() + " " + next.getDirection().down().equals(movement.getDirection())); } - //logDebug("Turning off sprinting " + movement + " " + next + " " + movement.getDirection() + " " + next.getDirection().down() + " " + next.getDirection().down().equals(movement.getDirection())); } if (current instanceof MovementAscend && pathPosition != 0) { IMovement prev = path.movements().get(pathPosition - 1); From 056742479e517d4a85ce2de5aa3f146cda8c9a77 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 16:06:34 -0800 Subject: [PATCH 059/682] except without that --- src/main/java/baritone/pathing/path/PathExecutor.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index b5b621e8..6f161cc0 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -414,7 +414,6 @@ public class PathExecutor implements IPathExecutor, Helper { if (ctx.playerFeet().equals(current.getDest())) { pathPosition++; onChangeInPathPosition(); - logDirect("skip lol"); onTick(); } return true; From 735cf47c35e6f6c3f1e5160143edb51b55b011ff Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 17:34:14 -0800 Subject: [PATCH 060/682] actually works --- src/api/java/baritone/api/Settings.java | 5 ++ .../launch/mixins/MixinChunkCache.java | 16 ++++++- .../launch/mixins/MixinChunkRenderWorker.java | 46 +++++++++++++++++++ src/launch/resources/mixins.baritone.json | 1 + .../utils/ExampleBaritoneControl.java | 8 ++++ 5 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 1b4f62e0..46c835cd 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -445,6 +445,11 @@ public class Settings { */ public Setting pathThroughCachedOnly = new Setting<>(false); + /** + * 😎 + */ + public Setting renderCachedChunks = new Setting<>(false); + /** * Whether or not to use the "#" command prefix */ diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkCache.java b/src/launch/java/baritone/launch/mixins/MixinChunkCache.java index 17fefb6d..f8d0a0bf 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkCache.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkCache.java @@ -38,9 +38,21 @@ public class MixinChunkCache { private void getBlockState(BlockPos pos, CallbackInfoReturnable ci) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); - if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { + if (ctx.player() != null && ctx.world() != null && baritone.bsi != null && Baritone.settings().renderCachedChunks.get()) { ci.setReturnValue(baritone.bsi.get0(pos)); - //ci.setReturnValue(Blocks.DIRT.getDefaultState()); + } + } + + @Inject( + method = "isEmpty", + at = @At("HEAD"), + cancellable = true + ) + private void isEmpty(CallbackInfoReturnable ci) { + Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); + IPlayerContext ctx = baritone.getPlayerContext(); + if (ctx.player() != null && ctx.world() != null && baritone.bsi != null && Baritone.settings().renderCachedChunks.get()) { + ci.setReturnValue(false); } } } diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java new file mode 100644 index 00000000..493d4869 --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java @@ -0,0 +1,46 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.utils.IPlayerContext; +import net.minecraft.client.renderer.chunk.ChunkRenderWorker; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(ChunkRenderWorker.class) +public class MixinChunkRenderWorker { + @Inject( + method = "isChunkExisting", + at = @At("HEAD"), + cancellable = true + ) + private void isChunkExisting(BlockPos pos, World world, CallbackInfoReturnable ci) { + Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); + IPlayerContext ctx = baritone.getPlayerContext(); + if (ctx.player() != null && ctx.world() != null && baritone.bsi != null && Baritone.settings().renderCachedChunks.get()) { + ci.setReturnValue(baritone.bsi.isLoaded(pos.getX(), pos.getZ())); + } + } +} + diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index eab28fdb..9a7dce45 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -13,6 +13,7 @@ "MixinChunkCache", "MixinChunkProviderClient", "MixinChunkProviderServer", + "MixinChunkRenderWorker", "MixinEntity", "MixinEntityLivingBase", "MixinEntityPlayerSP", diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 508a5e1b..f5d054be 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -24,6 +24,7 @@ import baritone.api.cache.IWaypoint; import baritone.api.event.events.ChatEvent; import baritone.api.pathing.goals.*; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.SettingsUtil; import baritone.behavior.Behavior; import baritone.behavior.PathingBehavior; @@ -35,6 +36,7 @@ import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; import baritone.utils.pathing.SegmentedCalculator; import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ChunkProviderClient; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; @@ -284,6 +286,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Baritone settings reset"); return true; } + if (msg.equals("render")) { + BetterBlockPos pf = ctx.playerFeet(); + Minecraft.getMinecraft().renderGlobal.markBlockRangeForRenderUpdate(pf.x - 500, pf.y - 500, pf.z - 500, pf.x + 500, pf.y + 500, pf.z + 500); + logDirect("okay"); + return true; + } if (msg.equals("echest")) { Optional> contents = baritone.getMemoryBehavior().echest(); if (contents.isPresent()) { From 784b2f541d39b61b9ac2b0a9133a9f3044efad69 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 19:02:07 -0800 Subject: [PATCH 061/682] lol --- .../mixins/MixinChunkRenderContainer.java | 40 +++++++++++++++++++ src/launch/resources/mixins.baritone.json | 1 + 2 files changed, 41 insertions(+) create mode 100644 src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java new file mode 100644 index 00000000..49af7d72 --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -0,0 +1,40 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.ChunkRenderContainer; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.chunk.RenderChunk; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ChunkRenderContainer.class) +public class MixinChunkRenderContainer { + @Inject( + method = "preRenderChunk", + at = @At("HEAD") + ) + private void preRenderChunk(RenderChunk renderChunkIn, CallbackInfo ci) { + if (Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { + GlStateManager.translate(0, Math.sin(System.currentTimeMillis() / 1000D + (renderChunkIn.getPosition().getX() + renderChunkIn.getPosition().getZ()) / 16D) * 4, 0); + } + } +} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index 9a7dce45..10e3510d 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -13,6 +13,7 @@ "MixinChunkCache", "MixinChunkProviderClient", "MixinChunkProviderServer", + "MixinChunkRenderContainer", "MixinChunkRenderWorker", "MixinEntity", "MixinEntityLivingBase", From 5179cfc5ba3a708445b6878bc2db72c9dc891168 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 28 Jan 2019 21:28:26 -0800 Subject: [PATCH 062/682] semitransparency working --- .../launch/mixins/MixinChunkRenderContainer.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index 49af7d72..1894caaa 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -21,11 +21,14 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ChunkRenderContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.chunk.RenderChunk; +import org.lwjgl.opengl.GL14; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import static org.lwjgl.opengl.GL11.*; + @Mixin(ChunkRenderContainer.class) public class MixinChunkRenderContainer { @Inject( @@ -34,7 +37,12 @@ public class MixinChunkRenderContainer { ) private void preRenderChunk(RenderChunk renderChunkIn, CallbackInfo ci) { if (Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { - GlStateManager.translate(0, Math.sin(System.currentTimeMillis() / 1000D + (renderChunkIn.getPosition().getX() + renderChunkIn.getPosition().getZ()) / 16D) * 4, 0); + GlStateManager.enableAlpha(); + GlStateManager.enableBlend(); + GL14.glBlendColor(0, 0, 0, 0.5F); + GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); + } else { + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } } } From b471d7419efaa24053c9128b2efcbf9b68cda864 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 29 Jan 2019 12:41:14 -0600 Subject: [PATCH 063/682] Replace most of the @Inject usages for cancer render with @Redirect --- .../launch/mixins/MixinChunkCache.java | 58 -------------- .../mixins/MixinChunkRenderContainer.java | 1 + .../launch/mixins/MixinChunkRenderWorker.java | 33 +++++--- .../launch/mixins/MixinRenderChunk.java | 75 +++++++++++++++++++ src/launch/resources/mixins.baritone.json | 2 +- 5 files changed, 98 insertions(+), 71 deletions(-) delete mode 100644 src/launch/java/baritone/launch/mixins/MixinChunkCache.java create mode 100644 src/launch/java/baritone/launch/mixins/MixinRenderChunk.java diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkCache.java b/src/launch/java/baritone/launch/mixins/MixinChunkCache.java deleted file mode 100644 index f8d0a0bf..00000000 --- a/src/launch/java/baritone/launch/mixins/MixinChunkCache.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.launch.mixins; - -import baritone.Baritone; -import baritone.api.BaritoneAPI; -import baritone.api.utils.IPlayerContext; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.ChunkCache; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(ChunkCache.class) -public class MixinChunkCache { - @Inject( - method = "getBlockState", - at = @At("HEAD"), - cancellable = true - ) - private void getBlockState(BlockPos pos, CallbackInfoReturnable ci) { - Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); - IPlayerContext ctx = baritone.getPlayerContext(); - if (ctx.player() != null && ctx.world() != null && baritone.bsi != null && Baritone.settings().renderCachedChunks.get()) { - ci.setReturnValue(baritone.bsi.get0(pos)); - } - } - - @Inject( - method = "isEmpty", - at = @At("HEAD"), - cancellable = true - ) - private void isEmpty(CallbackInfoReturnable ci) { - Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); - IPlayerContext ctx = baritone.getPlayerContext(); - if (ctx.player() != null && ctx.world() != null && baritone.bsi != null && Baritone.settings().renderCachedChunks.get()) { - ci.setReturnValue(false); - } - } -} diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index 1894caaa..19cbfc14 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -31,6 +31,7 @@ import static org.lwjgl.opengl.GL11.*; @Mixin(ChunkRenderContainer.class) public class MixinChunkRenderContainer { + @Inject( method = "preRenderChunk", at = @At("HEAD") diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java index 493d4869..3621b664 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java @@ -24,23 +24,32 @@ import net.minecraft.client.renderer.chunk.ChunkRenderWorker; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(ChunkRenderWorker.class) -public class MixinChunkRenderWorker { - @Inject( - method = "isChunkExisting", - at = @At("HEAD"), - cancellable = true +public abstract class MixinChunkRenderWorker { + + @Shadow protected abstract boolean isChunkExisting(BlockPos pos, World worldIn); + + @Redirect( + method = "processTask", + at = @At( + value = "INVOKE", + target = "net/minecraft/client/renderer/chunk/ChunkRenderWorker.isChunkExisting(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/World;)Z" + ) ) - private void isChunkExisting(BlockPos pos, World world, CallbackInfoReturnable ci) { - Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); - IPlayerContext ctx = baritone.getPlayerContext(); - if (ctx.player() != null && ctx.world() != null && baritone.bsi != null && Baritone.settings().renderCachedChunks.get()) { - ci.setReturnValue(baritone.bsi.isLoaded(pos.getX(), pos.getZ())); + private boolean isChunkExisting(ChunkRenderWorker worker, BlockPos pos, World world) { + if (Baritone.settings().renderCachedChunks.get()) { + Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); + IPlayerContext ctx = baritone.getPlayerContext(); + if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { + return baritone.bsi.isLoaded(pos.getX(), pos.getZ()); + } } + + return this.isChunkExisting(pos, world); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java b/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java new file mode 100644 index 00000000..47402c6b --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java @@ -0,0 +1,75 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.utils.IPlayerContext; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.chunk.RenderChunk; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.ChunkCache; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +/** + * @author Brady + * @since 1/29/2019 + */ +@Mixin(RenderChunk.class) +public class MixinRenderChunk { + + @Redirect( + method = "rebuildChunk", + at = @At( + value = "INVOKE", + target = "net/minecraft/world/ChunkCache.isEmpty()Z" + ) + ) + private boolean isEmpty(ChunkCache chunkCache) { + if (Baritone.settings().renderCachedChunks.get()) { + Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); + IPlayerContext ctx = baritone.getPlayerContext(); + if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { + return false; + } + } + + return chunkCache.isEmpty(); + } + + @Redirect( + method = "rebuildChunk", + at = @At( + value = "INVOKE", + target = "net/minecraft/world/ChunkCache.getBlockState(Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/state/IBlockState;" + ) + ) + private IBlockState getBlockState(ChunkCache chunkCache, BlockPos pos) { + if (Baritone.settings().renderCachedChunks.get()) { + Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); + IPlayerContext ctx = baritone.getPlayerContext(); + if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { + return baritone.bsi.get0(pos); + } + } + + return chunkCache.getBlockState(pos); + } +} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index 10e3510d..aa9a724f 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -10,7 +10,6 @@ "client": [ "MixinAnvilChunkLoader", "MixinBlockPos", - "MixinChunkCache", "MixinChunkProviderClient", "MixinChunkProviderServer", "MixinChunkRenderContainer", @@ -23,6 +22,7 @@ "MixinMinecraft", "MixinNetHandlerPlayClient", "MixinNetworkManager", + "MixinRenderChunk", "MixinWorldClient" ] } \ No newline at end of file From 8f2b23f8f99b91648a803ef39f62e17708071c9e Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 29 Jan 2019 14:33:34 -0600 Subject: [PATCH 064/682] Wew lad --- src/launch/java/baritone/launch/mixins/MixinKeyBinding.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java index cf832533..6e215547 100644 --- a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java +++ b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java @@ -34,7 +34,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; public class MixinKeyBinding { @Shadow - public int pressTime; + private int pressTime; @Inject( method = "isKeyDown", @@ -57,7 +57,7 @@ public class MixinKeyBinding { private void isPressed(CallbackInfoReturnable cir) { // only the primary baritone forces keys Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this); - if (force != null && force == false) { // <-- cursed + if (force != null && !force) { // <-- cursed if (pressTime > 0) { Helper.HELPER.logDirect("You're trying to press this mouse button but I won't let you"); pressTime--; From 9028564c10d64ff4ed33b5200a2eaf08514c6567 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 29 Jan 2019 13:54:54 -0800 Subject: [PATCH 065/682] only when the setting is enabled --- .../mixins/MixinChunkRenderContainer.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index 19cbfc14..8075f1f2 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -17,6 +17,7 @@ package baritone.launch.mixins; +import baritone.Baritone; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ChunkRenderContainer; import net.minecraft.client.renderer.GlStateManager; @@ -37,13 +38,15 @@ public class MixinChunkRenderContainer { at = @At("HEAD") ) private void preRenderChunk(RenderChunk renderChunkIn, CallbackInfo ci) { - if (Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { - GlStateManager.enableAlpha(); - GlStateManager.enableBlend(); - GL14.glBlendColor(0, 0, 0, 0.5F); - GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); - } else { - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); + if (Baritone.settings().renderCachedChunks.get()) { + if (Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { + GlStateManager.enableAlpha(); + GlStateManager.enableBlend(); + GL14.glBlendColor(0, 0, 0, 0.5F); + GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); + } else { + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); + } } } } From 9faa0ddc62ed10dc99fca669d1ace69490ae07f7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 29 Jan 2019 15:22:48 -0800 Subject: [PATCH 066/682] huge number of fixes --- .../api/behavior/IPathingBehavior.java | 12 +++- .../api/pathing/path/IPathExecutor.java | 2 + .../baritone/behavior/PathingBehavior.java | 72 ++++++------------- .../pathing/calc/AbstractNodeCostSearch.java | 22 +++++- .../movement/movements/MovementDescend.java | 5 +- .../movement/movements/MovementFall.java | 7 +- .../baritone/pathing/path/PathExecutor.java | 1 + .../java/baritone/process/MineProcess.java | 15 ++-- .../java/baritone/utils/pathing/PathBase.java | 4 ++ 9 files changed, 72 insertions(+), 68 deletions(-) diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index 0f44f2ee..d28195ae 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -37,7 +37,13 @@ public interface IPathingBehavior extends IBehavior { * * @return The estimated remaining ticks in the current segment. */ - Optional ticksRemainingInSegment(); + default Optional ticksRemainingInSegment() { + IPathExecutor current = getCurrent(); + if (current == null) { + return Optional.empty(); + } + return Optional.of(current.getPath().ticksRemainingFrom(current.getPosition())); + } /** * @return The current pathing goal @@ -47,7 +53,9 @@ public interface IPathingBehavior extends IBehavior { /** * @return Whether or not a path is currently being executed. */ - boolean isPathing(); + default boolean isPathing() { + return getCurrent() != null; + } /** * Cancels the pathing behavior or the current path calculation, and all processes that could be controlling path. diff --git a/src/api/java/baritone/api/pathing/path/IPathExecutor.java b/src/api/java/baritone/api/pathing/path/IPathExecutor.java index f72060dc..a5c3108e 100644 --- a/src/api/java/baritone/api/pathing/path/IPathExecutor.java +++ b/src/api/java/baritone/api/pathing/path/IPathExecutor.java @@ -26,4 +26,6 @@ import baritone.api.pathing.calc.IPath; public interface IPathExecutor { IPath getPath(); + + int getPosition(); } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 74cc46ee..ea752082 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -30,7 +30,6 @@ import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; -import baritone.pathing.path.CutoffPath; import baritone.pathing.path.PathExecutor; import baritone.utils.Helper; import baritone.utils.PathRenderer; @@ -125,7 +124,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, next = null; return; } - if (next != null && !next.getPath().positions().contains(ctx.playerFeet())) { + if (next != null && !next.getPath().positions().contains(ctx.playerFeet()) && !next.getPath().positions().contains(pathStart())) { // can contain either one // if the current path failed, we may not actually be on the next one, so make sure logDebug("Discarding next path as it does not contain current position"); // for example if we had a nicely planned ahead path that starts where current ends @@ -141,16 +140,27 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, queuePathEvent(PathEvent.CONTINUING_ONTO_PLANNED_NEXT); current = next; next = null; - current.onTick(); + current.onTick(); // don't waste a tick doing nothing, get started right away return; } // at this point, current just ended, but we aren't in the goal and have no plan for the future synchronized (pathCalcLock) { if (inProgress != null) { - queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING); - // if we aren't calculating right now - return; + // we are calculating + // are we calculating the right thing though? 🤔 + BetterBlockPos calcFrom = inProgress.getStart(); + // if current just succeeded, we should be standing in calcFrom, so that's cool and good + // but if current just failed, we should discard this calculation since it doesn't start from where we're standing + if (calcFrom.equals(ctx.playerFeet()) || calcFrom.equals(pathStart())) { + // cool and good + queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING); + return; + } + // oh noes + inProgress.cancel(); // cancellation doesn't dispatch any events + inProgress = null; // this is safe since we hold both locks } + // we aren't calculating queuePathEvent(PathEvent.CALC_STARTED); findPathInNewThread(pathStart(), true); } @@ -180,11 +190,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return; } if (goal == null || goal.isInGoal(current.getPath().getDest())) { - // and this path dosen't get us all the way there + // and this path doesn't get us all the way there return; } if (ticksRemainingInSegment().get() < Baritone.settings().planningTickLookAhead.get()) { - // and this path has 5 seconds or less left + // and this path has 7.5 seconds or less left logDebug("Path almost over. Planning ahead..."); queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED); findPathInNewThread(current.getPath().getDest(), false); @@ -210,14 +220,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } } - @Override - public Optional ticksRemainingInSegment() { - if (current == null) { - return Optional.empty(); - } - return Optional.of(current.getPath().ticksRemainingFrom(current.getPosition())); - } - public void secretInternalSetGoal(Goal goal) { this.goal = goal; } @@ -247,11 +249,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return Optional.ofNullable(inProgress); } - @Override - public boolean isPathing() { - return this.current != null; - } - public boolean isSafeToCancel() { return current == null || safeToCancel; } @@ -274,7 +271,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, if (doIt) { secretInternalSegmentCancel(); } - baritone.getPathingControlManager().cancelEverything(); + baritone.getPathingControlManager().cancelEverything(); // regardless of if we can stop the current segment, we can still stop the processes return doIt; } @@ -310,7 +307,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, public void forceCancel() { // NOT exposed on public api cancelEverything(); secretInternalSegmentCancel(); - inProgress = null; + synchronized (pathCalcLock) { + inProgress = null; + } } /** @@ -433,33 +432,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } PathCalculationResult calcResult = pathfinder.calculate(primaryTimeout, failureTimeout); - Optional path = calcResult.getPath(); - if (Baritone.settings().cutoffAtLoadBoundary.get()) { - path = path.map(p -> { - IPath result = p.cutoffAtLoadedChunks(context.bsi); - - if (result instanceof CutoffPath) { - logDebug("Cutting off path at edge of loaded chunks"); - logDebug("Length decreased by " + (p.length() - result.length())); - } else { - logDebug("Path ends within loaded chunks"); - } - - return result; - }); - } - - Optional executor = path.map(p -> { - IPath result = p.staticCutoff(goal); - - if (result instanceof CutoffPath) { - logDebug("Static cutoff " + p.length() + " to " + result.length()); - } - - return result; - }).map(p -> new PathExecutor(this, p)); - synchronized (pathPlanLock) { + Optional executor = calcResult.getPath().map(p -> new PathExecutor(PathingBehavior.this, p)); if (current == null) { if (executor.isPresent()) { queuePathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING); diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 78710204..625e8e59 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -92,13 +92,25 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { cancelRequested = false; try { IPath path = calculate0(primaryTimeout, failureTimeout).map(IPath::postProcess).orElse(null); - isFinished = true; if (cancelRequested) { - return new PathCalculationResult(PathCalculationResult.Type.CANCELLATION, path); + return new PathCalculationResult(PathCalculationResult.Type.CANCELLATION); } if (path == null) { return new PathCalculationResult(PathCalculationResult.Type.FAILURE); } + int previousLength = path.length(); + path = path.cutoffAtLoadedChunks(context.bsi); + if (path.length() < previousLength) { + Helper.HELPER.logDebug("Cutting off path at edge of loaded chunks"); + Helper.HELPER.logDebug("Length decreased by " + (previousLength - path.length())); + } else { + Helper.HELPER.logDebug("Path ends within loaded chunks"); + } + previousLength = path.length(); + path = path.staticCutoff(goal); + if (path.length() < previousLength) { + Helper.HELPER.logDebug("Static cutoff " + previousLength + " to " + path.length()); + } if (goal.isInGoal(path.getDest())) { return new PathCalculationResult(PathCalculationResult.Type.SUCCESS_TO_GOAL, path); } else { @@ -163,7 +175,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { } @Override - public Optional bestPathSoFar() { + public Optional bestPathSoFar() { // TODO cleanup code duplication between here and AStarPathFinder if (startNode == null || bestSoFar == null) { return Optional.empty(); } @@ -189,4 +201,8 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { public final Goal getGoal() { return goal; } + + public BetterBlockPos getStart() { + return new BetterBlockPos(startX, startY, startZ); + } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index d54ffc51..aeb4e138 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -137,7 +137,7 @@ public class MovementDescend extends Movement { IBlockState ontoBlock = context.get(destX, newY, destZ); int unprotectedFallHeight = fallHeight - (y - effectiveStartHeight); // equal to fallHeight - y + effectiveFallHeight, which is equal to -newY + effectiveFallHeight, which is equal to effectiveFallHeight - newY double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[unprotectedFallHeight] + frontBreak + costSoFar; - if (ontoBlock.getBlock() == Blocks.WATER && context.getBlock(destX, newY + 1, destZ) != Blocks.WATERLILY) { + if ((ontoBlock.getBlock() == Blocks.WATER || ontoBlock.getBlock() == Blocks.FLOWING_WATER) && context.getBlock(destX, newY + 1, destZ) != Blocks.WATERLILY) { // lilypads are canWalkThrough, but we can't end a fall that should be broken by water if it's covered by a lilypad // however, don't return impossible in the lilypad scenario, because we could still jump right on it (water that's below a lilypad is canWalkOn so it works) if (context.assumeWalkOnWater) { @@ -157,9 +157,6 @@ public class MovementDescend extends Movement { res.cost = tentativeCost;// TODO incorporate water swim up cost? return false; } - if (ontoBlock.getBlock() == Blocks.FLOWING_WATER) { - return false; - } if (unprotectedFallHeight <= 11 && (ontoBlock.getBlock() == Blocks.VINE || ontoBlock.getBlock() == Blocks.LADDER)) { // if fall height is greater than or equal to 11, we don't actually grab on to vines or ladders. the more you know // this effectively "resets" our falling speed diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index a82ad110..729a2f1d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -81,7 +81,8 @@ public class MovementFall extends Movement { Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)); Rotation targetRotation = null; Block destBlock = ctx.world().getBlockState(dest).getBlock(); - if (destBlock != Blocks.WATER && destBlock != Blocks.FLOWING_WATER && willPlaceBucket() && !playerFeet.equals(dest)) { + boolean isWater = destBlock == Blocks.WATER || destBlock == Blocks.FLOWING_WATER; + if (!isWater && willPlaceBucket() && !playerFeet.equals(dest)) { if (!InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER)) || ctx.world().provider.isNether()) { return state.setStatus(MovementStatus.UNREACHABLE); } @@ -102,8 +103,8 @@ public class MovementFall extends Movement { } else { state.setTarget(new MovementTarget(toDest, false)); } - if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || destBlock == Blocks.WATER)) { // 0.094 because lilypads - if (destBlock == Blocks.WATER) { // only match water, not flowing water (which we cannot pick up with a bucket) + if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || isWater)) { // 0.094 because lilypads + if (isWater) { // only match water, not flowing water (which we cannot pick up with a bucket) if (InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) { ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY); if (ctx.player().motionY >= 0) { diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 6f161cc0..a2c0e2ff 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -461,6 +461,7 @@ public class PathExecutor implements IPathExecutor, Helper { failed = true; } + @Override public int getPosition() { return pathPosition; } diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index d3883bbb..80677456 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -94,14 +94,14 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (Baritone.settings().legitMine.get()) { addNearby(); } - Goal goal = updateGoal(); - if (goal == null) { + PathingCommand command = updateGoal(); + if (command == null) { // none in range // maybe say something in chat? (ahem impact) cancel(); return null; } - return new PathingCommand(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); + return command; } @Override @@ -114,17 +114,18 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return "Mine " + mining; } - private Goal updateGoal() { + private PathingCommand updateGoal() { + boolean legit = Baritone.settings().legitMine.get(); List locs = knownOreLocations; if (!locs.isEmpty()) { List locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(ctx, loc, locs2)).toArray(Goal[]::new)); knownOreLocations = locs2; - return goal; + return new PathingCommand(goal, legit ? PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH : PathingCommandType.REVALIDATE_GOAL_AND_PATH); } // we don't know any ore locations at the moment - if (!Baritone.settings().legitMine.get()) { + if (!legit) { return null; } // only in non-Xray mode (aka legit mode) do we do this @@ -149,7 +150,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } }; } - return branchPointRunaway; + return new PathingCommand(branchPointRunaway, PathingCommandType.REVALIDATE_GOAL_AND_PATH); } private void rescan(List already, CalculationContext context) { diff --git a/src/main/java/baritone/utils/pathing/PathBase.java b/src/main/java/baritone/utils/pathing/PathBase.java index 04fe9872..3acf80b4 100644 --- a/src/main/java/baritone/utils/pathing/PathBase.java +++ b/src/main/java/baritone/utils/pathing/PathBase.java @@ -17,6 +17,7 @@ package baritone.utils.pathing; +import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; @@ -27,6 +28,9 @@ import net.minecraft.util.math.BlockPos; public abstract class PathBase implements IPath { @Override public PathBase cutoffAtLoadedChunks(Object bsi0) { // <-- cursed cursed cursed + if (!Baritone.settings().cutoffAtLoadBoundary.get()) { + return this; + } BlockStateInterface bsi = (BlockStateInterface) bsi0; for (int i = 0; i < positions().size(); i++) { BlockPos pos = positions().get(i); From 9b42aa36345a21b96c708121196d977f4e1bf939 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 29 Jan 2019 15:34:31 -0800 Subject: [PATCH 067/682] damn you javadocs --- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index ea752082..d8454c1f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -147,7 +147,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, synchronized (pathCalcLock) { if (inProgress != null) { // we are calculating - // are we calculating the right thing though? 🤔 + // are we calculating the right thing though? BetterBlockPos calcFrom = inProgress.getStart(); // if current just succeeded, we should be standing in calcFrom, so that's cool and good // but if current just failed, we should discard this calculation since it doesn't start from where we're standing From 1968f47fc914a134a12589c260428eb31fee1c9d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 29 Jan 2019 19:44:23 -0800 Subject: [PATCH 068/682] add a setting to play with --- src/api/java/baritone/api/Settings.java | 6 ++++++ .../baritone/launch/mixins/MixinChunkRenderContainer.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 9cb4b2ba..a1ae9c71 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -464,6 +464,12 @@ public final class Settings { */ public Setting renderCachedChunks = new Setting<>(false); + /** + * 0.0f = not visible, fully transparent + * 1.0f = fully opaque + */ + public Setting cachedChunksOpacity = new Setting<>(0.5f); + /** * Whether or not to use the "#" command prefix */ diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index 8075f1f2..286ca5d4 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -42,7 +42,7 @@ public class MixinChunkRenderContainer { if (Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { GlStateManager.enableAlpha(); GlStateManager.enableBlend(); - GL14.glBlendColor(0, 0, 0, 0.5F); + GL14.glBlendColor(1, 1, 1, Baritone.settings().cachedChunksOpacity.get()); GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); } else { GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); From b4d307d4cce23df64ccecb2367df74b3f443296d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 29 Jan 2019 19:56:50 -0800 Subject: [PATCH 069/682] cherry pick some movement fixes from builder --- .../pathing/movement/MovementHelper.java | 50 ++++++++++ .../movement/movements/MovementAscend.java | 56 +++-------- .../movement/movements/MovementParkour.java | 38 +------- .../movement/movements/MovementPillar.java | 4 +- .../movement/movements/MovementTraverse.java | 92 +++++++++---------- 5 files changed, 111 insertions(+), 129 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index d07f05e7..f91103d0 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -18,7 +18,9 @@ package baritone.pathing.movement; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.*; import baritone.api.utils.input.Input; import baritone.pathing.movement.MovementState.MovementTarget; @@ -35,6 +37,10 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; + +import static baritone.pathing.movement.Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP; /** * Static helpers for cost calculation @@ -485,4 +491,48 @@ public interface MovementHelper extends ActionCosts, Helper { return state.getBlock() instanceof BlockLiquid && state.getValue(BlockLiquid.LEVEL) != 0; } + + static PlaceResult attemptToPlaceABlock(MovementState state, IBaritone baritone, BlockPos placeAt, boolean preferDown) { + IPlayerContext ctx = baritone.getPlayerContext(); + boolean found = false; + for (int i = 0; i < 5; i++) { + BlockPos against1 = placeAt.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); + if (MovementHelper.canPlaceAgainst(ctx, against1)) { + //if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(placeAt.getX(), placeAt.getY(), placeAt.getZ())) { // get ready to place a throwaway block + if (!throwaway(ctx, true)) { + Helper.HELPER.logDebug("bb pls get me some blocks. dirt or cobble"); + state.setStatus(MovementStatus.UNREACHABLE); + return PlaceResult.NO_OPTION; + } + double faceX = (placeAt.getX() + against1.getX() + 1.0D) * 0.5D; + double faceY = (placeAt.getY() + against1.getY() + 1.0D) * 0.5D; + double faceZ = (placeAt.getZ() + against1.getZ() + 1.0D) * 0.5D; + Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); + RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance()); + 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; + + if (!preferDown) { + // if preferDown is true, we want the last option + // if preferDown is false, we want the first + break; + } + } + } + } + if (ctx.getSelectedBlock().isPresent()) { + BlockPos selectedBlock = ctx.getSelectedBlock().get(); + EnumFacing side = ctx.objectMouseOver().sideHit; + // only way for selectedBlock.equals(placeAt) to be true is if it's replacable + if (selectedBlock.equals(placeAt) || (MovementHelper.canPlaceAgainst(ctx, selectedBlock) && selectedBlock.offset(side).equals(placeAt))) { + return PlaceResult.READY_TO_PLACE; + } + } + return found ? PlaceResult.ATTEMPTING : PlaceResult.NO_OPTION; + } + + enum PlaceResult { + READY_TO_PLACE, ATTEMPTING, NO_OPTION; + } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 2e20dd6e..97eaa7fb 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -21,7 +21,6 @@ import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -32,10 +31,6 @@ import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; - -import java.util.Objects; public class MovementAscend extends Movement { @@ -162,55 +157,30 @@ public class MovementAscend extends Movement { IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace); if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) { - for (int i = 0; i < 5; i++) { - BlockPos anAgainst = positionToPlace.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); - if (anAgainst.equals(src)) { - continue; - } - if (MovementHelper.canPlaceAgainst(ctx, anAgainst)) { - if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block - return state.setStatus(MovementStatus.UNREACHABLE); - } - double faceX = (dest.getX() + anAgainst.getX() + 1.0D) * 0.5D; - double faceY = (dest.getY() + anAgainst.getY()) * 0.5D; - double faceZ = (dest.getZ() + anAgainst.getZ() + 1.0D) * 0.5D; - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true)); - EnumFacing side = ctx.objectMouseOver().sideHit; - - ctx.getSelectedBlock().ifPresent(selectedBlock -> { - if (Objects.equals(selectedBlock, anAgainst) && selectedBlock.offset(side).equals(positionToPlace)) { - ticksWithoutPlacement++; - state.setInput(Input.SNEAK, true); - if (ctx.player().isSneaking()) { - state.setInput(Input.CLICK_RIGHT, true); - } - if (ticksWithoutPlacement > 10) { - // After 10 ticks without placement, we might be standing in the way, move back - state.setInput(Input.MOVE_BACK, true); - } - } else { - state.setInput(Input.CLICK_LEFT, true); // break whatever replaceable block is in the way - } - //System.out.println("Trying to look at " + anAgainst + ", actually looking at" + selectedBlock); - }); - return state; + ticksWithoutPlacement++; + if (MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false) == PlaceResult.READY_TO_PLACE) { + state.setInput(Input.SNEAK, true); + if (ctx.player().isSneaking()) { + state.setInput(Input.CLICK_RIGHT, true); } } - return state.setStatus(MovementStatus.UNREACHABLE); + if (ticksWithoutPlacement > 10) { + // After 10 ticks without placement, we might be standing in the way, move back + state.setInput(Input.MOVE_BACK, true); + } + + return state; } MovementHelper.moveTowards(ctx, state, dest); if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(BlockStateInterface.get(ctx, src.down()))) { return state; // don't jump while walking from a non double slab into a bottom slab } - if (Baritone.settings().assumeStep.get()) { + if (Baritone.settings().assumeStep.get() || ctx.playerFeet().equals(src.up())) { + // no need to hit space if we're already jumping return state; } - if (ctx.playerFeet().equals(src.up())) { - return state; // no need to hit space if we're already jumping - } - if (headBonkClear()) { return state.setInput(Input.JUMP, true); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index ab98d3d0..38fd510a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -20,9 +20,6 @@ package baritone.pathing.movement.movements; import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.RayTraceUtils; -import baritone.api.utils.Rotation; -import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -35,9 +32,6 @@ import net.minecraft.block.BlockStairs; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; public class MovementParkour extends Movement { @@ -209,35 +203,9 @@ public class MovementParkour extends Movement { } } else if (!ctx.playerFeet().equals(src)) { if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - ctx.playerFeet().getY() > 0.0001) { - - if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround) { - BlockPos positionToPlace = dest.down(); - for (int i = 4; i >= 0; i--) { // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory - BlockPos against1 = positionToPlace.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); - if (against1.up().equals(src.offset(direction, 3))) { // we can't turn around that fast - continue; - } - if (MovementHelper.canPlaceAgainst(ctx, against1)) { - if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block - return state.setStatus(MovementStatus.UNREACHABLE); - } - double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; - double faceY = (dest.getY() + against1.getY()) * 0.5D; - double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; - Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); - RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance()); - if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(dest.down())) { - state.setTarget(new MovementState.MovementTarget(place, true)); - break; - } - } - } - ctx.getSelectedBlock().ifPresent(selectedBlock -> { - EnumFacing side = ctx.objectMouseOver().sideHit; - if (MovementHelper.canPlaceAgainst(ctx, selectedBlock) && selectedBlock.offset(side).equals(dest.down())) { - state.setInput(Input.CLICK_RIGHT, true); - } - }); + if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), true) == PlaceResult.READY_TO_PLACE) { + // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory + state.setInput(Input.CLICK_RIGHT, true); } if (dist == 3) { // this is a 2 block gap, dest = src + direction * 3 double xDiff = (src.x + 0.5) - ctx.player().posX; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index b236f7e2..03bdb6f7 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -35,6 +35,8 @@ import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; +import java.util.Objects; + public class MovementPillar extends Movement { public MovementPillar(IBaritone baritone, BetterBlockPos start, BetterBlockPos end) { @@ -224,7 +226,7 @@ public class MovementPillar extends Movement { if (!(fr instanceof BlockAir || fr.isReplaceable(ctx.world(), src))) { state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; - } else if (ctx.player().isSneaking()) { // 1 tick after we're able to place + } else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos()))) { state.setInput(Input.CLICK_RIGHT, true); } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 4a87a8a6..4f9b6b51 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -36,7 +36,6 @@ import net.minecraft.block.BlockFenceGate; import net.minecraft.block.BlockSlab; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; -import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; @@ -136,7 +135,7 @@ public class MovementTraverse extends Movement { } // now that we've checked all possible directions to side place, we actually need to backplace if (srcDown == Blocks.SOUL_SAND || (srcDown instanceof BlockSlab && !((BlockSlab) srcDown).isDouble())) { - return COST_INF; // can't sneak and backplace against soul sand or half slabs =/ + return COST_INF; // can't sneak and backplace against soul sand or half slabs (regardless of whether it's top half or bottom half) =/ } if (srcDown == Blocks.FLOWING_WATER || srcDown == Blocks.WATER) { return COST_INF; // this is obviously impossible @@ -247,53 +246,45 @@ public class MovementTraverse extends Movement { return state; } else { wasTheBridgeBlockAlwaysThere = false; - for (int i = 0; i < 5; i++) { - BlockPos against1 = dest.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); - if (against1.equals(src)) { - continue; - } - against1 = against1.down(); - if (MovementHelper.canPlaceAgainst(ctx, against1)) { - if (!MovementHelper.throwaway(ctx, true)) { // get ready to place a throwaway block - logDebug("bb pls get me some blocks. dirt or cobble"); - return state.setStatus(MovementStatus.UNREACHABLE); - } - if (!Baritone.settings().assumeSafeWalk.get()) { - state.setInput(Input.SNEAK, true); - } - Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock(); - if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 - double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); - if (dist < 0.85) { // 0.5 + 0.3 + epsilon - MovementHelper.moveTowards(ctx, state, dest); - return state.setInput(Input.MOVE_FORWARD, false) - .setInput(Input.MOVE_BACK, true); - } - } - state.setInput(Input.MOVE_BACK, false); - double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; - double faceY = (dest.getY() + against1.getY()) * 0.5D; - double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true)); - - EnumFacing side = ctx.objectMouseOver().sideHit; - if (Objects.equals(ctx.getSelectedBlock().orElse(null), against1) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && ctx.getSelectedBlock().get().offset(side).equals(positionToPlace)) { - return state.setInput(Input.CLICK_RIGHT, true); - } - //System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); - return state.setInput(Input.CLICK_LEFT, true); + Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock(); + if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 + double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); + if (dist < 0.85) { // 0.5 + 0.3 + epsilon + MovementHelper.moveTowards(ctx, state, dest); + return state.setInput(Input.MOVE_FORWARD, false) + .setInput(Input.MOVE_BACK, true); } } - if (!Baritone.settings().assumeSafeWalk.get()) { + double dist1 = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); + PlaceResult p = MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false); + if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.get()) { state.setInput(Input.SNEAK, true); } + switch (p) { + case READY_TO_PLACE: { + if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) { + state.setInput(Input.CLICK_RIGHT, true); + } + return state; + } + case ATTEMPTING: { + if (dist1 > 0.83) { + // might need to go forward a bit + float yaw = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()).getYaw(); + if (Math.abs(state.getTarget().rotation.getYaw() - yaw) < 0.1) { + // but only if our attempted place is straight ahead + return state.setInput(Input.MOVE_FORWARD, true); + } + } else if (ctx.playerRotations().isReallyCloseTo(state.getTarget().rotation)) { + // well i guess theres something in the way + return state.setInput(Input.CLICK_LEFT, true); + } + return state; + } + } if (whereAmI.equals(dest)) { // If we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of // Out.log(from + " " + to + " " + faceX + "," + faceY + "," + faceZ + " " + whereAmI); - if (!MovementHelper.throwaway(ctx, true)) {// get ready to place a throwaway block - logDebug("bb pls get me some blocks. dirt or cobble"); - return state.setStatus(MovementStatus.UNREACHABLE); - } double faceX = (dest.getX() + src.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + src.getY() - 1.0D) * 0.5D; double faceZ = (dest.getZ() + src.getZ() + 1.0D) * 0.5D; @@ -302,25 +293,26 @@ public class MovementTraverse extends Movement { Rotation backToFace = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); float pitch = backToFace.getPitch(); - double dist = Math.max(Math.abs(ctx.player().posX - faceX), Math.abs(ctx.player().posZ - faceZ)); - if (dist < 0.29) { + double dist2 = Math.max(Math.abs(ctx.player().posX - faceX), Math.abs(ctx.player().posZ - faceZ)); + if (dist2 < 0.29) { // see issue #208 float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), ctx.playerHead(), ctx.playerRotations()).getYaw(); state.setTarget(new MovementState.MovementTarget(new Rotation(yaw, pitch), true)); state.setInput(Input.MOVE_BACK, true); } else { state.setTarget(new MovementState.MovementTarget(backToFace, true)); } - state.setInput(Input.SNEAK, true); if (Objects.equals(ctx.getSelectedBlock().orElse(null), goalLook)) { return state.setInput(Input.CLICK_RIGHT, true); // wait to right click until we are able to place } // Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt()); - return state.setInput(Input.CLICK_LEFT, true); - } else { - MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); + if (ctx.playerRotations().isReallyCloseTo(state.getTarget().rotation)) { + state.setInput(Input.CLICK_LEFT, true); + } return state; - // TODO MovementManager.moveTowardsBlock(to); // move towards not look at because if we are bridging for a couple blocks in a row, it is faster if we dont spin around and walk forwards then spin around and place backwards for every block } + MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); + return state; + // TODO MovementManager.moveTowardsBlock(to); // move towards not look at because if we are bridging for a couple blocks in a row, it is faster if we dont spin around and walk forwards then spin around and place backwards for every block } } @@ -342,4 +334,4 @@ public class MovementTraverse extends Movement { } return super.prepared(state); } -} +} \ No newline at end of file From 06b3c5ddb596c425d073df41e862556b837c12ad Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 30 Jan 2019 12:42:26 -0600 Subject: [PATCH 070/682] LeijurvUtils --- .../mixins/MixinChunkRenderContainer.java | 4 +- .../java/baritone/utils/LeijurvUtils.java | 85 +++++++++++++++++++ 2 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 src/main/java/baritone/utils/LeijurvUtils.java diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index 286ca5d4..4a7830f5 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -18,11 +18,11 @@ package baritone.launch.mixins; import baritone.Baritone; +import baritone.utils.LeijurvUtils; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ChunkRenderContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.chunk.RenderChunk; -import org.lwjgl.opengl.GL14; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -42,7 +42,7 @@ public class MixinChunkRenderContainer { if (Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { GlStateManager.enableAlpha(); GlStateManager.enableBlend(); - GL14.glBlendColor(1, 1, 1, Baritone.settings().cachedChunksOpacity.get()); + LeijurvUtils.updateAndGet().run(); GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); } else { GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); diff --git a/src/main/java/baritone/utils/LeijurvUtils.java b/src/main/java/baritone/utils/LeijurvUtils.java new file mode 100644 index 00000000..05aa65db --- /dev/null +++ b/src/main/java/baritone/utils/LeijurvUtils.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.utils; + +import baritone.Baritone; +import org.lwjgl.opengl.GL14; + +import java.lang.invoke.LambdaMetafactory; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; + +/** + * Is your name Leijurv and you have a severe handicap for X? Well, no worries! This class has YOU covered! + * + * @author Brady + * @since 1/30/2019 + */ +public class LeijurvUtils { + + private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); + + private static Runnable glBlendColorChunkOwnage = null; + private static float existingAlpha; + + public static Runnable updateAndGet() { + float currentAlpha = Baritone.settings().cachedChunksOpacity.get(); + if (glBlendColorChunkOwnage == null || existingAlpha != currentAlpha) { + glBlendColorChunkOwnage = createBlendColorRunnable(1, 1, 1, existingAlpha = currentAlpha); + } + return glBlendColorChunkOwnage; + } + + /** + * Hahhahaha + * WHY???? you may ask. well: + * + * basically proguard sucks (actually the gradle automated setup for it does) and I'm too + * lazy to actually make it work. (It is unable to recognize the GL14 class). This is an + * AWESOME workaround by creating a runnable for the {@code glBlendColor} method without having + * to directly reference the method itself with the added bonus of pre-filling the invocation arguments. + * + * @param r red + * @param g green + * @param b blue + * @param a alpha + * @return Epic runnable that calls {@link GL14#glBlendColor(float, float, float, float)} + */ + public static Runnable createBlendColorRunnable(float r, float g, float b, float a) { + try { + MethodHandle glBlendColor = LOOKUP.findStatic( + Class.forName("org.lwjgl.opengl.GL14"), + "glBlendColor", + MethodType.methodType(Void.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE) + ); + + // noinspection unchecked + return (Runnable) LambdaMetafactory.metafactory( + LOOKUP, + "run", + glBlendColor.type().changeReturnType(Runnable.class), + MethodType.methodType(Void.TYPE), + glBlendColor, + MethodType.methodType(Void.TYPE) + ).dynamicInvoker().invoke(r, g, b, a); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } +} From 8947eff3b19b7705f6127bdb7a9700660c160a33 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 30 Jan 2019 11:42:46 -0800 Subject: [PATCH 071/682] bsi might be old --- .../java/baritone/launch/mixins/MixinChunkRenderWorker.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java index 3621b664..a8247a9b 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java @@ -31,7 +31,8 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(ChunkRenderWorker.class) public abstract class MixinChunkRenderWorker { - @Shadow protected abstract boolean isChunkExisting(BlockPos pos, World worldIn); + @Shadow + protected abstract boolean isChunkExisting(BlockPos pos, World worldIn); @Redirect( method = "processTask", @@ -45,7 +46,7 @@ public abstract class MixinChunkRenderWorker { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { - return baritone.bsi.isLoaded(pos.getX(), pos.getZ()); + return baritone.bsi.isLoaded(pos.getX(), pos.getZ()) || this.isChunkExisting(pos, world); } } From 68a9a1439a9b930daa57b7b9d33f263996a3dccc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 30 Jan 2019 11:45:03 -0800 Subject: [PATCH 072/682] maybe this will allow emoji --- build.gradle | 1 + src/main/java/baritone/behavior/PathingBehavior.java | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 8583642d..a9477967 100755 --- a/build.gradle +++ b/build.gradle @@ -101,6 +101,7 @@ mixin { javadoc { options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error options.linkSource true + options.encoding "UTF-8" source += sourceSets.api.allJava classpath += sourceSets.api.compileClasspath } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index d8454c1f..ea752082 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -147,7 +147,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, synchronized (pathCalcLock) { if (inProgress != null) { // we are calculating - // are we calculating the right thing though? + // are we calculating the right thing though? 🤔 BetterBlockPos calcFrom = inProgress.getStart(); // if current just succeeded, we should be standing in calcFrom, so that's cool and good // but if current just failed, we should discard this calculation since it doesn't start from where we're standing From 90fa347fc2a616984662533e6cd4a0e202a23d15 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 30 Jan 2019 11:54:02 -0800 Subject: [PATCH 073/682] also get rid of warning in build stage --- build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/build.gradle b/build.gradle index a9477967..bcd0fdeb 100755 --- a/build.gradle +++ b/build.gradle @@ -48,6 +48,7 @@ apply plugin: 'org.spongepowered.mixin' sourceCompatibility = targetCompatibility = '1.8' compileJava { sourceCompatibility = targetCompatibility = '1.8' + options.encoding = "UTF-8" } sourceSets { From 22bd5be5a9b9fbb085dbb5be02f0d22b7ea47250 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 30 Jan 2019 11:54:38 -0800 Subject: [PATCH 074/682] explain --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index bcd0fdeb..f356a3b2 100755 --- a/build.gradle +++ b/build.gradle @@ -48,7 +48,7 @@ apply plugin: 'org.spongepowered.mixin' sourceCompatibility = targetCompatibility = '1.8' compileJava { sourceCompatibility = targetCompatibility = '1.8' - options.encoding = "UTF-8" + options.encoding = "UTF-8" // allow emoji in comments :^) } sourceSets { @@ -102,7 +102,7 @@ mixin { javadoc { options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error options.linkSource true - options.encoding "UTF-8" + options.encoding "UTF-8" // allow emoji in comments :^) source += sourceSets.api.allJava classpath += sourceSets.api.compileClasspath } From b177ae7ee6494705257ebc6bbeebef89b635aad4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 30 Jan 2019 11:57:54 -0800 Subject: [PATCH 075/682] proguard can just ignore GL14 reference actually --- scripts/proguard.pro | 3 + .../mixins/MixinChunkRenderContainer.java | 4 +- .../java/baritone/utils/LeijurvUtils.java | 85 ------------------- 3 files changed, 5 insertions(+), 87 deletions(-) delete mode 100644 src/main/java/baritone/utils/LeijurvUtils.java diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 07e1ec41..df6ad43a 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -12,6 +12,9 @@ -flattenpackagehierarchy -repackageclasses 'baritone' +# lwjgl is weird +-dontwarn org.lwjgl.opengl.GL14 + -keep class baritone.api.** { *; } # this is the keep api # service provider needs these class names diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index 4a7830f5..e2c1e025 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -18,11 +18,11 @@ package baritone.launch.mixins; import baritone.Baritone; -import baritone.utils.LeijurvUtils; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ChunkRenderContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.chunk.RenderChunk; +import org.lwjgl.opengl.GL14; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -42,7 +42,7 @@ public class MixinChunkRenderContainer { if (Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { GlStateManager.enableAlpha(); GlStateManager.enableBlend(); - LeijurvUtils.updateAndGet().run(); + GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.get()); GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); } else { GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); diff --git a/src/main/java/baritone/utils/LeijurvUtils.java b/src/main/java/baritone/utils/LeijurvUtils.java deleted file mode 100644 index 05aa65db..00000000 --- a/src/main/java/baritone/utils/LeijurvUtils.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.utils; - -import baritone.Baritone; -import org.lwjgl.opengl.GL14; - -import java.lang.invoke.LambdaMetafactory; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; - -/** - * Is your name Leijurv and you have a severe handicap for X? Well, no worries! This class has YOU covered! - * - * @author Brady - * @since 1/30/2019 - */ -public class LeijurvUtils { - - private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); - - private static Runnable glBlendColorChunkOwnage = null; - private static float existingAlpha; - - public static Runnable updateAndGet() { - float currentAlpha = Baritone.settings().cachedChunksOpacity.get(); - if (glBlendColorChunkOwnage == null || existingAlpha != currentAlpha) { - glBlendColorChunkOwnage = createBlendColorRunnable(1, 1, 1, existingAlpha = currentAlpha); - } - return glBlendColorChunkOwnage; - } - - /** - * Hahhahaha - * WHY???? you may ask. well: - * - * basically proguard sucks (actually the gradle automated setup for it does) and I'm too - * lazy to actually make it work. (It is unable to recognize the GL14 class). This is an - * AWESOME workaround by creating a runnable for the {@code glBlendColor} method without having - * to directly reference the method itself with the added bonus of pre-filling the invocation arguments. - * - * @param r red - * @param g green - * @param b blue - * @param a alpha - * @return Epic runnable that calls {@link GL14#glBlendColor(float, float, float, float)} - */ - public static Runnable createBlendColorRunnable(float r, float g, float b, float a) { - try { - MethodHandle glBlendColor = LOOKUP.findStatic( - Class.forName("org.lwjgl.opengl.GL14"), - "glBlendColor", - MethodType.methodType(Void.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE) - ); - - // noinspection unchecked - return (Runnable) LambdaMetafactory.metafactory( - LOOKUP, - "run", - glBlendColor.type().changeReturnType(Runnable.class), - MethodType.methodType(Void.TYPE), - glBlendColor, - MethodType.methodType(Void.TYPE) - ).dynamicInvoker().invoke(r, g, b, a); - } catch (Throwable e) { - throw new RuntimeException(e); - } - } -} From b953da0341344632e54d4b3132a1ce3da35b22f7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 30 Jan 2019 12:19:15 -0800 Subject: [PATCH 076/682] more accurate isEmpty --- .../launch/mixins/MixinRenderChunk.java | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java b/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java index 47402c6b..4190ae59 100644 --- a/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java +++ b/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java @@ -43,15 +43,28 @@ public class MixinRenderChunk { ) ) private boolean isEmpty(ChunkCache chunkCache) { + if (!chunkCache.isEmpty()) { + return false; + } if (Baritone.settings().renderCachedChunks.get()) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { - return false; + BlockPos position = ((RenderChunk) (Object) this).getPosition(); + // RenderChunk extends from -1,-1,-1 to +16,+16,+16 + // then the constructor of ChunkCache extends it one more (presumably to get things like the connected status of fences? idk) + // so if ANY of the adjacent chunks are loaded, we are unempty + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + if (baritone.bsi.isLoaded(16 * dx + position.getX(), 16 * dz + position.getZ())) { + return false; + } + } + } } } - return chunkCache.isEmpty(); + return true; } @Redirect( From 272dd7942650d7fb45510e502f6858a3a628b8d1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 30 Jan 2019 15:49:37 -0800 Subject: [PATCH 077/682] much needed pathing overhaul --- .../pathing/calc/AStarPathFinder.java | 58 +++++-------------- .../pathing/calc/AbstractNodeCostSearch.java | 56 ++++++++++++++---- 2 files changed, 57 insertions(+), 57 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index b32fc99f..6f44fac2 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -25,7 +25,6 @@ import baritone.api.utils.BetterBlockPos; import baritone.pathing.calc.openset.BinaryHeapOpenSet; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Moves; -import baritone.utils.Helper; import baritone.utils.pathing.BetterWorldBorder; import baritone.utils.pathing.Favoring; import baritone.utils.pathing.MutableMoveResult; @@ -37,7 +36,7 @@ import java.util.Optional; * * @author leijurv */ -public final class AStarPathFinder extends AbstractNodeCostSearch implements Helper { +public final class AStarPathFinder extends AbstractNodeCostSearch { private final Favoring favoring; private final CalculationContext calcContext; @@ -55,14 +54,12 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel startNode.combinedCost = startNode.estimatedCostToGoal; BinaryHeapOpenSet openSet = new BinaryHeapOpenSet(); openSet.insert(startNode); - bestSoFar = new PathNode[COEFFICIENTS.length];//keep track of the best node by the metric of (estimatedCostToGoal + cost / COEFFICIENTS[i]) - double[] bestHeuristicSoFar = new double[COEFFICIENTS.length]; + double[] bestHeuristicSoFar = new double[COEFFICIENTS.length];//keep track of the best node by the metric of (estimatedCostToGoal + cost / COEFFICIENTS[i]) for (int i = 0; i < bestHeuristicSoFar.length; i++) { bestHeuristicSoFar[i] = startNode.estimatedCostToGoal; bestSoFar[i] = startNode; } MutableMoveResult res = new MutableMoveResult(); - Favoring favored = favoring; BetterWorldBorder worldBorder = new BetterWorldBorder(calcContext.world.getWorldBorder()); long startTime = System.currentTimeMillis(); boolean slowPath = Baritone.settings().slowPath.get(); @@ -75,10 +72,10 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel int numNodes = 0; int numMovementsConsidered = 0; int numEmptyChunk = 0; - boolean favoring = !favored.isEmpty(); + boolean isFavoring = !favoring.isEmpty(); int timeCheckInterval = 1 << 6; int pathingMaxChunkBorderFetch = Baritone.settings().pathingMaxChunkBorderFetch.get(); // grab all settings beforehand so that changing settings during pathing doesn't cause a crash or unpredictable behavior - boolean minimumImprovementRepropagation = Baritone.settings().minimumImprovementRepropagation.get(); + double minimumImprovement = Baritone.settings().minimumImprovementRepropagation.get() ? MIN_IMPROVEMENT : 0; while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && !cancelRequested) { if ((numNodes & (timeCheckInterval - 1)) == 0) { // only call this once every 64 nodes (about half a millisecond) long now = System.currentTimeMillis(); // since nanoTime is slow on windows (takes many microseconds) @@ -136,21 +133,13 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel throw new IllegalStateException(moves + " " + res.y + " " + (currentNode.y + moves.yOffset)); } long hashCode = BetterBlockPos.longHash(res.x, res.y, res.z); - if (favoring) { + if (isFavoring) { // see issue #18 - actionCost *= favored.calculate(hashCode); + actionCost *= favoring.calculate(hashCode); } PathNode neighbor = getNodeAtPosition(res.x, res.y, res.z, hashCode); double tentativeCost = currentNode.cost + actionCost; - if (tentativeCost < neighbor.cost) { - double improvementBy = neighbor.cost - tentativeCost; - // there are floating point errors caused by random combinations of traverse and diagonal over a flat area - // that means that sometimes there's a cost improvement of like 10 ^ -16 - // it's not worth the time to update the costs, decrease-key the heap, potentially repropagate, etc - if (improvementBy < 0.01 && minimumImprovementRepropagation) { - // who cares about a hundredth of a tick? that's half a millisecond for crying out loud! - continue; - } + if (neighbor.cost - tentativeCost > minimumImprovement) { neighbor.previous = currentNode; neighbor.cost = tentativeCost; neighbor.combinedCost = tentativeCost + neighbor.estimatedCostToGoal; @@ -159,12 +148,9 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel } else { openSet.insert(neighbor);//dont double count, dont insert into open set if it's already there } - for (int i = 0; i < bestSoFar.length; i++) { + for (int i = 0; i < COEFFICIENTS.length; i++) { double heuristic = neighbor.estimatedCostToGoal + neighbor.cost / COEFFICIENTS[i]; - if (heuristic < bestHeuristicSoFar[i]) { - if (bestHeuristicSoFar[i] - heuristic < 0.01 && minimumImprovementRepropagation) { - continue; - } + if (bestHeuristicSoFar[i] - heuristic > minimumImprovement) { bestHeuristicSoFar[i] = heuristic; bestSoFar[i] = neighbor; if (getDistFromStartSq(neighbor) > MIN_DIST_PATH * MIN_DIST_PATH) { @@ -182,28 +168,10 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel System.out.println("Open set size: " + openSet.size()); System.out.println("PathNode map size: " + mapSize()); System.out.println((int) (numNodes * 1.0 / ((System.currentTimeMillis() - startTime) / 1000F)) + " nodes per second"); - double bestDist = 0; - for (int i = 0; i < bestSoFar.length; i++) { - if (bestSoFar[i] == null) { - continue; - } - double dist = getDistFromStartSq(bestSoFar[i]); - if (dist > bestDist) { - bestDist = dist; - } - if (dist > MIN_DIST_PATH * MIN_DIST_PATH) { // square the comparison since distFromStartSq is squared - logDebug("Took " + (System.currentTimeMillis() - startTime) + "ms, A* cost coefficient " + COEFFICIENTS[i] + ", " + numMovementsConsidered + " movements considered"); - if (COEFFICIENTS[i] >= 3) { - System.out.println("Warning: cost coefficient is greater than three! Probably means that"); - System.out.println("the path I found is pretty terrible (like sneak-bridging for dozens of blocks)"); - System.out.println("But I'm going to do it anyway, because yolo"); - } - System.out.println("Path goes for " + Math.sqrt(dist) + " blocks"); - return Optional.of(new Path(startNode, bestSoFar[i], numNodes, goal, calcContext)); - } + Optional result = bestSoFar(true, numNodes); + if (result.isPresent()) { + logDebug("Took " + (System.currentTimeMillis() - startTime) + "ms, " + numMovementsConsidered + " movements considered"); } - logDebug("Even with a cost coefficient of " + COEFFICIENTS[COEFFICIENTS.length - 1] + ", I couldn't get more than " + Math.sqrt(bestDist) + " blocks"); - logDebug("No path found =("); - return Optional.empty(); + return result; } } diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 625e8e59..a9974e8d 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -34,7 +34,7 @@ import java.util.Optional; * * @author leijurv */ -public abstract class AbstractNodeCostSearch implements IPathFinder { +public abstract class AbstractNodeCostSearch implements IPathFinder, Helper { protected final int startX; protected final int startY; @@ -53,7 +53,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { protected PathNode mostRecentConsidered; - protected PathNode[] bestSoFar; + protected final PathNode[] bestSoFar = new PathNode[COEFFICIENTS.length]; private volatile boolean isFinished; @@ -63,13 +63,23 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { * This is really complicated and hard to explain. I wrote a comment in the old version of MineBot but it was so * long it was easier as a Google Doc (because I could insert charts). * - * @see + * @see here */ - protected static final double[] COEFFICIENTS = {1.5, 2, 2.5, 3, 4, 5, 10}; // big TODO tune + protected static final double[] COEFFICIENTS = {1.5, 2, 2.5, 3, 4, 5, 10}; + /** * If a path goes less than 5 blocks and doesn't make it to its goal, it's not worth considering. */ - protected final static double MIN_DIST_PATH = 5; + protected static final double MIN_DIST_PATH = 5; + + /** + * there are floating point errors caused by random combinations of traverse and diagonal over a flat area + * that means that sometimes there's a cost improvement of like 10 ^ -16 + * it's not worth the time to update the costs, decrease-key the heap, potentially repropagate, etc + *

+ * who cares about a hundredth of a tick? that's half a millisecond for crying out loud! + */ + protected static final double MIN_IMPROVEMENT = 0.01; AbstractNodeCostSearch(int startX, int startY, int startZ, Goal goal, CalculationContext context) { this.startX = startX; @@ -170,25 +180,43 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { return Optional.ofNullable(mostRecentConsidered).map(node -> new Path(startNode, node, 0, goal, context)); } - protected int mapSize() { - return map.size(); + @Override + public Optional bestPathSoFar() { + return bestSoFar(false, 0); } - @Override - public Optional bestPathSoFar() { // TODO cleanup code duplication between here and AStarPathFinder + protected Optional bestSoFar(boolean logInfo, int numNodes) { if (startNode == null || bestSoFar == null) { return Optional.empty(); } - for (int i = 0; i < bestSoFar.length; i++) { + double bestDist = 0; + for (int i = 0; i < COEFFICIENTS.length; i++) { if (bestSoFar[i] == null) { continue; } - if (getDistFromStartSq(bestSoFar[i]) > MIN_DIST_PATH * MIN_DIST_PATH) { // square the comparison since distFromStartSq is squared - return Optional.of(new Path(startNode, bestSoFar[i], 0, goal, context)); + double dist = getDistFromStartSq(bestSoFar[i]); + if (dist > bestDist) { + bestDist = dist; + } + if (dist > MIN_DIST_PATH * MIN_DIST_PATH) { // square the comparison since distFromStartSq is squared + if (logInfo) { + if (COEFFICIENTS[i] >= 3) { + System.out.println("Warning: cost coefficient is greater than three! Probably means that"); + System.out.println("the path I found is pretty terrible (like sneak-bridging for dozens of blocks)"); + System.out.println("But I'm going to do it anyway, because yolo"); + } + System.out.println("Path goes for " + Math.sqrt(dist) + " blocks"); + logDebug("A* cost coefficient " + COEFFICIENTS[i]); + } + return Optional.of(new Path(startNode, bestSoFar[i], numNodes, goal, context)); } } // instead of returning bestSoFar[0], be less misleading // if it actually won't find any path, don't make them think it will by rendering a dark blue that will never actually happen + if (logInfo) { + logDebug("Even with a cost coefficient of " + COEFFICIENTS[COEFFICIENTS.length - 1] + ", I couldn't get more than " + Math.sqrt(bestDist) + " blocks"); + logDebug("No path found =("); + } return Optional.empty(); } @@ -205,4 +233,8 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { public BetterBlockPos getStart() { return new BetterBlockPos(startX, startY, startZ); } + + protected int mapSize() { + return map.size(); + } } From 246c00c7733885a6ab8026e6a9088b829d2f34ea Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 31 Jan 2019 19:19:44 -0800 Subject: [PATCH 078/682] dont repeat that --- .../java/baritone/pathing/path/PathExecutor.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index a2c0e2ff..8ad0db59 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -377,21 +377,21 @@ public class PathExecutor implements IPathExecutor, Helper { } private boolean shouldSprintNextTick() { + boolean requested = behavior.baritone.getInputOverrideHandler().isInputForcedDown(Input.SPRINT); + + // we'll take it from here, no need for minecraft to see we're holding down control and sprint for us + behavior.baritone.getInputOverrideHandler().setInputForceState(Input.SPRINT, false); + // first and foremost, if allowSprint is off, or if we don't have enough hunger, don't try and sprint if (!new CalculationContext(behavior.baritone).canSprint) { - behavior.baritone.getInputOverrideHandler().setInputForceState(Input.SPRINT, false); return false; } // if the movement requested sprinting, then we're done - if (behavior.baritone.getInputOverrideHandler().isInputForcedDown(Input.SPRINT)) { - behavior.baritone.getInputOverrideHandler().setInputForceState(Input.SPRINT, false); + if (requested) { return true; } - // we'll take it from here, no need for minecraft to see we're holding down control and sprint for us - behavior.baritone.getInputOverrideHandler().setInputForceState(Input.SPRINT, false); - // however, descend doesn't request sprinting, beceause it doesn't know the context of what movement comes after it IMovement current = path.movements().get(pathPosition); if (current instanceof MovementDescend) { From 747bee41b75633224a851f249e3cf4c0904f6221 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 31 Jan 2019 20:26:24 -0800 Subject: [PATCH 079/682] holding control shouldnt make all bots sprint --- .../baritone/launch/mixins/MixinEntityPlayerSP.java | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index bbf92011..6e0eb3f0 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -18,6 +18,7 @@ package baritone.launch.mixins; import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; import baritone.api.behavior.IPathingBehavior; import baritone.api.event.events.ChatEvent; import baritone.api.event.events.PlayerUpdateEvent; @@ -100,8 +101,16 @@ public class MixinEntityPlayerSP { ) private boolean isKeyDown(KeyBinding keyBinding) { SprintStateEvent event = new SprintStateEvent(); - BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerSprintState(event); - return event.getState() == null ? keyBinding.isKeyDown() : event.getState(); + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); + baritone.getGameEventHandler().onPlayerSprintState(event); + if (event.getState() != null) { + return event.getState(); + } + if (baritone == BaritoneAPI.getProvider().getPrimaryBaritone()) { + // hitting control shouldn't make all bots sprint + return false; + } + return keyBinding.isKeyDown(); } @Inject( From 5c1cf050e2bf5bd83566fb17bdc104d15d83c0c6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 31 Jan 2019 20:27:14 -0800 Subject: [PATCH 080/682] im idiot --- src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index 6e0eb3f0..87cc6562 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -106,7 +106,7 @@ public class MixinEntityPlayerSP { if (event.getState() != null) { return event.getState(); } - if (baritone == BaritoneAPI.getProvider().getPrimaryBaritone()) { + if (baritone != BaritoneAPI.getProvider().getPrimaryBaritone()) { // hitting control shouldn't make all bots sprint return false; } From dc3bab26deb69ccb42159245c2a695521637490a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 1 Feb 2019 22:54:14 -0800 Subject: [PATCH 081/682] 6 months =D --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 7782651a..1826eb20 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ Baritone is the pathfinding system used in [Impact](https://impactdevelopment.gi This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). +Have committed at least once a day for the last 6 months =D 🦀 + Here are some links to help to get started: - [Features](FEATURES.md) From 913247996e9250d5c734a44dca0fd103f7c5fcfd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 2 Feb 2019 14:23:01 -0800 Subject: [PATCH 082/682] smh my head. who right clicks gradle tasks?? --- SETUP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SETUP.md b/SETUP.md index 6400990d..a479227b 100644 --- a/SETUP.md +++ b/SETUP.md @@ -65,7 +65,7 @@ $ gradlew build ![Image](https://i.imgur.com/PE6r9iN.png) -- Right click on **build** and press **Run** +- Double click on **build** to run it ## Artifacts From d799fac688b345bb66cbac9d76b3795b558340cf Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 3 Feb 2019 19:27:28 -0800 Subject: [PATCH 083/682] epicer gradle output --- .../src/main/java/baritone/gradle/task/ProguardTask.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java index 351ded3a..4d10e7f5 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java @@ -298,8 +298,8 @@ public class ProguardTask extends BaritoneGradleTask { .start(); // We can't do output inherit process I/O with gradle for some reason and have it work, so we have to do this - this.printOutputLog(p.getInputStream()); - this.printOutputLog(p.getErrorStream()); + this.printOutputLog(p.getInputStream(), System.out); + this.printOutputLog(p.getErrorStream(), System.err); // Halt the current thread until the process is complete, if the exit code isn't 0, throw an exception int exitCode = p.waitFor(); @@ -308,12 +308,12 @@ public class ProguardTask extends BaritoneGradleTask { } } - private void printOutputLog(InputStream stream) { + private void printOutputLog(InputStream stream, PrintStream outerr) { new Thread(() -> { try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { String line; while ((line = reader.readLine()) != null) { - System.out.println(line); + outerr.println(line); } } catch (Exception e) { e.printStackTrace(); From 0e1534613cf82b9e98020da9d7c73c73780b686e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 3 Feb 2019 19:34:24 -0800 Subject: [PATCH 084/682] appease codacy --- .../baritone/pathing/movement/movements/MovementTraverse.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 4f9b6b51..74e4b6f3 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -281,6 +281,8 @@ public class MovementTraverse extends Movement { } return state; } + default: + break; } if (whereAmI.equals(dest)) { // If we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of From 5382d265f2ba13045fcc77af8132293c521ac5dc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 3 Feb 2019 19:46:59 -0800 Subject: [PATCH 085/682] crucial performance optimization --- src/main/java/baritone/pathing/calc/AStarPathFinder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index 6f44fac2..fda41cfd 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -153,7 +153,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch { if (bestHeuristicSoFar[i] - heuristic > minimumImprovement) { bestHeuristicSoFar[i] = heuristic; bestSoFar[i] = neighbor; - if (getDistFromStartSq(neighbor) > MIN_DIST_PATH * MIN_DIST_PATH) { + if (failing && getDistFromStartSq(neighbor) > MIN_DIST_PATH * MIN_DIST_PATH) { failing = false; } } From 04e7da9b73e104052b0493dff7a7bcdd6679d5b4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 13:07:05 -0800 Subject: [PATCH 086/682] lower walk into can be water, but not upper --- .../baritone/pathing/movement/movements/MovementDiagonal.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index a47fc263..0abaccf7 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -114,7 +114,7 @@ public class MovementDiagonal extends Movement { return; } IBlockState pb3 = context.get(destX, y + 1, z); - if (optionA == 0 && ((MovementHelper.avoidWalkingInto(pb2.getBlock()) && pb2.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb3.getBlock()) && pb3.getBlock() != Blocks.WATER))) { + if (optionA == 0 && ((MovementHelper.avoidWalkingInto(pb2.getBlock()) && pb2.getBlock() != Blocks.WATER) || MovementHelper.avoidWalkingInto(pb3.getBlock()))) { // at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction return; } @@ -123,7 +123,7 @@ public class MovementDiagonal extends Movement { // and finally, if the cost is nonzero for both ways to approach this diagonal, it's not possible return; } - if (optionB == 0 && ((MovementHelper.avoidWalkingInto(pb0.getBlock()) && pb0.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb1.getBlock()) && pb1.getBlock() != Blocks.WATER))) { + if (optionB == 0 && ((MovementHelper.avoidWalkingInto(pb0.getBlock()) && pb0.getBlock() != Blocks.WATER) || MovementHelper.avoidWalkingInto(pb1.getBlock()))) { // and now that option B is fully calculated, see if we can edge around that way return; } From ee23d59e111ba741aa9a6539c3302897310c2c59 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 13:07:16 -0800 Subject: [PATCH 087/682] now we can cache flowing water properly --- src/main/java/baritone/cache/ChunkPacker.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index 60ac6331..e2903cea 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -124,12 +124,13 @@ public final class ChunkPacker { private static PathingBlockType getPathingBlockType(IBlockState state) { Block block = state.getBlock(); - if (block == Blocks.WATER && !MovementHelper.isFlowing(state)) { + if ((block == Blocks.WATER || block == Blocks.FLOWING_WATER) && !MovementHelper.isFlowing(state)) { // only water source blocks are plausibly usable, flowing water should be avoid + // FLOWING_WATER is a waterfall, it doesn't really matter and caching it as AVOID just makes it look wrong return PathingBlockType.WATER; } - if (MovementHelper.avoidWalkingInto(block) || block == Blocks.FLOWING_WATER || MovementHelper.isBottomSlab(state)) { + if (MovementHelper.avoidWalkingInto(block) || MovementHelper.isBottomSlab(state)) { return PathingBlockType.AVOID; } // We used to do an AABB check here From 57b2e360ca43cfc1639faf085032621594c9959b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 13:27:35 -0800 Subject: [PATCH 088/682] dont include current movement cost while deciding when to plan ahead --- .../baritone/api/behavior/IPathingBehavior.java | 15 ++++++++++++++- .../java/baritone/behavior/PathingBehavior.java | 4 +++- .../java/baritone/pathing/path/PathExecutor.java | 2 ++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index d28195ae..64be71d5 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -38,11 +38,24 @@ public interface IPathingBehavior extends IBehavior { * @return The estimated remaining ticks in the current segment. */ default Optional ticksRemainingInSegment() { + return ticksRemainingInSegment(true); + } + + /** + * Returns the estimated remaining ticks in the current pathing + * segment. Given that the return type is an optional, {@link Optional#empty()} + * will be returned in the case that there is no current segment being pathed. + * + * @param includeCurrentMovement whether or not to include the entirety of the cost of the currently executing movement in the total + * @return The estimated remaining ticks in the current segment. + */ + default Optional ticksRemainingInSegment(boolean includeCurrentMovement) { IPathExecutor current = getCurrent(); if (current == null) { return Optional.empty(); } - return Optional.of(current.getPath().ticksRemainingFrom(current.getPosition())); + int start = includeCurrentMovement ? current.getPosition() : current.getPosition() + 1; + return Optional.of(current.getPath().ticksRemainingFrom(start)); } /** diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index ea752082..8339625d 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -193,8 +193,10 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // and this path doesn't get us all the way there return; } - if (ticksRemainingInSegment().get() < Baritone.settings().planningTickLookAhead.get()) { + if (ticksRemainingInSegment(false).get() < Baritone.settings().planningTickLookAhead.get()) { // and this path has 7.5 seconds or less left + // don't include the current movement so a very long last movement (e.g. descend) doesn't trip it up + // if we actually included current, it wouldn't start planning ahead until the last movement was done, if the last movement took more than 7.5 seconds on its own logDebug("Path almost over. Planning ahead..."); queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED); findPathInNewThread(current.getPath().getDest(), false); diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 8ad0db59..1b59f8e3 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -249,6 +249,8 @@ public class PathExecutor implements IPathExecutor, Helper { return true; } if (!movement.calculatedWhileLoaded() && currentCost - currentMovementOriginalCostEstimate > Baritone.settings().maxCostIncrease.get() && canCancel) { + // don't do this if the movement was calculated while loaded + // that means that this isn't a cache error, it's just part of the path interfering with a later part logDebug("Original cost " + currentMovementOriginalCostEstimate + " current cost " + currentCost + ". Cancelling."); cancel(); return true; From 798f25ff81dc767fe69768831aa468827c0c64f0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 13:52:11 -0800 Subject: [PATCH 089/682] dont glitch weirdly when failing a parkour jump --- .../baritone/pathing/movement/movements/MovementParkour.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 38fd510a..74acac48 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -187,6 +187,11 @@ public class MovementParkour extends Movement { logDebug("Pausing parkour since hand is active"); return state; } + if (ctx.playerFeet().y < src.y) { + // we have fallen + logDebug("sorry"); + return state.setStatus(MovementStatus.UNREACHABLE); + } if (dist >= 4) { state.setInput(Input.SPRINT, true); } From 2cbe77aa049e203a09ee37fab66aeaf9b1d4c65f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 15:24:27 -0800 Subject: [PATCH 090/682] many fixes --- src/api/java/baritone/api/Settings.java | 8 +++- .../mixins/MixinChunkRenderContainer.java | 14 ++---- .../launch/mixins/MixinRenderList.java | 46 +++++++++++++++++++ .../launch/mixins/MixinVboRenderList.java | 46 +++++++++++++++++++ src/launch/resources/mixins.baritone.json | 2 + .../java/baritone/event/GameEventHandler.java | 10 ++-- 6 files changed, 113 insertions(+), 13 deletions(-) create mode 100644 src/launch/java/baritone/launch/mixins/MixinRenderList.java create mode 100644 src/launch/java/baritone/launch/mixins/MixinVboRenderList.java diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index a1ae9c71..db97999b 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -460,7 +460,13 @@ public final class Settings { public final Setting pathThroughCachedOnly = new Setting<>(false); /** - * 😎 + * 😎 Render cached chunks as semitransparent. + *

+ * Can be very useful on servers with low render distance. + *

+ * Note that flowing water is cached as AVOID, which is rendered as lava. As you get closer, you may therefore see lava falls being replaced with water falls. + *

+ * SOLID is rendered as stone in the overworld, netherrack in the nether, and end stone in the end */ public Setting renderCachedChunks = new Setting<>(false); diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index e2c1e025..fef16d6b 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -38,15 +38,11 @@ public class MixinChunkRenderContainer { at = @At("HEAD") ) private void preRenderChunk(RenderChunk renderChunkIn, CallbackInfo ci) { - if (Baritone.settings().renderCachedChunks.get()) { - if (Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { - GlStateManager.enableAlpha(); - GlStateManager.enableBlend(); - GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.get()); - GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); - } else { - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); - } + if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { + GlStateManager.enableAlpha(); + GlStateManager.enableBlend(); + GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.get()); + GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); } } } diff --git a/src/launch/java/baritone/launch/mixins/MixinRenderList.java b/src/launch/java/baritone/launch/mixins/MixinRenderList.java new file mode 100644 index 00000000..55d1da70 --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinRenderList.java @@ -0,0 +1,46 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import baritone.Baritone; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderList; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import static org.lwjgl.opengl.GL11.*; + +@Mixin(RenderList.class) +public class MixinRenderList { + + @Inject( + method = "renderChunkLayer", + at = @At( + value = "INVOKE", + target = "net/minecraft/client/renderer/GlStateManager.popMatrix()V" + ) + ) + private void renderChunkLayer(CallbackInfo info) { + if (Baritone.settings().renderCachedChunks.get()) { + // reset the blend func to normal (not dependent on constant alpha) + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); + } + } +} diff --git a/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java b/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java new file mode 100644 index 00000000..c2c9fd8c --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java @@ -0,0 +1,46 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import baritone.Baritone; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.VboRenderList; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import static org.lwjgl.opengl.GL11.*; + +@Mixin(VboRenderList.class) +public class MixinVboRenderList { + + @Inject( + method = "renderChunkLayer", + at = @At( + value = "INVOKE", + target = "net/minecraft/client/renderer/GlStateManager.popMatrix()V" + ) + ) + private void renderChunkLayer(CallbackInfo info) { + if (Baritone.settings().renderCachedChunks.get()) { + // reset the blend func to normal (not dependent on constant alpha) + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); + } + } +} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index aa9a724f..ddd3a718 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -23,6 +23,8 @@ "MixinNetHandlerPlayClient", "MixinNetworkManager", "MixinRenderChunk", + "MixinRenderList", + "MixinVboRenderList", "MixinWorldClient" ] } \ No newline at end of file diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 1bf63502..84bac80f 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -47,9 +47,13 @@ public final class GameEventHandler implements IEventBus, Helper { @Override public final void onTick(TickEvent event) { - try { - baritone.bsi = new BlockStateInterface(baritone.getPlayerContext(), true); - } catch (Exception ex) {} + if (event.getType() == TickEvent.Type.IN) { + try { + baritone.bsi = new BlockStateInterface(baritone.getPlayerContext(), true); + } catch (Exception ex) {} + } else { + baritone.bsi = null; + } listeners.forEach(l -> l.onTick(event)); } From 58fa1571f39318cbf762fc09775fa2b8c360c214 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 15:43:02 -0800 Subject: [PATCH 091/682] added more info --- src/api/java/baritone/api/Settings.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index db97999b..1ead7696 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -462,7 +462,9 @@ public final class Settings { /** * 😎 Render cached chunks as semitransparent. *

- * Can be very useful on servers with low render distance. + * Can be very useful on servers with low render distance. After enabling, you may need to reload the world in order for it to have an effect + * (e.g. disconnect and reconnect, enter then exit the nether, die and respawn, etc). This may literally kill your FPS and CPU because + * every chunk gets recompiled twice as much as normal, since the cached version comes into range, then the normal one comes from the server for real. *

* Note that flowing water is cached as AVOID, which is rendered as lava. As you get closer, you may therefore see lava falls being replaced with water falls. *

From 8c899698e09c8a2324615585de9f05aebfdfa4a1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 16:27:32 -0800 Subject: [PATCH 092/682] explore for blocks, fixes #323 --- src/api/java/baritone/api/Settings.java | 5 +++++ .../java/baritone/process/GetToBlockProcess.java | 16 ++++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 1ead7696..fd1d9ab8 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -504,6 +504,11 @@ public final class Settings { */ public final Setting mineGoalUpdateInterval = new Setting<>(5); + /** + * When GetToBlock doesn't know any locations for the desired block, explore randomly instead of giving up. + */ + public final Setting exploreForBlocks = new Setting<>(true); + /** * While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)? */ diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index f3e245da..c3ac0616 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -18,10 +18,7 @@ package baritone.process; import baritone.Baritone; -import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.goals.GoalComposite; -import baritone.api.pathing.goals.GoalGetToBlock; -import baritone.api.pathing.goals.GoalTwoBlocks; +import baritone.api.pathing.goals.*; import baritone.api.process.IGetToBlockProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; @@ -44,6 +41,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl private Block gettingTo; private List knownLocations; + private BlockPos start; private int tickCount = 0; @@ -55,6 +53,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl public void getToBlock(Block block) { onLostControl(); gettingTo = block; + start = ctx.playerFeet(); rescan(new ArrayList<>(), new CalculationContext(baritone)); } @@ -69,6 +68,14 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl rescan(new ArrayList<>(), new CalculationContext(baritone)); } if (knownLocations.isEmpty()) { + if (Baritone.settings().exploreForBlocks.get()) { + return new PathingCommand(new GoalRunAway(1, start) { + @Override + public boolean isInGoal(int x, int y, int z) { + return false; + } + }, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); + } logDirect("No known locations of " + gettingTo + ", canceling GetToBlock"); if (isSafeToCancel) { onLostControl(); @@ -106,6 +113,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl public void onLostControl() { gettingTo = null; knownLocations = null; + start = null; baritone.getInputOverrideHandler().clearAllKeys(); } From 40a66b03063e7e65a6c8b0a8a558c06648c4a55f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 18:05:05 -0800 Subject: [PATCH 093/682] almost forge support --- build.gradle | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index f356a3b2..57597d7a 100755 --- a/build.gradle +++ b/build.gradle @@ -60,7 +60,7 @@ sourceSets { minecraft { version = '1.12.2' mappings = 'stable_39' - tweakClass = 'baritone.launch.BaritoneTweaker' + tweakClass = 'org.spongepowered.asm.launch.MixinTweaker' runDir = 'run' // The sources jar should use SRG names not MCP to ensure compatibility with all mappings @@ -113,6 +113,15 @@ jar { reproducibleFileOrder = true } + +jar { + manifest { + attributes( + 'MixinConfigs': 'mixins.baritone.json' + ) + } +} + task proguard(type: ProguardTask) { url 'https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip' extract 'proguard6.0.3/lib/proguard.jar' From 90cb11f55e011adc78ef304f6578a30781efda41 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 18:19:51 -0800 Subject: [PATCH 094/682] this is needed --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 57597d7a..d1cc1919 100755 --- a/build.gradle +++ b/build.gradle @@ -95,7 +95,7 @@ dependencies { } mixin { - defaultObfuscationEnv notch + defaultObfuscationEnv searge add sourceSets.launch, 'mixins.baritone.refmap.json' } From 62b11c0a8ad1e3fc68701c432d9d72a04ee407fc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 19:01:01 -0800 Subject: [PATCH 095/682] i'm legitimately sorry --- build.gradle | 2 +- .../main/java/baritone/gradle/util/Determinizer.java | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index d1cc1919..44c258ee 100755 --- a/build.gradle +++ b/build.gradle @@ -60,7 +60,7 @@ sourceSets { minecraft { version = '1.12.2' mappings = 'stable_39' - tweakClass = 'org.spongepowered.asm.launch.MixinTweaker' + tweakClass = 'baritone.launch.BaritoneTweaker' runDir = 'run' // The sources jar should use SRG names not MCP to ensure compatibility with all mappings diff --git a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java index fc268cd3..462516d6 100644 --- a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java +++ b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java @@ -60,12 +60,22 @@ public class Determinizer { if (entry.getName().equals("META-INF/fml_cache_class_versions.json")) { continue; } + JarEntry clone = new JarEntry(entry.getName()); clone.setTime(42069); jos.putNextEntry(clone); if (entry.getName().endsWith(".refmap.json")) { JsonObject object = new JsonParser().parse(new InputStreamReader(jarFile.getInputStream(entry))).getAsJsonObject(); jos.write(writeSorted(object).getBytes()); + } else if (entry.getName().equals("META-INF/MANIFEST.MF")) { + ByteArrayOutputStream cancer = new ByteArrayOutputStream(); + copy(jarFile.getInputStream(entry), cancer); + String manifest = new String(cancer.toByteArray()); + if (!manifest.contains("baritone.launch.BaritoneTweaker")) { + throw new IllegalStateException("unable to replace"); + } + manifest = manifest.replace("baritone.launch.BaritoneTweaker", "org.spongepowered.asm.launch.MixinTweaker"); + jos.write(manifest.getBytes()); } else { copy(jarFile.getInputStream(entry), jos); } From b55e4493983edcec4840229d2ee4c1954c18b2ca Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 19:01:50 -0800 Subject: [PATCH 096/682] extra line --- buildSrc/src/main/java/baritone/gradle/util/Determinizer.java | 1 - 1 file changed, 1 deletion(-) diff --git a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java index 462516d6..77df2cf7 100644 --- a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java +++ b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java @@ -60,7 +60,6 @@ public class Determinizer { if (entry.getName().equals("META-INF/fml_cache_class_versions.json")) { continue; } - JarEntry clone = new JarEntry(entry.getName()); clone.setTime(42069); jos.putNextEntry(clone); From dfe171a5c2cdcb22ad1f08843ad12dc52e11e8b8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 19:34:44 -0800 Subject: [PATCH 097/682] forge --- .../gradle/task/BaritoneGradleTask.java | 6 ++++-- .../baritone/gradle/task/CreateDistTask.java | 4 +++- .../baritone/gradle/task/ProguardTask.java | 21 ++++++++++++++++--- .../baritone/gradle/util/Determinizer.java | 20 ++++++++++++------ 4 files changed, 39 insertions(+), 12 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java index 0450509f..42bd0736 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java @@ -52,10 +52,11 @@ class BaritoneGradleTask extends DefaultTask { ARTIFACT_STANDARD = "%s-%s.jar", ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar", ARTIFACT_API = "%s-api-%s.jar", - ARTIFACT_STANDALONE = "%s-standalone-%s.jar"; + ARTIFACT_STANDALONE = "%s-standalone-%s.jar", + ARTIFACT_FORGE = "%s-forge-%s.jar"; protected String artifactName, artifactVersion; - protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut; + protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, artifactForgePath, proguardOut; protected void verifyArtifacts() throws IllegalStateException { this.artifactName = getProject().getName(); @@ -65,6 +66,7 @@ class BaritoneGradleTask extends DefaultTask { this.artifactUnoptimizedPath = this.getBuildFile(formatVersion(ARTIFACT_UNOPTIMIZED)); this.artifactApiPath = this.getBuildFile(formatVersion(ARTIFACT_API)); this.artifactStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_STANDALONE)); + this.artifactForgePath = this.getBuildFile(formatVersion(ARTIFACT_FORGE)); this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH); diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index 49e2e142..71df695a 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -45,6 +45,7 @@ public class CreateDistTask extends BaritoneGradleTask { Path api = getRelativeFile("dist/" + formatVersion(ARTIFACT_API)); Path standalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_STANDALONE)); Path unoptimized = getRelativeFile("dist/" + formatVersion(ARTIFACT_UNOPTIMIZED)); + Path forge = getRelativeFile("dist/" + formatVersion(ARTIFACT_FORGE)); // NIO will not automatically create directories Path dir = getRelativeFile("dist/"); @@ -56,9 +57,10 @@ public class CreateDistTask extends BaritoneGradleTask { Files.copy(this.artifactApiPath, api, REPLACE_EXISTING); Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING); Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING); + Files.copy(this.artifactForgePath, forge, REPLACE_EXISTING); // Calculate all checksums and format them like "shasum" - List shasum = Stream.of(api, standalone, unoptimized) + List shasum = Stream.of(api, standalone, unoptimized, forge) .map(path -> sha1(path) + " " + path.getFileName().toString()) .collect(Collectors.toList()); diff --git a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java index 4d10e7f5..54cb3119 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java @@ -59,6 +59,8 @@ public class ProguardTask extends BaritoneGradleTask { private List requiredLibraries; + private File mixin; + @TaskAction protected void exec() throws Exception { super.verifyArtifacts(); @@ -71,6 +73,7 @@ public class ProguardTask extends BaritoneGradleTask { acquireDependencies(); proguardApi(); proguardStandalone(); + createForge(); cleanup(); } @@ -79,7 +82,7 @@ public class ProguardTask extends BaritoneGradleTask { Files.delete(this.artifactUnoptimizedPath); } - Determinizer.determinize(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString()); + Determinizer.determinize(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString(), Optional.empty()); } private void downloadProguard() throws Exception { @@ -173,10 +176,18 @@ public class ProguardTask extends BaritoneGradleTask { // Find the library jar file, and copy it to tempLibraries for (File file : pair.getLeft().files(pair.getRight())) { if (file.getName().startsWith(lib)) { + System.out.println(lib); + if (lib.contains("mixin")) { + + mixin = file; + } Files.copy(file.toPath(), getTemporaryFile("tempLibraries/" + lib + ".jar"), REPLACE_EXISTING); } } } + if (mixin == null) { + throw new IllegalStateException("Unable to find mixin jar"); + } } // a bunch of epic stuff to get the path to the cached jar @@ -264,12 +275,16 @@ public class ProguardTask extends BaritoneGradleTask { private void proguardApi() throws Exception { runProguard(getTemporaryFile(PROGUARD_API_CONFIG)); - Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString()); + Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString(), Optional.empty()); } private void proguardStandalone() throws Exception { runProguard(getTemporaryFile(PROGUARD_STANDALONE_CONFIG)); - Determinizer.determinize(this.proguardOut.toString(), this.artifactStandalonePath.toString()); + Determinizer.determinize(this.proguardOut.toString(), this.artifactStandalonePath.toString(), Optional.empty()); + } + + private void createForge() throws Exception { + Determinizer.determinize(this.proguardOut.toString(), this.artifactForgePath.toString(), Optional.of(mixin)); } private void cleanup() { diff --git a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java index 77df2cf7..d9f475a5 100644 --- a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java +++ b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java @@ -22,10 +22,7 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.*; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; @@ -39,7 +36,7 @@ import java.util.stream.Collectors; */ public class Determinizer { - public static void determinize(String inputPath, String outputPath) throws IOException { + public static void determinize(String inputPath, String outputPath, Optional toInclude) throws IOException { System.out.println("Running Determinizer"); System.out.println(" Input path: " + inputPath); System.out.println(" Output path: " + outputPath); @@ -66,7 +63,7 @@ public class Determinizer { if (entry.getName().endsWith(".refmap.json")) { JsonObject object = new JsonParser().parse(new InputStreamReader(jarFile.getInputStream(entry))).getAsJsonObject(); jos.write(writeSorted(object).getBytes()); - } else if (entry.getName().equals("META-INF/MANIFEST.MF")) { + } else if (entry.getName().equals("META-INF/MANIFEST.MF") && toInclude.isPresent()) { // only replace for forge jar ByteArrayOutputStream cancer = new ByteArrayOutputStream(); copy(jarFile.getInputStream(entry), cancer); String manifest = new String(cancer.toByteArray()); @@ -79,6 +76,17 @@ public class Determinizer { copy(jarFile.getInputStream(entry), jos); } } + if (toInclude.isPresent()) { + try (JarFile mixin = new JarFile(toInclude.get())) { + for (JarEntry entry : mixin.stream().sorted(Comparator.comparing(JarEntry::getName)).collect(Collectors.toList())) { + if (entry.getName().startsWith("META-INF") && !entry.getName().startsWith("META-INF/services")) { + continue; + } + jos.putNextEntry(entry); + copy(mixin.getInputStream(entry), jos); + } + } + } jos.finish(); } } From adbf9272702356c3ea7c2f0f2dcbb3d1c30595eb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 19:35:22 -0800 Subject: [PATCH 098/682] spacing --- .../src/main/java/baritone/gradle/task/BaritoneGradleTask.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java index 42bd0736..384e99fe 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java @@ -66,7 +66,7 @@ class BaritoneGradleTask extends DefaultTask { this.artifactUnoptimizedPath = this.getBuildFile(formatVersion(ARTIFACT_UNOPTIMIZED)); this.artifactApiPath = this.getBuildFile(formatVersion(ARTIFACT_API)); this.artifactStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_STANDALONE)); - this.artifactForgePath = this.getBuildFile(formatVersion(ARTIFACT_FORGE)); + this.artifactForgePath = this.getBuildFile(formatVersion(ARTIFACT_FORGE)); this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH); From e85de55c8f91a33d8e5314f6c59b58cec8f7f16f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 19:36:16 -0800 Subject: [PATCH 099/682] spacing 2 --- buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java | 2 +- buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index 71df695a..5090a2ea 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -57,7 +57,7 @@ public class CreateDistTask extends BaritoneGradleTask { Files.copy(this.artifactApiPath, api, REPLACE_EXISTING); Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING); Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING); - Files.copy(this.artifactForgePath, forge, REPLACE_EXISTING); + Files.copy(this.artifactForgePath, forge, REPLACE_EXISTING); // Calculate all checksums and format them like "shasum" List shasum = Stream.of(api, standalone, unoptimized, forge) diff --git a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java index 54cb3119..590211d5 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java @@ -176,9 +176,7 @@ public class ProguardTask extends BaritoneGradleTask { // Find the library jar file, and copy it to tempLibraries for (File file : pair.getLeft().files(pair.getRight())) { if (file.getName().startsWith(lib)) { - System.out.println(lib); if (lib.contains("mixin")) { - mixin = file; } Files.copy(file.toPath(), getTemporaryFile("tempLibraries/" + lib + ".jar"), REPLACE_EXISTING); From ed8f9863e32a922d63dbcb1f591d030649a2d40c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 19:37:36 -0800 Subject: [PATCH 100/682] spacing 3 --- build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/build.gradle b/build.gradle index 44c258ee..02950ffa 100755 --- a/build.gradle +++ b/build.gradle @@ -113,7 +113,6 @@ jar { reproducibleFileOrder = true } - jar { manifest { attributes( From 4aededff46e47d71b9b2be47840f2edefa90d6f0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 19:57:01 -0800 Subject: [PATCH 101/682] allow prefix and non prefix control at the same time --- src/api/java/baritone/api/Settings.java | 2 +- .../baritone/utils/ExampleBaritoneControl.java | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index fd1d9ab8..508af1cc 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -481,7 +481,7 @@ public final class Settings { /** * Whether or not to use the "#" command prefix */ - public final Setting prefix = new Setting<>(false); + public final Setting prefixControl = new Setting<>(true); /** * Don't stop walking forward when you need to break blocks in your way diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 1c710bde..cca2bf3a 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -87,22 +87,22 @@ public class ExampleBaritoneControl extends Behavior implements Helper { @Override public void onSendChatMessage(ChatEvent event) { - if (!Baritone.settings().chatControl.get() && !Baritone.settings().removePrefix.get()) { - return; - } String msg = event.getMessage(); - if (Baritone.settings().prefix.get()) { + if (Baritone.settings().prefixControl.get()) { if (msg.startsWith(COMMAND_PREFIX)) { if (!runCommand(msg.substring(COMMAND_PREFIX.length()))) { logDirect("Invalid command"); } - event.cancel(); // always cancel if using prefix - } - } else { - if (runCommand(msg)) { - event.cancel(); + event.cancel(); // always cancel if using prefixControl + return; } } + if (!Baritone.settings().chatControl.get() && !Baritone.settings().removePrefix.get()) { + return; + } + if (runCommand(msg)) { + event.cancel(); + } } public boolean runCommand(String msg0) { // you may think this can be private, but impcat calls it from .b =) From b9ae8306dd8b62e3020d41a982f2021fb970051b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 20:11:40 -0800 Subject: [PATCH 102/682] v1.1.0 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 02950ffa..5c369408 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.0.0-hotfix-2' +version '1.1.0' buildscript { repositories { From 568bb1b0e8f05980c64c3d133f6b97fc24b404a8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 21:23:19 -0800 Subject: [PATCH 103/682] some forge info --- README.md | 4 ++++ SETUP.md | 11 ++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1826eb20..2b494e64 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,10 @@ Here are some links to help to get started: Quick start example: `thisway 1000` or `goal 70` to set the goal, `path` to actually start pathing. Also try `mine diamond_ore`. `cancel` to cancel. +Put a `#` in front so that if you make a typo it doesn't go into public chat (anything beginning with `#` isn't sent). + +`.b` is also a valid prefix, but **only** in Impact. + # API example ``` diff --git a/SETUP.md b/SETUP.md index a479227b..2dc1eb47 100644 --- a/SETUP.md +++ b/SETUP.md @@ -1,5 +1,13 @@ # Setup +## Prebuilt +[Releases](https://github.com/cabaletta/baritone/releases) + +Not always completely up to date with latest features. + +The forge release (currently `baritone-forge-1.1.0.jar`) can simply be added as a Forge mod. However, it is not fully compatible with the latest version of Forge. `freeLook` was broken in Forge 14.23.4.2744. You should use Forge 14.23.4.2743 or **older** with Baritone. Newer versions of Forge "work", sort of, but Baritone's movement becomes unreliable and `freeLook` must be off. + +## Build it yourself - Clone or download Baritone ![Image](https://i.imgur.com/kbqBtoN.png) @@ -69,8 +77,9 @@ $ gradlew build ## Artifacts -Building Baritone will result in 3 artifacts created in the ``dist`` directory. +Building Baritone will result in 4 artifacts created in the ``dist`` directory. +- **Forge**: Forge mod - **API**: Only the non-api packages are obfuscated. This should be used in environments where other mods would like to use Baritone's features. - **Standalone**: Everything is obfuscated. This should be used in environments where there are no other mods present that would like to use Baritone's features. - **Unoptimized**: Nothing is obfuscated. This shouldn't be used ever in production. From 3d5de440fd78498e432628f86b4e904f99193005 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Feb 2019 21:30:58 -0800 Subject: [PATCH 104/682] what a mess --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2b494e64..16fc7090 100644 --- a/README.md +++ b/README.md @@ -45,9 +45,11 @@ Here are some links to help to get started: Quick start example: `thisway 1000` or `goal 70` to set the goal, `path` to actually start pathing. Also try `mine diamond_ore`. `cancel` to cancel. -Put a `#` in front so that if you make a typo it doesn't go into public chat (anything beginning with `#` isn't sent). +On v1.1.0 and newer: Put a `#` in front so that if you make a typo it doesn't go into public chat (anything beginning with `#` isn't sent). -`.b` is also a valid prefix, but **only** in Impact. +For older than v1.1.0, `#` must be enabled by toggling on the `prefix` setting. + +**Only** in Impact is `.b` also a valid prefix # API example From 529895f970dc8174edf49f9f850f76c6f8496f4c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 08:25:14 -0800 Subject: [PATCH 105/682] was only needed for freecam anyway --- src/launch/java/baritone/launch/mixins/MixinKeyBinding.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java index 6e215547..94e8bfd0 100644 --- a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java +++ b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java @@ -18,7 +18,6 @@ package baritone.launch.mixins; import baritone.api.BaritoneAPI; -import baritone.utils.Helper; import net.minecraft.client.settings.KeyBinding; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -49,7 +48,7 @@ public class MixinKeyBinding { } } - @Inject( + /*@Inject( method = "isPressed", at = @At("HEAD"), cancellable = true @@ -64,5 +63,5 @@ public class MixinKeyBinding { } cir.setReturnValue(force); // :sunglasses: } - } + }*/ } From fa7588062642b41e4f198f8e1650847b372d237e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 08:25:30 -0800 Subject: [PATCH 106/682] v1.1.1 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 5c369408..1be05db5 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.1.0' +version '1.1.1' buildscript { repositories { From a9895479761eece7334b376016e558bf665cb2f0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 09:37:42 -0800 Subject: [PATCH 107/682] add proper setting for suppressing clicks --- src/api/java/baritone/api/Settings.java | 5 +++++ .../baritone/launch/mixins/MixinKeyBinding.java | 14 ++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 508af1cc..152c12b2 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -478,6 +478,11 @@ public final class Settings { */ public Setting cachedChunksOpacity = new Setting<>(0.5f); + /** + * If true, Baritone will not allow you to left or right click while pathing + */ + public Setting suppressClicks = new Setting<>(false); + /** * Whether or not to use the "#" command prefix */ diff --git a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java index 94e8bfd0..9ef080bf 100644 --- a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java +++ b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java @@ -17,7 +17,9 @@ package baritone.launch.mixins; +import baritone.Baritone; import baritone.api.BaritoneAPI; +import baritone.utils.Helper; import net.minecraft.client.settings.KeyBinding; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -44,11 +46,14 @@ public class MixinKeyBinding { // only the primary baritone forces keys Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this); if (force != null) { + if (!force && !Baritone.settings().suppressClicks.get()) { + return; + } cir.setReturnValue(force); // :sunglasses: } } - /*@Inject( + @Inject( method = "isPressed", at = @At("HEAD"), cancellable = true @@ -56,12 +61,13 @@ public class MixinKeyBinding { private void isPressed(CallbackInfoReturnable cir) { // only the primary baritone forces keys Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this); - if (force != null && !force) { // <-- cursed + if (force != null && !force && Baritone.settings().suppressClicks.get()) { // <-- cursed if (pressTime > 0) { - Helper.HELPER.logDirect("You're trying to press this mouse button but I won't let you"); + Helper.HELPER.logDirect("You're trying to press this mouse button but I won't let you."); + Helper.HELPER.logDirect("Turn off the suppressClicks setting to allow clicking while pathing."); pressTime--; } cir.setReturnValue(force); // :sunglasses: } - }*/ + } } From c7ad235110b5aca13dac009987a0a6fe267856b6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 09:38:33 -0800 Subject: [PATCH 108/682] v1.1.2 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 1be05db5..84fe06a8 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.1.1' +version '1.1.2' buildscript { repositories { From 7dd881aa9adc0dd8c39581540395279f21664dfb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 09:54:17 -0800 Subject: [PATCH 109/682] latest forge works yay --- SETUP.md | 4 +- .../baritone/launch/mixins/MixinEntity.java | 74 ------------------- .../launch/mixins/MixinEntityLivingBase.java | 21 ++++++ src/launch/resources/mixins.baritone.json | 1 - 4 files changed, 24 insertions(+), 76 deletions(-) delete mode 100644 src/launch/java/baritone/launch/mixins/MixinEntity.java diff --git a/SETUP.md b/SETUP.md index 2dc1eb47..dfbb1fa7 100644 --- a/SETUP.md +++ b/SETUP.md @@ -5,7 +5,9 @@ Not always completely up to date with latest features. -The forge release (currently `baritone-forge-1.1.0.jar`) can simply be added as a Forge mod. However, it is not fully compatible with the latest version of Forge. `freeLook` was broken in Forge 14.23.4.2744. You should use Forge 14.23.4.2743 or **older** with Baritone. Newer versions of Forge "work", sort of, but Baritone's movement becomes unreliable and `freeLook` must be off. +The forge release (currently `baritone-forge-1.1.3.jar`) can simply be added as a Forge mod. + +Previously (Baritone v1.1.2 and below), it was not fully compatible with the latest version of Forge. `freeLook` was broken in Forge 14.23.4.2744. Forge 14.23.4.2743 or **older** worked with Baritone v1.1.2 and lower. Newer versions of Forge "worked", sort of, but Baritone's movement became unreliable and `freeLook` must be off. ## Build it yourself - Clone or download Baritone diff --git a/src/launch/java/baritone/launch/mixins/MixinEntity.java b/src/launch/java/baritone/launch/mixins/MixinEntity.java deleted file mode 100644 index 83655783..00000000 --- a/src/launch/java/baritone/launch/mixins/MixinEntity.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.launch.mixins; - -import baritone.api.BaritoneAPI; -import baritone.api.event.events.RotationMoveEvent; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.entity.Entity; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import static org.spongepowered.asm.lib.Opcodes.GETFIELD; - -/** - * @author Brady - * @since 8/21/2018 - */ -@Mixin(Entity.class) -public class MixinEntity { - - @Shadow - public float rotationYaw; - - /** - * Event called to override the movement direction when walking - */ - private RotationMoveEvent motionUpdateRotationEvent; - - @Inject( - method = "moveRelative", - at = @At("HEAD") - ) - private void preMoveRelative(float strafe, float up, float forward, float friction, CallbackInfo ci) { - // noinspection ConstantConditions - if (EntityPlayerSP.class.isInstance(this)) { - this.motionUpdateRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw); - BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.motionUpdateRotationEvent); - } - } - - @Redirect( - method = "moveRelative", - at = @At( - value = "FIELD", - opcode = GETFIELD, - target = "net/minecraft/entity/Entity.rotationYaw:F" - ) - ) - private float overrideYaw(Entity self) { - if (self instanceof EntityPlayerSP) { - return this.motionUpdateRotationEvent.getYaw(); - } - return self.rotationYaw; - } -} diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java index c6d76634..460d8a27 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -74,4 +74,25 @@ public abstract class MixinEntityLivingBase extends Entity { } return self.rotationYaw; } + + @Redirect( + method = "travel", + at = @At( + value = "INVOKE", + 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)) { + 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(); + this.moveRelative(strafe, up, forward, friction); + this.rotationYaw = originalYaw; + } } diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index ddd3a718..fea9cca7 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -14,7 +14,6 @@ "MixinChunkProviderServer", "MixinChunkRenderContainer", "MixinChunkRenderWorker", - "MixinEntity", "MixinEntityLivingBase", "MixinEntityPlayerSP", "MixinEntityRenderer", From 1cae7ad6b10621facff805c147d4e85a825f62f6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 09:55:29 -0800 Subject: [PATCH 110/682] v1.1.3 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 84fe06a8..a9f4c8ec 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.1.2' +version '1.1.3' buildscript { repositories { From b12fedb2d923b9079eb3c8c2026634dc7b0711d4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 11:08:12 -0800 Subject: [PATCH 111/682] help --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 16fc7090..e500d8f4 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ Here are some links to help to get started: # Chat control [Defined Here](src/main/java/baritone/utils/ExampleBaritoneControl.java) +`help` for help. + Quick start example: `thisway 1000` or `goal 70` to set the goal, `path` to actually start pathing. Also try `mine diamond_ore`. `cancel` to cancel. On v1.1.0 and newer: Put a `#` in front so that if you make a typo it doesn't go into public chat (anything beginning with `#` isn't sent). From cd3ae2a7f555b2d620fd5194b280884e54d2b41f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 12:34:29 -0800 Subject: [PATCH 112/682] documentation overhaul --- FEATURES.md | 6 ++--- INSTALL.md | 4 +-- README.md | 11 +------- USAGE.md | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 83 insertions(+), 15 deletions(-) create mode 100644 USAGE.md diff --git a/FEATURES.md b/FEATURES.md index e3714a8c..09c932f0 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -22,9 +22,9 @@ Baritone uses A*, with some modifications: - **Backtrack cost favoring** While calculating the next segment, Baritone favors backtracking its current segment. The cost is decreased heavily, but is still positive (this won't cause it to backtrack if it doesn't need to). This allows it to splice and jump onto the next segment as early as possible, if the next segment begins with a backtrack of the current one. Example - **Backtrack detection and pausing** While path calculation happens on a separate thread, the main game thread has access to the latest node considered, and the best path so far (those are rendered light blue and dark blue respectively). When the current best path (rendered dark blue) passes through the player's current position on the current path segment, path execution is paused (if it's safe to do so), because there's no point continuing forward if we're about to turn around and go back that same way. Note that the current best path as reported by the path calculation thread takes into account the incremental cost backoff system, so it's accurate to what the path calculation thread will actually pick once it finishes. -# Configuring Baritone -All the settings and documentation are here. -To change a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `pathTimeoutMS 250`). It's case insensitive. +# Chat control + +- [Baritone chat control usage](USAGE.md) # Goals The pathing goal can be set to any of these options: diff --git a/INSTALL.md b/INSTALL.md index f05e0280..cb66440f 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -84,5 +84,5 @@ The final step is "registering" the Baritone library with Impact, so that it loa - You can now launch Impact 4.3 as normal, and Baritone should start up ## How to use Baritone - Instructions on how to use Baritone are limited, and you may have to read a little bit of code (Really nothing much - just plain English), you can view that here. + +- [Baritone chat control usage](USAGE.md) diff --git a/README.md b/README.md index e500d8f4..4c4b35a3 100644 --- a/README.md +++ b/README.md @@ -41,17 +41,8 @@ Here are some links to help to get started: - [Javadocs](https://baritone.leijurv.com/) # Chat control -[Defined Here](src/main/java/baritone/utils/ExampleBaritoneControl.java) -`help` for help. - -Quick start example: `thisway 1000` or `goal 70` to set the goal, `path` to actually start pathing. Also try `mine diamond_ore`. `cancel` to cancel. - -On v1.1.0 and newer: Put a `#` in front so that if you make a typo it doesn't go into public chat (anything beginning with `#` isn't sent). - -For older than v1.1.0, `#` must be enabled by toggling on the `prefix` setting. - -**Only** in Impact is `.b` also a valid prefix +- [Baritone chat control usage](USAGE.md) # API example diff --git a/USAGE.md b/USAGE.md new file mode 100644 index 00000000..43fda9a2 --- /dev/null +++ b/USAGE.md @@ -0,0 +1,77 @@ +# Prefix + +Baritone commands can by default be typed in the chatbox. However if you make a typo, like typing "gola 10000 10000" instead of goal it goes into public chat, which is bad. + +Therefore you can use a prefix before your messages. + +On Baritone v1.1.0 and newer: The prefix is `#` by default. Anything beginning with `#` isn't sent, and is only interpreted by Baritone. +For older than v1.1.0, `#` must be enabled by toggling on the `prefix` setting. + +**Only** in Impact 4.4 is `.b` also a valid prefix. In 4.4, `#` does **not** work, neither does saying the commands directly in chat. + +Other clients like Kami and Asuna have their own custom things (like `-path`), and can disable direct chat control entirely. + + + +# Commands + +**All** of these commands may need a prefix before them, as above ^. + +`help` for (rudimentary) help. You can see what it says [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java#L53). + +To toggle a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `primaryTimeoutMS 250`). It's case insensitive. + + + + +Some common examples: +- `thisway 1000` then `path` to go in the direction you're facing for a thousand blocks +- `goal x y z` or `goal x z` or `goal y`, then `path` to go to a certain coordinate +- `goal` to set the goal to your player's feet +- `goal clear` to clear the goal +- `cancel` or `stop` to stop everything +- `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part) +- `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) +- `follow playerName` to follow a player. `follow` to follow the entity you're looking at (only works if it hitting range). `followplayers` to follow any players in range (combine with Kill Aura for a fun time). +- `save waypointName` to save a waypoint. `goto waypointName` to go to it. +- `goto axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120). +- `invert` to invert the current goal and path. This gets as far away from it as possible, instead of as close as possible. For example, do `goal` then `invert` to run as far as possible from where you're standing at the start. +- `render` to rerender the world in case `renderCachedChunks` is being glitchy +- `damn` daniel + +For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java). + +All the settings and documentation are here. If you find HTML easier to read than Javadoc, you can look here and navigate to Settings in the left sidebar. + +There are about a hundred settings, but here are some fun / interesting / important ones that you might want to look at changing in normal usage of Baritone. The documentation for each can be found at the above links. +- `allowBreak` +- `allowSprint` +- `allowPlace` +- `allowParkour` +- `allowParkourPlace` +- `renderCachedChunks` (and `cachedChunksOpacity`) <-- very fun but you need a beefy computer +- `avoidance` +- `legitMine` +- `followRadius` + + + +# Troubleshooting / common issues + +## Baritone highlights a block in green but gets completely stuck? Also I'm using Baritone with Future? +Baritone is trying to right click to place a block there, but it can't since there's a conflicting mixin. Baritone can't force click right click when Future is also installed. Left click **does work** on recent Baritone even with Future, however. For now, turn off `allowPlace` and Baritone will only search for paths that don't require placing blocks to complete. `allowBreak` can remain on. + +## Why doesn't Baritone respond to any of my chat commands? +This could be one of many things. + +First, make sure it's actually installed. + +Second, make sure that you're using the prefix properly, and that chat control is enabled in the way you expect. + +For example, Impact disables direct chat control. (i.e. anything typed in chat without a prefix will be ignored and sent publicly). **This is a saved setting**, so if you run Impact once, `chatControl` will be off from then on, **even in other clients**. +So you'll need to use the `#` prefix or edit `baritone/settings.txt` in your Minecraft folder to undo that (specifically, remove the line `chatControl false` then restart your client). + + +## Why can I do `.goto x z` in Impact but nowhere else? Why can I do `-path to x z` in KAMI but nowhere else? +These are custom commands that they added; those aren't from Baritone. +The equivalent you're looking for is `goal x z` then `path`. From 920cb6556b5f7d6b4e8adcf0e58cc3997c1314f4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 12:38:39 -0800 Subject: [PATCH 113/682] a bit more --- SETUP.md | 2 +- USAGE.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/SETUP.md b/SETUP.md index dfbb1fa7..fbb6b22c 100644 --- a/SETUP.md +++ b/SETUP.md @@ -1,7 +1,7 @@ # Setup ## Prebuilt -[Releases](https://github.com/cabaletta/baritone/releases) +Download from the [Releases](https://github.com/cabaletta/baritone/releases) Not always completely up to date with latest features. diff --git a/USAGE.md b/USAGE.md index 43fda9a2..54bf9347 100644 --- a/USAGE.md +++ b/USAGE.md @@ -1,3 +1,5 @@ +(assuming you already have Baritone [set up](SETUP.md)) + # Prefix Baritone commands can by default be typed in the chatbox. However if you make a typo, like typing "gola 10000 10000" instead of goal it goes into public chat, which is bad. From d2bfd47039b01f6135630434b6c7bf295ba7a006 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 12:41:30 -0800 Subject: [PATCH 114/682] how to check --- USAGE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/USAGE.md b/USAGE.md index 54bf9347..a763d400 100644 --- a/USAGE.md +++ b/USAGE.md @@ -66,7 +66,7 @@ Baritone is trying to right click to place a block there, but it can't since the ## Why doesn't Baritone respond to any of my chat commands? This could be one of many things. -First, make sure it's actually installed. +First, make sure it's actually installed. An easy way to check is seeing if it created the folder `baritone` in your Minecraft folder. Second, make sure that you're using the prefix properly, and that chat control is enabled in the way you expect. From 3cf944398f124800f64438d99b14848647805c16 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 14:03:32 -0800 Subject: [PATCH 115/682] =?UTF-8?q?=F0=9F=98=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 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 152c12b2..28668ee2 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -460,7 +460,7 @@ public final class Settings { public final Setting pathThroughCachedOnly = new Setting<>(false); /** - * 😎 Render cached chunks as semitransparent. + * 😎 Render cached chunks as semitransparent. Doesn't work with OptiFine 😭 *

* Can be very useful on servers with low render distance. After enabling, you may need to reload the world in order for it to have an effect * (e.g. disconnect and reconnect, enter then exit the nether, die and respawn, etc). This may literally kill your FPS and CPU because From efb316de1475a37fd0047e601d004c8cfcc41b1c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 18:11:33 -0800 Subject: [PATCH 116/682] codacy --- .../java/baritone/utils/ExampleBaritoneControl.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index cca2bf3a..289ff936 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -88,14 +88,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper { @Override public void onSendChatMessage(ChatEvent event) { String msg = event.getMessage(); - if (Baritone.settings().prefixControl.get()) { - if (msg.startsWith(COMMAND_PREFIX)) { - if (!runCommand(msg.substring(COMMAND_PREFIX.length()))) { - logDirect("Invalid command"); - } - event.cancel(); // always cancel if using prefixControl - return; + if (Baritone.settings().prefixControl.get() && msg.startsWith(COMMAND_PREFIX)) { + if (!runCommand(msg.substring(COMMAND_PREFIX.length()))) { + logDirect("Invalid command"); } + event.cancel(); // always cancel if using prefixControl + return; } if (!Baritone.settings().chatControl.get() && !Baritone.settings().removePrefix.get()) { return; From 52cafbc7aa425d6bf6e6c05e82d9d71aa6d68b2e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 21:49:09 -0800 Subject: [PATCH 117/682] add a little version thingy --- build.gradle | 5 ++++- src/main/java/baritone/utils/ExampleBaritoneControl.java | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index a9f4c8ec..0833e04d 100755 --- a/build.gradle +++ b/build.gradle @@ -116,7 +116,10 @@ jar { jar { manifest { attributes( - 'MixinConfigs': 'mixins.baritone.json' + 'MixinConfigs': 'mixins.baritone.json', + + 'Implementation-Title': 'Baritone', + 'Implementation-Version': version ) } } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 289ff936..a5b2b57e 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -227,6 +227,15 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } return true; } + if (msg.equals("version")) { + String version = ExampleBaritoneControl.class.getPackage().getImplementationVersion(); + if (version == null) { + logDirect("No version detected. Either dev environment or broken install."); + } else { + logDirect("You are using Baritone v" + version); + } + return true; + } if (msg.equals("repack") || msg.equals("rescan")) { ChunkProviderClient cli = (ChunkProviderClient) ctx.world().getChunkProvider(); int playerChunkX = ctx.playerFeet().getX() >> 4; From 3326339263f6f07131e929747d90236ba220fc76 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Feb 2019 22:17:28 -0800 Subject: [PATCH 118/682] lol that wasnt even right --- USAGE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/USAGE.md b/USAGE.md index a763d400..dab1edb1 100644 --- a/USAGE.md +++ b/USAGE.md @@ -36,7 +36,7 @@ Some common examples: - `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) - `follow playerName` to follow a player. `follow` to follow the entity you're looking at (only works if it hitting range). `followplayers` to follow any players in range (combine with Kill Aura for a fun time). - `save waypointName` to save a waypoint. `goto waypointName` to go to it. -- `goto axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120). +- `axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120). - `invert` to invert the current goal and path. This gets as far away from it as possible, instead of as close as possible. For example, do `goal` then `invert` to run as far as possible from where you're standing at the start. - `render` to rerender the world in case `renderCachedChunks` is being glitchy - `damn` daniel From 92ba76e7a1ee43406672fea768a4f0d1f27f725a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 6 Feb 2019 10:23:01 -0800 Subject: [PATCH 119/682] since all settings are individually final, the class should be too --- 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 28668ee2..e8e39792 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -667,7 +667,7 @@ public final class Settings { } } - public class Setting { + public final class Setting { public T value; public final T defaultValue; private String name; From bf9ee918f32bae4d6fbbbcc5151c8b88a7459e49 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 6 Feb 2019 12:50:42 -0800 Subject: [PATCH 120/682] 5 artifacts and documentation --- INSTALL.md | 12 ++++--- SETUP.md | 35 +++++++++++-------- .../gradle/task/BaritoneGradleTask.java | 32 +++++++---------- .../baritone/gradle/task/CreateDistTask.java | 20 ++++++----- .../baritone/gradle/task/ProguardTask.java | 7 ++-- 5 files changed, 53 insertions(+), 53 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index cb66440f..e66054b6 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,7 +1,9 @@ # Integration between Baritone and Impact Impact 4.4 has Baritone included. -These instructions apply to Impact 4.3 (and potentially other "hacked clients"). +These instructions apply to Impact 4.3. + +For Forge follow the instructions in [Setup](SETUP.md). To run Baritone on Vanilla, just follow the instructions in the README (it's `./gradlew runClient`). @@ -18,11 +20,11 @@ There are two methods of acquiring a build of Baritone ### Official Release (Not always up to date) https://github.com/cabaletta/baritone/releases -For Impact 4.3, there is no Baritone integration yet, so you will want `baritone-standalone-X.Y.Z.jar`. +For Impact 4.3, there is no Baritone integration yet, so you will want `baritone-standalone-X.Y.Z.jar`. **For the rest of this guide, replace `X.Y.Z` with the actual numeric version you are using.** Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. -The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone . && docker run --rm cabaletta/baritone cat /code/dist/checksums.txt` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). +The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone .` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). ### Building Baritone yourself You can either build Baritone through a command line or through IntelliJ's UI, information on that can be found [here](SETUP.md#building). @@ -36,7 +38,7 @@ putting baritone. - ``cabaletta`` - ``baritone`` - ``X.Y.Z`` - - Copy the build of Baritone that was acquired earlier, and place it into the ``X.Y.Z`` folder + - Copy the build of Baritone that was acquired earlier, and place it into the ``X.Y.Z`` folder, renamed like so: - The full path should look like ``/libraries/cabaletta/baritone/X.Y.Z/baritone-X.Y.Z.jar`` ## Modifying the Impact Profile JSON to run baritone @@ -79,7 +81,7 @@ The final step is "registering" the Baritone library with Impact, so that it loa ``` - Now find the ``"minecraftArguments": "..."`` text near the top. - At the very end of the quotes where it says ``--tweakClass clientapi.load.ClientTweaker"``, add on the following so it looks like: - - ``--tweakClass clientapi.load.ClientTweaker --tweakClass baritone.launch.BaritoneTweakerOptifine"`` + - ``--tweakClass clientapi.load.ClientTweaker --tweakClass baritone.launch.BaritoneTweaker"`` - If you didn't close your launcher for this step, restart it now. - You can now launch Impact 4.3 as normal, and Baritone should start up diff --git a/SETUP.md b/SETUP.md index fbb6b22c..6d50a85b 100644 --- a/SETUP.md +++ b/SETUP.md @@ -1,14 +1,31 @@ # Setup ## Prebuilt +(not always completely up to date with latest features) + Download from the [Releases](https://github.com/cabaletta/baritone/releases) -Not always completely up to date with latest features. +The Forge releases can simply be added as a Forge mod. -The forge release (currently `baritone-forge-1.1.3.jar`) can simply be added as a Forge mod. +If another one of your Forge mods has a Baritone integration, you want `baritone-api-forge-VERSION.jar`. Otherwise, you want `baritone-standalone-forge-VERSION.jar` Previously (Baritone v1.1.2 and below), it was not fully compatible with the latest version of Forge. `freeLook` was broken in Forge 14.23.4.2744. Forge 14.23.4.2743 or **older** worked with Baritone v1.1.2 and lower. Newer versions of Forge "worked", sort of, but Baritone's movement became unreliable and `freeLook` must be off. +## Artifacts + +Building Baritone will result in 5 artifacts created in the ``dist`` directory. These are the same as the artifacts created in the [releases](https://github.com/cabaletta/baritone/releases). + +- **API**: Only the non-api packages are obfuscated. This should be used in environments where other mods would like to use Baritone's features. +- **Forge API**: Same as API, but packaged for Forge. This should be used where another mod has a Baritone integration. +- **Standalone**: Everything is obfuscated. This should be used in environments where there are no other mods present that would like to use Baritone's features. +- **Forge Standalone**: Same as Standalone, but packaged for Forge. This should be used when Baritone is your only Forge mod, or none of your other Forge mods integrate with Baritone. +- **Unoptimized**: Nothing is obfuscated. This shouldn't be used ever in production. + +## More Info +To replace out Impact 4.4's Baritone build with a customized one, switch to the `impact4.4-compat` branch, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). + +Impact 4.4 **only** works with builds from the quite outdated `impact4.4-compat` branch. If you must have the latest Baritone features with Impact, and can't wait for 4.5, consider creating a standalone (non forge) build then adding it to Impact 4.**3** via the instructions in [Install](INSTALL.md). + ## Build it yourself - Clone or download Baritone @@ -75,16 +92,4 @@ $ gradlew build ![Image](https://i.imgur.com/PE6r9iN.png) -- Double click on **build** to run it - -## Artifacts - -Building Baritone will result in 4 artifacts created in the ``dist`` directory. - -- **Forge**: Forge mod -- **API**: Only the non-api packages are obfuscated. This should be used in environments where other mods would like to use Baritone's features. -- **Standalone**: Everything is obfuscated. This should be used in environments where there are no other mods present that would like to use Baritone's features. -- **Unoptimized**: Nothing is obfuscated. This shouldn't be used ever in production. - -## More Info -To replace out Impact 4.4's Baritone build with a customized one, switch to the `impact4.4-compat` branch, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). +- Double click on **build** to run it \ No newline at end of file diff --git a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java index 384e99fe..4f7674f6 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java @@ -34,8 +34,6 @@ import java.util.List; */ class BaritoneGradleTask extends DefaultTask { - protected static final JsonParser PARSER = new JsonParser(); - protected static final String PROGUARD_ZIP = "proguard.zip", PROGUARD_JAR = "proguard.jar", @@ -45,28 +43,28 @@ class BaritoneGradleTask extends DefaultTask { PROGUARD_STANDALONE_CONFIG = "standalone.pro", PROGUARD_EXPORT_PATH = "proguard_out.jar", - VERSION_MANIFEST = "version_manifest.json", - TEMP_LIBRARY_DIR = "tempLibraries/", - ARTIFACT_STANDARD = "%s-%s.jar", - ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar", - ARTIFACT_API = "%s-api-%s.jar", - ARTIFACT_STANDALONE = "%s-standalone-%s.jar", - ARTIFACT_FORGE = "%s-forge-%s.jar"; + ARTIFACT_STANDARD = "%s-%s.jar", + ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar", + ARTIFACT_API = "%s-api-%s.jar", + ARTIFACT_STANDALONE = "%s-standalone-%s.jar", + ARTIFACT_FORGE_API = "%s-api-forge-%s.jar", + ARTIFACT_FORGE_STANDALONE = "%s-standalone-forge-%s.jar"; protected String artifactName, artifactVersion; - protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, artifactForgePath, proguardOut; + protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, artifactForgeApiPath, artifactForgeStandalonePath, proguardOut; protected void verifyArtifacts() throws IllegalStateException { this.artifactName = getProject().getName(); this.artifactVersion = getProject().getVersion().toString(); - this.artifactPath = this.getBuildFile(formatVersion(ARTIFACT_STANDARD)); - this.artifactUnoptimizedPath = this.getBuildFile(formatVersion(ARTIFACT_UNOPTIMIZED)); - this.artifactApiPath = this.getBuildFile(formatVersion(ARTIFACT_API)); - this.artifactStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_STANDALONE)); - this.artifactForgePath = this.getBuildFile(formatVersion(ARTIFACT_FORGE)); + this.artifactPath = this.getBuildFile(formatVersion(ARTIFACT_STANDARD)); + this.artifactUnoptimizedPath = this.getBuildFile(formatVersion(ARTIFACT_UNOPTIMIZED)); + this.artifactApiPath = this.getBuildFile(formatVersion(ARTIFACT_API)); + this.artifactStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_STANDALONE)); + this.artifactForgeApiPath = this.getBuildFile(formatVersion(ARTIFACT_FORGE_API)); + this.artifactForgeStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_FORGE_STANDALONE)); this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH); @@ -97,8 +95,4 @@ class BaritoneGradleTask extends DefaultTask { protected Path getBuildFile(String file) { return getRelativeFile("build/libs/" + file); } - - protected JsonElement readJson(List lines) { - return PARSER.parse(String.join("\n", lines)); - } } diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index 5090a2ea..3ca935d1 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -42,10 +42,11 @@ public class CreateDistTask extends BaritoneGradleTask { super.verifyArtifacts(); // Define the distribution file paths - Path api = getRelativeFile("dist/" + formatVersion(ARTIFACT_API)); - Path standalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_STANDALONE)); - Path unoptimized = getRelativeFile("dist/" + formatVersion(ARTIFACT_UNOPTIMIZED)); - Path forge = getRelativeFile("dist/" + formatVersion(ARTIFACT_FORGE)); + Path api = getRelativeFile("dist/" + formatVersion(ARTIFACT_API)); + Path standalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_STANDALONE)); + Path unoptimized = getRelativeFile("dist/" + formatVersion(ARTIFACT_UNOPTIMIZED)); + Path forgeApi = getRelativeFile("dist/" + formatVersion(ARTIFACT_FORGE_API)); + Path forgeStandalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_FORGE_STANDALONE)); // NIO will not automatically create directories Path dir = getRelativeFile("dist/"); @@ -54,13 +55,14 @@ public class CreateDistTask extends BaritoneGradleTask { } // Copy build jars to dist/ - Files.copy(this.artifactApiPath, api, REPLACE_EXISTING); - Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING); - Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING); - Files.copy(this.artifactForgePath, forge, REPLACE_EXISTING); + Files.copy(this.artifactApiPath, api, REPLACE_EXISTING); + Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING); + Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING); + Files.copy(this.artifactForgeApiPath, forgeApi, REPLACE_EXISTING); + Files.copy(this.artifactForgeStandalonePath, forgeStandalone, REPLACE_EXISTING); // Calculate all checksums and format them like "shasum" - List shasum = Stream.of(api, standalone, unoptimized, forge) + List shasum = Stream.of(api, forgeApi, standalone, forgeStandalone, unoptimized) .map(path -> sha1(path) + " " + path.getFileName().toString()) .collect(Collectors.toList()); diff --git a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java index 590211d5..30ffddfb 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java @@ -73,7 +73,6 @@ public class ProguardTask extends BaritoneGradleTask { acquireDependencies(); proguardApi(); proguardStandalone(); - createForge(); cleanup(); } @@ -274,15 +273,13 @@ public class ProguardTask extends BaritoneGradleTask { private void proguardApi() throws Exception { runProguard(getTemporaryFile(PROGUARD_API_CONFIG)); Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString(), Optional.empty()); + Determinizer.determinize(this.proguardOut.toString(), this.artifactForgeApiPath.toString(), Optional.of(mixin)); } private void proguardStandalone() throws Exception { runProguard(getTemporaryFile(PROGUARD_STANDALONE_CONFIG)); Determinizer.determinize(this.proguardOut.toString(), this.artifactStandalonePath.toString(), Optional.empty()); - } - - private void createForge() throws Exception { - Determinizer.determinize(this.proguardOut.toString(), this.artifactForgePath.toString(), Optional.of(mixin)); + Determinizer.determinize(this.proguardOut.toString(), this.artifactForgeStandalonePath.toString(), Optional.of(mixin)); } private void cleanup() { From a822d3ef0524587cea8712a8f71ad9d19744e28c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 6 Feb 2019 16:22:40 -0800 Subject: [PATCH 121/682] horrifying placement --- .../java/baritone/behavior/LookBehavior.java | 2 +- .../baritone/pathing/movement/Movement.java | 2 +- .../pathing/movement/MovementHelper.java | 15 +- .../java/baritone/process/BuilderProcess.java | 187 +++++++++++++++++- .../baritone/utils/InputOverrideHandler.java | 6 +- 5 files changed, 195 insertions(+), 17 deletions(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index c2d0326c..8b115e90 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -73,7 +73,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior { float desiredPitch = this.target.getPitch(); ctx.player().rotationPitch = desiredPitch; if (desiredPitch == oldPitch) { - nudgeToLevel(); + //nudgeToLevel(); } this.target = null; } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 4599637a..4e7eb26f 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -34,7 +34,7 @@ import java.util.Optional; public abstract class Movement implements IMovement, MovementHelper { - protected static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN}; + public static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN}; protected final IBaritone baritone; protected final IPlayerContext ctx; diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 9bfebcc2..437aa2c3 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -80,6 +80,9 @@ public interface MovementHelper extends ActionCosts, Helper { // be opened by just interacting. return block != Blocks.IRON_DOOR; } + if (block == Blocks.CARPET) { + return canWalkOn(bsi, x, y - 1, z); + } boolean snow = block instanceof BlockSnow; boolean trapdoor = block instanceof BlockTrapDoor; if (snow || trapdoor) { @@ -321,20 +324,22 @@ public interface MovementHelper extends ActionCosts, Helper { } static boolean canPlaceAgainst(BlockStateInterface bsi, int x, int y, int z) { - return canPlaceAgainst(bsi.get0(x, y, z)); + return canPlaceAgainst(bsi, x, y, z, bsi.get0(x, y, z)); } static boolean canPlaceAgainst(BlockStateInterface bsi, BlockPos pos) { - return canPlaceAgainst(bsi.get0(pos.getX(), pos.getY(), pos.getZ())); + return canPlaceAgainst(bsi, pos.getX(), pos.getY(), pos.getZ()); } static boolean canPlaceAgainst(IPlayerContext ctx, BlockPos pos) { return canPlaceAgainst(new BlockStateInterface(ctx), pos); } - static boolean canPlaceAgainst(IBlockState state) { - // TODO isBlockNormalCube isn't the best check for whether or not we can place a block against it. e.g. glass isn't normalCube but we can place against it - return state.isBlockNormalCube(); + static boolean canPlaceAgainst(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { + // can we look at the center of a side face of this block and likely be able to place? + // (thats how this check is used) + // therefore dont include weird things that we technically could place against (like carpet) but practically can't + return state.isBlockNormalCube() || state.isFullBlock() || state.getBlock() == Blocks.GLASS || state.getBlock() == Blocks.STAINED_GLASS; } static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, boolean includeFalling) { diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index cadb5416..5718ea27 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -25,14 +25,13 @@ import baritone.api.pathing.goals.GoalGetToBlock; import baritone.api.process.IBuilderProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.ISchematic; -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; import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; +import baritone.utils.BlockStateInterface; import baritone.utils.PathingCommandContext; import baritone.utils.schematic.Schematic; import net.minecraft.block.state.IBlockState; @@ -44,8 +43,7 @@ import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.Tuple; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3i; +import net.minecraft.util.math.*; import java.io.File; import java.io.FileInputStream; @@ -65,6 +63,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro private String name; private ISchematic schematic; private Vec3i origin; + private int ticks; public boolean build(String schematicFile) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); @@ -145,6 +144,125 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return Optional.empty(); } + public class Placement { + final int hotbarSelection; + final BlockPos placeAgainst; + final EnumFacing side; + final Rotation rot; + + public Placement(int hotbarSelection, BlockPos placeAgainst, EnumFacing side, Rotation rot) { + this.hotbarSelection = hotbarSelection; + this.placeAgainst = placeAgainst; + this.side = side; + this.rot = rot; + } + } + + public Optional searchForPlacables(BuilderCalculationContext bcc) { + BetterBlockPos center = ctx.playerFeet(); + for (int dx = -5; dx <= 5; dx++) { + for (int dy = -5; dy <= 1; dy++) { + for (int dz = -5; dz <= 5; dz++) { + int x = center.x + dx; + int y = center.y + dy; + int z = center.z + dz; + IBlockState desired = bcc.getSchematic(x, y, z); + if (desired == null) { + continue; // irrelevant + } + IBlockState curr = bcc.bsi.get0(x, y, z); + if (MovementHelper.isReplacable(x, y, z, curr, bcc.bsi) && !valid(curr, desired)) { + if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() == Blocks.AIR) { + continue; + } + Optional opt = possibleToPlace(desired, x, y, z, bcc.bsi); + if (opt.isPresent()) { + return opt; + } + } + } + } + } + return Optional.empty(); + } + + public Optional possibleToPlace(IBlockState toPlace, int x, int y, int z, BlockStateInterface bsi) { + for (EnumFacing against : EnumFacing.values()) { + BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against); + IBlockState placeAgainstState = bsi.get0(placeAgainstPos); + if (MovementHelper.isReplacable(placeAgainstPos.x, placeAgainstPos.y, placeAgainstPos.z, placeAgainstState, bsi)) { + continue; + } + if (!ctx.world().mayPlace(toPlace.getBlock(), new BetterBlockPos(x, y, z), false, against, null)) { + continue; + } + AxisAlignedBB aabb = placeAgainstState.getBoundingBox(ctx.world(), placeAgainstPos); + for (Vec3d placementMultiplier : aabbSideMultipliers(against)) { + double placeX = placeAgainstPos.x + aabb.minX * placementMultiplier.x + aabb.maxX * (1 - placementMultiplier.x); + 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(ctx.playerHead(), new Vec3d(placeX, placeY, placeZ)); + RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot, ctx.playerController().getBlockReachDistance()); + if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK && result.getBlockPos().equals(placeAgainstPos) && result.sideHit == against.getOpposite()) { + OptionalInt hotbar = hasAnyItemThatWouldPlace(toPlace, result, rot); + if (hotbar.isPresent()) { + return Optional.of(new Placement(hotbar.getAsInt(), placeAgainstPos, against.getOpposite(), rot)); + } + } + } + } + return Optional.empty(); + } + + + public OptionalInt hasAnyItemThatWouldPlace(IBlockState desired, RayTraceResult result, Rotation rot) { + for (int i = 0; i < 9; i++) { + ItemStack stack = ctx.player().inventory.mainInventory.get(i); + if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) { + continue; + } + float originalYaw = ctx.player().rotationYaw; + float originalPitch = ctx.player().rotationPitch; + // the state depends on the facing of the player sometimes + ctx.player().rotationYaw = rot.getYaw(); + ctx.player().rotationPitch = rot.getPitch(); + IBlockState wouldBePlaced = ((ItemBlock) stack.getItem()).getBlock().getStateForPlacement( + ctx.world(), + result.getBlockPos().offset(result.sideHit), + result.sideHit, + (float) result.hitVec.x - result.getBlockPos().getX(), // as in PlayerControllerMP + (float) result.hitVec.y - result.getBlockPos().getY(), + (float) result.hitVec.z - result.getBlockPos().getZ(), + stack.getItem().getMetadata(stack.getMetadata()), + ctx.player() + ); + ctx.player().rotationYaw = originalYaw; + ctx.player().rotationPitch = originalPitch; + if (valid(wouldBePlaced, desired)) { + return OptionalInt.of(i); + } + } + return OptionalInt.empty(); + } + + private static Vec3d[] aabbSideMultipliers(EnumFacing side) { + switch (side) { + case UP: + return new Vec3d[]{new Vec3d(0.5, 1, 0.5)}; + case DOWN: + return new Vec3d[]{new Vec3d(0.5, 0, 0.5)}; + case NORTH: + case SOUTH: + case EAST: + case WEST: + double x = side.getXOffset() == 0 ? 0.5 : (1 + side.getXOffset()) / 2D; + double z = side.getZOffset() == 0 ? 0.5 : (1 + side.getZOffset()) / 2D; + return new Vec3d[]{new Vec3d(x, 0.25, z), new Vec3d(x, 0.75, z)}; + default: // null + throw new NullPointerException(); + } + } + @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { // TODO somehow tell inventorybehavior what we'd like to have on the hotbar @@ -161,6 +279,11 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro onLostControl(); return null; } + if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) { + ticks = 5; + } else { + ticks--; + } Optional> toBreak = toBreakNearPlayer(bcc); baritone.getInputOverrideHandler().clearAllKeys(); if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) { @@ -170,11 +293,22 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro BetterBlockPos pos = toBreak.get().getFirst(); baritone.getLookBehavior().updateTarget(rot, true); MovementHelper.switchToBestToolFor(ctx, bcc.get(pos)); - if (Objects.equals(ctx.objectMouseOver().getBlockPos(), rot) || ctx.playerRotations().isReallyCloseTo(rot)) { + if (Objects.equals(ctx.objectMouseOver().getBlockPos(), pos) || ctx.playerRotations().isReallyCloseTo(rot)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); } return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } + Optional toPlace = searchForPlacables(bcc); + if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) { + Rotation rot = toPlace.get().rot; + baritone.getLookBehavior().updateTarget(rot, true); + ctx.player().inventory.currentItem = toPlace.get().hotbarSelection; + baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true); + if ((Objects.equals(ctx.objectMouseOver().getBlockPos(), toPlace.get().placeAgainst) && ctx.objectMouseOver().sideHit.equals(toPlace.get().side)) || ctx.playerRotations().isReallyCloseTo(rot)) { + baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); + } + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } Goal goal = assemble(bcc); if (goal == null) { @@ -241,7 +375,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro List approxPlacable = placable(); List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); Goal[] toBreak = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); - Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(GoalPlace::new).toArray(Goal[]::new); + Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(pos -> placementgoal(pos, bcc)).toArray(Goal[]::new); if (toPlace.length != 0) { return new JankyGoalComposite(new GoalComposite(toPlace), new GoalComposite(toBreak)); @@ -290,6 +424,43 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } + public Goal placementgoal(BlockPos pos, BuilderCalculationContext bcc) { + boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR; + for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP) { + if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ()).getBlock(), pos, false, facing, null)) { + return new GoalAdjacent(pos, allowSameLevel); + } + } + return new GoalPlace(pos); + } + + public static class GoalAdjacent extends GoalGetToBlock { + boolean allowSameLevel; + + public GoalAdjacent(BlockPos pos, boolean allowSameLevel) { + super(pos); + this.allowSameLevel = allowSameLevel; + } + + public boolean isInGoal(int x, int y, int z) { + if (x == this.x && y == this.y && z == this.z) { + return false; + } + if (!allowSameLevel && y == this.y - 1) { + return false; + } + if (y < this.y - 1) { + return false; + } + return super.isInGoal(x, y, z); + } + + public double heuristic(int x, int y, int z) { + // prioritize lower y coordinates + return this.y * 100 + super.heuristic(x, y, z); + } + } + public static class GoalPlace extends GoalBlock { public GoalPlace(BlockPos placeAt) { super(placeAt.up()); diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 93fbe875..14fe46cc 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -69,7 +69,9 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri return false; } if (input == Input.CLICK_RIGHT) { - return isInputForcedDown(Input.CLICK_RIGHT); + boolean ret = isInputForcedDown(Input.CLICK_RIGHT); + System.out.println("click right ret: " + ret); + return ret; } return null; } @@ -122,7 +124,7 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri } private boolean inControl() { - return baritone.getPathingBehavior().isPathing() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone(); + return baritone.getPathingBehavior().isPathing() || baritone.getBuilderProcess().isActive() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone(); } public BlockBreakHelper getBlockBreakHelper() { From aa8773a67e185c36bbf3e8bd83aecf37696d88f3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 6 Feb 2019 20:54:07 -0800 Subject: [PATCH 122/682] fixes to sprinting through descend and diagonal --- .../movement/movements/MovementDescend.java | 8 ++++++-- .../movement/movements/MovementDiagonal.java | 14 +++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index aeb4e138..4f1bce4d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -210,8 +210,8 @@ public class MovementDescend extends Movement { }*/ } if (safeMode()) { - double destX = (src.getX() + 0.5) * 0.19 + (dest.getX() + 0.5) * 0.81; - double destZ = (src.getZ() + 0.5) * 0.19 + (dest.getZ() + 0.5) * 0.81; + 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(player.getPositionEyes(1.0F), @@ -245,6 +245,10 @@ public class MovementDescend extends Movement { // (dest - src) + dest is offset 1 more in the same direction // so it's the block we'd need to worry about running into if we decide to sprint straight through this descend BlockPos into = dest.subtract(src.down()).add(dest); + if (!MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into)) && MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into).up()) && MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into).up(2))) { + // if dest extends into can't walk through, but the two above are can walk through, then we can overshoot and glitch in that weird way + return true; + } for (int y = 0; y <= 2; y++) { // we could hit any of the three blocks if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(ctx, into.up(y)))) { return true; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 0abaccf7..f34e9468 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -173,13 +173,25 @@ public class MovementDiagonal extends Movement { state.setStatus(MovementStatus.SUCCESS); return state; } - if (!MovementHelper.isLiquid(ctx, ctx.playerFeet())) { + if (sprint()) { state.setInput(Input.SPRINT, true); } MovementHelper.moveTowards(ctx, state, dest); return state; } + public boolean sprint() { + if (MovementHelper.isLiquid(ctx, ctx.playerFeet())) { + return false; + } + for (int i = 0; i < 4; i++) { + if (!MovementHelper.canWalkThrough(ctx, positionsToBreak[i])) { + return false; + } + } + return true; + } + @Override protected boolean prepared(MovementState state) { return true; From b484e6fa3f53f1d2f2787bacbfe804ab3c172629 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 6 Feb 2019 21:00:53 -0800 Subject: [PATCH 123/682] literally disable the entire thing --- src/api/java/baritone/api/Settings.java | 7 +++++++ src/main/java/baritone/behavior/MemoryBehavior.java | 12 ++++++++++++ src/main/java/baritone/cache/ContainerMemory.java | 4 ++++ 3 files changed, 23 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index e8e39792..ecadb571 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -378,6 +378,13 @@ public final class Settings { */ public final Setting pruneRegionsFromRAM = new Setting<>(false); + /** + * Remember the contents of containers (chests, echests, furnaces) + *

+ * Really buggy since the packet stuff is multithreaded badly thanks to brady + */ + public final Setting containerMemory = new Setting<>(false); + /** * Print all the debug messages to chat */ diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index d371116c..390ac859 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -65,6 +65,9 @@ public final class MemoryBehavior extends Behavior { @Override public synchronized void onTick(TickEvent event) { + if (!Baritone.settings().containerMemory.get()) { + return; + } if (event.getType() == TickEvent.Type.OUT) { enderChestWindowId = null; futureInventories.clear(); @@ -80,6 +83,9 @@ public final class MemoryBehavior extends Behavior { @Override public synchronized void onSendPacket(PacketEvent event) { + if (!Baritone.settings().containerMemory.get()) { + return; + } Packet p = event.getPacket(); if (event.getState() == EventState.PRE) { @@ -116,6 +122,9 @@ public final class MemoryBehavior extends Behavior { @Override public synchronized void onReceivePacket(PacketEvent event) { + if (!Baritone.settings().containerMemory.get()) { + return; + } Packet p = event.getPacket(); if (event.getState() == EventState.PRE) { @@ -162,6 +171,9 @@ public final class MemoryBehavior extends Behavior { private void updateInventory() { + if (!Baritone.settings().containerMemory.get()) { + return; + } int windowId = ctx.player().openContainer.windowId; if (enderChestWindowId != null) { if (windowId == enderChestWindowId) { diff --git a/src/main/java/baritone/cache/ContainerMemory.java b/src/main/java/baritone/cache/ContainerMemory.java index f2b69e5c..466bf710 100644 --- a/src/main/java/baritone/cache/ContainerMemory.java +++ b/src/main/java/baritone/cache/ContainerMemory.java @@ -17,6 +17,7 @@ package baritone.cache; +import baritone.Baritone; import baritone.api.cache.IContainerMemory; import baritone.api.cache.IRememberedInventory; import baritone.api.utils.IPlayerContext; @@ -69,6 +70,9 @@ public class ContainerMemory implements IContainerMemory { } public synchronized void save() throws IOException { + if (!Baritone.settings().containerMemory.get()) { + return; + } ByteBuf buf = Unpooled.buffer(0, Integer.MAX_VALUE); PacketBuffer out = new PacketBuffer(buf); out.writeInt(inventories.size()); From 4c4bce35611a4978b15c34b61a7574ad4cab0568 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 6 Feb 2019 22:10:52 -0800 Subject: [PATCH 124/682] define origin --- .../java/baritone/process/BuilderProcess.java | 4 ++-- .../baritone/utils/ExampleBaritoneControl.java | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 5718ea27..bfc8c3b9 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -65,10 +65,10 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro private Vec3i origin; private int ticks; - public boolean build(String schematicFile) { + public boolean build(String schematicFile, BlockPos origin) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); System.out.println(file + " " + file.exists()); - return build(schematicFile, file, ctx.playerFeet()); + return build(schematicFile, file, origin); } @Override diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 427bc83a..b2114ad2 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -255,8 +255,19 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.startsWith("build")) { - String file = msg.substring(6) + ".schematic"; - logDirect("" + baritone.getBuilderProcess().build(file)); + String file; + BlockPos origin; + try { + String[] coords = msg.substring("build".length()).split(" "); + file = coords[0] + ".schematic"; + origin = new BlockPos(Integer.parseInt(coords[1]), Integer.parseInt(coords[2]), Integer.parseInt(coords[3])); + } catch (Exception ex) { + file = msg.substring(5) + ".schematic"; + origin = ctx.playerFeet(); + } + logDirect("Loading '" + file + "' to build from origin " + origin); + boolean success = baritone.getBuilderProcess().build(file, origin); + logDirect(success ? "Loaded" : "Unable to load"); return true; } if (msg.equals("axis")) { From 46f882995107e336e01d268303ec36c0f4746227 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 09:16:19 -0800 Subject: [PATCH 125/682] v1.1.4 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 0833e04d..ceb024c1 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.1.3' +version '1.1.4' buildscript { repositories { From 8694d926c48a427d07b2c3aa1f7640df0c50f4fc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 10:45:51 -0800 Subject: [PATCH 126/682] remove unneeded printouts --- src/main/java/baritone/utils/InputOverrideHandler.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 14fe46cc..6a8f9215 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -69,9 +69,7 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri return false; } if (input == Input.CLICK_RIGHT) { - boolean ret = isInputForcedDown(Input.CLICK_RIGHT); - System.out.println("click right ret: " + ret); - return ret; + return isInputForcedDown(Input.CLICK_RIGHT); } return null; } From c0761c0eeff7f193e4b723c1964cfd512b6277f0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 10:46:32 -0800 Subject: [PATCH 127/682] be more tolerant of alternate movement inputs --- .../baritone/utils/InputOverrideHandler.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 93fbe875..30ec8409 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -25,7 +25,6 @@ import baritone.api.utils.input.Input; import baritone.behavior.Behavior; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; -import net.minecraft.util.MovementInput; import net.minecraft.util.MovementInputFromOptions; import java.util.HashMap; @@ -111,14 +110,17 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri } blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT)); - MovementInput desired = inControl() - ? new PlayerMovementInput(this) - : new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings); - - if (ctx.player().movementInput.getClass() != desired.getClass()) { - ctx.player().movementInput = desired; // only set it if it was previously incorrect - // gotta do it this way, or else it constantly thinks you're beginning a double tap W sprint lol + if (inControl()) { + if (ctx.player().movementInput.getClass() != PlayerMovementInput.class) { + ctx.player().movementInput = new PlayerMovementInput(this); + } + } else { + if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { + ctx.player().movementInput = new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings); + } } + // only set it if it was previously incorrect + // gotta do it this way, or else it constantly thinks you're beginning a double tap W sprint lol } private boolean inControl() { From 0ef08142fd178902b2d319cc92e930f4697a6ec2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 13:12:37 -0800 Subject: [PATCH 128/682] trim spaces from schematic name --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index b2114ad2..aeca0a0c 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -262,7 +262,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { file = coords[0] + ".schematic"; origin = new BlockPos(Integer.parseInt(coords[1]), Integer.parseInt(coords[2]), Integer.parseInt(coords[3])); } catch (Exception ex) { - file = msg.substring(5) + ".schematic"; + file = msg.substring(5).trim() + ".schematic"; origin = ctx.playerFeet(); } logDirect("Loading '" + file + "' to build from origin " + origin); From 299540725e70f5b06a1ceb77537c89a7e7c2c239 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 13:59:37 -0800 Subject: [PATCH 129/682] a start on inventory movement --- .../baritone/behavior/InventoryBehavior.java | 31 ++++++++++ .../java/baritone/process/BuilderProcess.java | 60 +++++++++++++------ .../utils/ExampleBaritoneControl.java | 2 +- 3 files changed, 74 insertions(+), 19 deletions(-) diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 908e304b..f3ce4a93 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -28,6 +28,9 @@ import net.minecraft.inventory.ClickType; import net.minecraft.item.*; import net.minecraft.util.NonNullList; +import java.util.ArrayList; +import java.util.OptionalInt; +import java.util.Random; import java.util.function.Predicate; public class InventoryBehavior extends Behavior { @@ -56,6 +59,34 @@ public class InventoryBehavior extends Behavior { } } + public void attemptToPutOnHotbar(int inMainInvy, Predicate disallowedHotbar) { + OptionalInt destination = getTempHotbarSlot(disallowedHotbar); + if (destination.isPresent()) { + swapWithHotBar(inMainInvy, destination.getAsInt()); + } + } + + public OptionalInt getTempHotbarSlot(Predicate disallowedHotbar) { + // we're using 0 and 8 for pickaxe and throwaway + ArrayList candidates = new ArrayList<>(); + for (int i = 1; i < 8; i++) { + if (ctx.player().inventory.mainInventory.get(i).isEmpty() && !disallowedHotbar.test(i)) { + candidates.add(i); + } + } + if (candidates.isEmpty()) { + for (int i = 1; i < 8; i++) { + if (!disallowedHotbar.test(i)) { + candidates.add(i); + } + } + } + if (candidates.isEmpty()) { + return OptionalInt.empty(); + } + return OptionalInt.of(candidates.get(new Random().nextInt(candidates.size()))); + } + private void swapWithHotBar(int inInventory, int inHotbar) { ctx.playerController().windowClick(ctx.player().inventoryContainer.windowId, inInventory < 9 ? inInventory + 36 : inInventory, inHotbar, ClickType.SWAP, ctx.player()); } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index bfc8c3b9..351f0253 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -158,7 +158,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } - public Optional searchForPlacables(BuilderCalculationContext bcc) { + public Optional searchForPlacables(BuilderCalculationContext bcc, List desirableOnHotbar) { BetterBlockPos center = ctx.playerFeet(); for (int dx = -5; dx <= 5; dx++) { for (int dy = -5; dy <= 1; dy++) { @@ -175,6 +175,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() == Blocks.AIR) { continue; } + desirableOnHotbar.add(desired); Optional opt = possibleToPlace(desired, x, y, z, bcc.bsi); if (opt.isPresent()) { return opt; @@ -298,7 +299,8 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } - Optional toPlace = searchForPlacables(bcc); + List desirableOnHotbar = new ArrayList<>(); + Optional toPlace = searchForPlacables(bcc, desirableOnHotbar); if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) { Rotation rot = toPlace.get().rot; baritone.getLookBehavior().updateTarget(rot, true); @@ -310,11 +312,41 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } - Goal goal = assemble(bcc); + List approxPlacable = placable(36); + if (Baritone.settings().allowInventory.get()) { + ArrayList usefulSlots = new ArrayList<>(); + List noValidHotbarOption = new ArrayList<>(); + outer: + for (IBlockState desired : desirableOnHotbar) { + for (int i = 0; i < 9; i++) { + if (valid(approxPlacable.get(i), desired)) { + usefulSlots.add(i); + continue outer; + } + } + noValidHotbarOption.add(desired); + } + + outer: + for (int i = 9; i < 36; i++) { + for (IBlockState desired : noValidHotbarOption) { + if (valid(approxPlacable.get(i), desired)) { + baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains); + break outer; + } + } + } + } + + + Goal goal = assemble(bcc, approxPlacable.subList(0, 9)); if (goal == null) { - logDirect("Unable to do it =("); - onLostControl(); - return null; + goal = assemble(bcc, approxPlacable); // we're far away, so assume that we have our whole inventory to recalculate placable properly + if (goal == null) { + logDirect("Unable to do it =("); + onLostControl(); + return null; + } } return new PathingCommandContext(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc); } @@ -371,8 +403,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } - private Goal assemble(BuilderCalculationContext bcc) { - List approxPlacable = placable(); + private Goal assemble(BuilderCalculationContext bcc, List approxPlacable) { List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); Goal[] toBreak = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(pos -> placementgoal(pos, bcc)).toArray(Goal[]::new); @@ -484,16 +515,9 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return "Building " + name; } - /** - * Hotbar contents, if they were placed - *

- * Always length nine, empty slots become Blocks.AIR.getDefaultState() - * - * @return - */ - public List placable() { + public List placable(int size) { List result = new ArrayList<>(); - for (int i = 0; i < 9; i++) { + for (int i = 0; i < size; i++) { ItemStack stack = ctx.player().inventory.mainInventory.get(i); if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) { result.add(Blocks.AIR.getDefaultState()); @@ -520,7 +544,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro public BuilderCalculationContext() { super(BuilderProcess.this.baritone, true); // wew lad - this.placable = placable(); + this.placable = placable(9); this.schematic = BuilderProcess.this.schematic; this.originX = origin.getX(); this.originY = origin.getY(); diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index aeca0a0c..68c9eae1 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -258,7 +258,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { String file; BlockPos origin; try { - String[] coords = msg.substring("build".length()).split(" "); + String[] coords = msg.substring("build".length()).trim().split(" "); file = coords[0] + ".schematic"; origin = new BlockPos(Integer.parseInt(coords[1]), Integer.parseInt(coords[2]), Integer.parseInt(coords[3])); } catch (Exception ex) { From 6faa7344aad5aa8733b246ec07fef6dceca83582 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 14:11:18 -0800 Subject: [PATCH 130/682] properly discard orphan path segments --- src/main/java/baritone/behavior/PathingBehavior.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 8339625d..3776f55e 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -61,6 +61,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private boolean lastAutoJump; + private BlockPos expectedSegmentStart; + private final LinkedBlockingQueue toDispatch = new LinkedBlockingQueue<>(); public PathingBehavior(Baritone baritone) { @@ -88,6 +90,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, baritone.getPathingControlManager().cancelEverything(); return; } + expectedSegmentStart = pathStart(); baritone.getPathingControlManager().preTick(); tickPath(); dispatchEvents(); @@ -438,8 +441,12 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, Optional executor = calcResult.getPath().map(p -> new PathExecutor(PathingBehavior.this, p)); if (current == null) { if (executor.isPresent()) { - queuePathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING); - current = executor.get(); + if (executor.get().getPath().getSrc().equals(expectedSegmentStart)) { + queuePathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING); + current = executor.get(); + } else { + logDebug("Warning: discarding orphan path segment with incorrect start"); + } } else { if (calcResult.getType() != PathCalculationResult.Type.CANCELLATION && calcResult.getType() != PathCalculationResult.Type.EXCEPTION) { // don't dispatch CALC_FAILED on cancellation From 67fa91abe8c1e53651b286e07b3bdfad5efbe7ab Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 15:55:39 -0800 Subject: [PATCH 131/682] fixes to descend, and goto coords --- .../movement/movements/MovementDescend.java | 7 +- .../baritone/pathing/path/PathExecutor.java | 2 +- .../utils/ExampleBaritoneControl.java | 72 +++++++++++-------- 3 files changed, 50 insertions(+), 31 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 4f1bce4d..914a2993 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -245,7 +245,7 @@ public class MovementDescend extends Movement { // (dest - src) + dest is offset 1 more in the same direction // so it's the block we'd need to worry about running into if we decide to sprint straight through this descend BlockPos into = dest.subtract(src.down()).add(dest); - if (!MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into)) && MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into).up()) && MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into).up(2))) { + if (skipToAscend()) { // if dest extends into can't walk through, but the two above are can walk through, then we can overshoot and glitch in that weird way return true; } @@ -256,4 +256,9 @@ public class MovementDescend extends Movement { } return false; } + + public boolean skipToAscend() { + BlockPos into = dest.subtract(src.down()).add(dest); + return !MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into)) && MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into).up()) && MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into).up(2)); + } } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 1b59f8e3..fffae13f 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -398,7 +398,7 @@ public class PathExecutor implements IPathExecutor, Helper { IMovement current = path.movements().get(pathPosition); if (current instanceof MovementDescend) { - if (((MovementDescend) current).safeMode()) { + if (((MovementDescend) current).safeMode() && !((MovementDescend) current).skipToAscend()) { logDebug("Sprinting would be unsafe"); return false; } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index a5b2b57e..97282a63 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -163,36 +163,19 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } if (msg.startsWith("goal")) { - String[] params = msg.substring(4).trim().split(" "); - if (params[0].equals("")) { - params = new String[]{}; - } + String rest = msg.substring(4).trim(); Goal goal; - try { - switch (params.length) { - case 0: - goal = new GoalBlock(ctx.playerFeet()); - break; - case 1: - if (params[0].equals("clear") || params[0].equals("none")) { - goal = null; - } else { - goal = new GoalYLevel(Integer.parseInt(params[0])); - } - break; - case 2: - goal = new GoalXZ(Integer.parseInt(params[0]), Integer.parseInt(params[1])); - break; - case 3: - goal = new GoalBlock(new BlockPos(Integer.parseInt(params[0]), Integer.parseInt(params[1]), Integer.parseInt(params[2]))); - break; - default: - logDirect("unable to understand lol"); - return true; + if (rest.equals("clear") || rest.equals("none")) { + goal = null; + } else { + String[] params = rest.split(" "); + if (params[0].equals("")) { + params = new String[]{}; + } + goal = parseGoal(params); + if (goal == null) { + return true; } - } catch (NumberFormatException ex) { - logDirect("unable to parse integer " + ex); - return true; } customGoalProcess.setGoal(goal); logDirect("Goal: " + goal); @@ -469,7 +452,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { if (block == null) { waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null); if (waypoint == null) { - logDirect("No locations for " + mining + " known, cancelling"); + Goal goal = parseGoal(waypointType.split(" ")); + if (goal != null) { + logDirect("Going to " + goal); + customGoalProcess.setGoalAndPath(goal); + } return true; } } else { @@ -548,4 +535,31 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } } } + + private Goal parseGoal(String[] params) { + Goal goal; + try { + switch (params.length) { + case 0: + goal = new GoalBlock(ctx.playerFeet()); + break; + case 1: + goal = new GoalYLevel(Integer.parseInt(params[0])); + break; + case 2: + goal = new GoalXZ(Integer.parseInt(params[0]), Integer.parseInt(params[1])); + break; + case 3: + goal = new GoalBlock(new BlockPos(Integer.parseInt(params[0]), Integer.parseInt(params[1]), Integer.parseInt(params[2]))); + break; + default: + logDirect("unable to understand lol"); + return null; + } + } catch (NumberFormatException ex) { + logDirect("unable to parse integer " + ex); + return null; + } + return goal; + } } From 42513e4b56847ae4ff561e4f324cabb308e78e5d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 16:12:34 -0800 Subject: [PATCH 132/682] better check --- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 3776f55e..c0c21e92 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -441,7 +441,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, Optional executor = calcResult.getPath().map(p -> new PathExecutor(PathingBehavior.this, p)); if (current == null) { if (executor.isPresent()) { - if (executor.get().getPath().getSrc().equals(expectedSegmentStart)) { + if (executor.get().getPath().positions().contains(expectedSegmentStart)) { queuePathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING); current = executor.get(); } else { From 9a29f9ce573dd1f73c026de108c9611921e2e88f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 16:39:15 -0800 Subject: [PATCH 133/682] better behavior on arrival and failure --- src/main/java/baritone/process/GetToBlockProcess.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index c3ac0616..a6e2e68b 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -82,12 +82,13 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); } + Goal goal = new GoalComposite(knownLocations.stream().map(this::createGoal).toArray(Goal[]::new)); if (calcFailed) { logDirect("Unable to find any path to " + gettingTo + ", canceling GetToBlock"); if (isSafeToCancel) { onLostControl(); } - return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); + return new PathingCommand(goal, PathingCommandType.CANCEL_AND_SET_GOAL); } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain @@ -95,15 +96,16 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl CalculationContext context = new CalculationContext(baritone, true); Baritone.getExecutor().execute(() -> rescan(current, context)); } - Goal goal = new GoalComposite(knownLocations.stream().map(this::createGoal).toArray(Goal[]::new)); if (goal.isInGoal(ctx.playerFeet()) && isSafeToCancel) { // we're there if (rightClickOnArrival(gettingTo)) { if (rightClick()) { onLostControl(); + return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); } } else { onLostControl(); + return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); } } return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH); From d0d8b12fb8d645bc0a2427fcc7bfa7a1e0970083 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 17:18:14 -0800 Subject: [PATCH 134/682] add clickCancel, fixes #326 --- src/api/java/baritone/api/Settings.java | 5 +++++ src/launch/java/baritone/launch/mixins/MixinKeyBinding.java | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index ecadb571..85d823ea 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -378,6 +378,11 @@ public final class Settings { */ public final Setting pruneRegionsFromRAM = new Setting<>(false); + /** + * Cancel baritone on left click, as a form of "panic button" + */ + public final Setting clickCancel = new Setting<>(false); + /** * Remember the contents of containers (chests, echests, furnaces) *

diff --git a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java index 9ef080bf..4db240e3 100644 --- a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java +++ b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java @@ -20,6 +20,7 @@ package baritone.launch.mixins; import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.utils.Helper; +import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -61,6 +62,9 @@ public class MixinKeyBinding { private void isPressed(CallbackInfoReturnable cir) { // only the primary baritone forces keys Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this); + if (pressTime > 0 && (KeyBinding) (Object) this == Minecraft.getMinecraft().gameSettings.keyBindAttack && Baritone.settings().clickCancel.get()) { + BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().cancelEverything(); + } if (force != null && !force && Baritone.settings().suppressClicks.get()) { // <-- cursed if (pressTime > 0) { Helper.HELPER.logDirect("You're trying to press this mouse button but I won't let you."); From e37a09a1c80ced7bc5540c0112f40da81fce665a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 8 Feb 2019 12:08:34 -0800 Subject: [PATCH 135/682] makes mining faster, fixes #330 --- src/main/java/baritone/process/MineProcess.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 80677456..e345c8b8 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -250,6 +250,14 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro public static List prune(CalculationContext ctx, List locs2, List mining, int max) { List dropped = droppedItemsScan(mining, ctx.world); + dropped.removeIf(drop -> { + for (BlockPos pos : locs2) { + if (mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) && MineProcess.plausibleToBreak(ctx.bsi, pos) && pos.distanceSq(drop) <= 9) { // TODO maybe drop also has to be supported? no lava below? + return true; + } + } + return false; + }); List locs = locs2 .stream() .distinct() From 1a430dc2cf4b2d5d719c9a6d0378eef0bbfc4f5c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 9 Feb 2019 17:38:42 -0800 Subject: [PATCH 136/682] explain --- src/main/java/baritone/utils/InputOverrideHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 30ec8409..c6db6dc5 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -115,7 +115,7 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri ctx.player().movementInput = new PlayerMovementInput(this); } } else { - if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { + if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { // allow other movement inputs that arent this one, e.g. for a freecam ctx.player().movementInput = new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings); } } From 9d1d4fe0d9e3680be59ad0a8cfe2c7f0e4f80b1f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 10 Feb 2019 10:44:04 -0800 Subject: [PATCH 137/682] typo --- src/main/java/baritone/utils/InputOverrideHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index c6db6dc5..f32bdaa4 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -115,7 +115,7 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri ctx.player().movementInput = new PlayerMovementInput(this); } } else { - if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { // allow other movement inputs that arent this one, e.g. for a freecam + 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); } } From a18eb90702a5f1d71a728efe8f207ddce88d5daf Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 10 Feb 2019 13:49:28 -0800 Subject: [PATCH 138/682] address glaring inconsistency --- src/api/java/baritone/api/Settings.java | 2 +- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 85d823ea..2e1115ac 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -277,7 +277,7 @@ public final class Settings { /** * Start planning the next path once the remaining movements tick estimates sum up to less than this value */ - public final Setting planningTickLookAhead = new Setting<>(150); + public final Setting planningTickLookahead = new Setting<>(150); /** * Default size of the Long2ObjectOpenHashMap used in pathing diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index c0c21e92..004f149f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -196,7 +196,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // and this path doesn't get us all the way there return; } - if (ticksRemainingInSegment(false).get() < Baritone.settings().planningTickLookAhead.get()) { + if (ticksRemainingInSegment(false).get() < Baritone.settings().planningTickLookahead.get()) { // and this path has 7.5 seconds or less left // don't include the current movement so a very long last movement (e.g. descend) doesn't trip it up // if we actually included current, it wouldn't start planning ahead until the last movement was done, if the last movement took more than 7.5 seconds on its own From 7017e9e2eac11b0739b0aac97fb7b6c277b577c9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 10 Feb 2019 15:10:44 -0800 Subject: [PATCH 139/682] crucial performance optimization --- 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 e345c8b8..513caed0 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -252,7 +252,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro List dropped = droppedItemsScan(mining, ctx.world); dropped.removeIf(drop -> { for (BlockPos pos : locs2) { - if (mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) && MineProcess.plausibleToBreak(ctx.bsi, pos) && pos.distanceSq(drop) <= 9) { // TODO maybe drop also has to be supported? no lava below? + if (pos.distanceSq(drop) <= 9 && mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) && MineProcess.plausibleToBreak(ctx.bsi, pos)) { // TODO maybe drop also has to be supported? no lava below? return true; } } From 4868ed75606badb0f726005c9dc971ccd17ee9e9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 10 Feb 2019 15:12:52 -0800 Subject: [PATCH 140/682] explain whats going on --- src/launch/java/baritone/launch/mixins/MixinKeyBinding.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java index 4db240e3..6814b6d6 100644 --- a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java +++ b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java @@ -63,7 +63,9 @@ public class MixinKeyBinding { // only the primary baritone forces keys Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this); if (pressTime > 0 && (KeyBinding) (Object) this == Minecraft.getMinecraft().gameSettings.keyBindAttack && Baritone.settings().clickCancel.get()) { + Helper.HELPER.logDirect("Cancelling path on left click since the clickCancel setting is enabled!"); BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().cancelEverything(); + return; } if (force != null && !force && Baritone.settings().suppressClicks.get()) { // <-- cursed if (pressTime > 0) { From bb000c4e3fbd301bccb963d1a75e50537d9e995a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 10 Feb 2019 16:44:09 -0800 Subject: [PATCH 141/682] include diagonals, and better settings --- README.md | 2 ++ USAGE.md | 2 +- src/api/java/baritone/api/Settings.java | 13 +++++++++++++ src/main/java/baritone/process/MineProcess.java | 10 ++++++---- 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 4c4b35a3..e7e51c01 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ Here are some links to help to get started: - [Javadocs](https://baritone.leijurv.com/) +- [Settings](https://baritone.leijurv.com/baritone/api/Settings.html) + # Chat control - [Baritone chat control usage](USAGE.md) diff --git a/USAGE.md b/USAGE.md index dab1edb1..a34244ce 100644 --- a/USAGE.md +++ b/USAGE.md @@ -43,7 +43,7 @@ Some common examples: For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java). -All the settings and documentation are here. If you find HTML easier to read than Javadoc, you can look here and navigate to Settings in the left sidebar. +All the settings and documentation are here. If you find HTML easier to read than Javadoc, you can look here. There are about a hundred settings, but here are some fun / interesting / important ones that you might want to look at changing in normal usage of Baritone. The documentation for each can be found at the above links. - `allowBreak` diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 2e1115ac..1182579f 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -563,6 +563,19 @@ public final class Settings { */ public final Setting legitMineYLevel = new Setting<>(11); + /** + * Magically see ores that are separated diagonally from existing ores. Basically like mining around the ores that it finds + * in case there's one there touching it diagonally, except it checks it un-legit-ly without having the mine blocks to see it. + * You can decide whether this looks plausible or not. + *

+ * This is disabled because it results in some weird behavior. For example, it can """see""" the top block of a vein of iron_ore + * through a lava lake. This isn't an issue normally since it won't consider anything touching lava, so it just ignores it. + * However, this setting expands that and allows it to see the entire vein so it'll mine under the lava lake to get the iron that + * it can reach without mining blocks adjacent to lava. This really defeats the purpose of legitMine since a player could never + * do that lol, so thats one reason why its disabled + */ + public final Setting legitMineIncludeDiagonals = new Setting<>(false); + /** * When mining block of a certain type, try to mine two at once instead of one. * If the block above is also a goal block, set GoalBlock instead of GoalTwoBlocks diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 513caed0..a299bf31 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -228,7 +228,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return prune(ctx, locs, mining, max); } - public void addNearby() { + private void addNearby() { knownOreLocations.addAll(droppedItemsScan(mining, ctx.world())); BlockPos playerFeet = ctx.playerFeet(); BlockStateInterface bsi = new BlockStateInterface(ctx); @@ -239,8 +239,11 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) { // crucial to only add blocks we can see because otherwise this // is an x-ray and it'll get caught - if (mining.contains(bsi.get0(x, y, z).getBlock()) && RotationUtils.reachable(ctx.player(), new BlockPos(x, y, z), fakedBlockReachDistance).isPresent()) { - knownOreLocations.add(new BlockPos(x, y, z)); + if (mining.contains(bsi.get0(x, y, z).getBlock())) { + BlockPos pos = new BlockPos(x, y, z); + if ((Baritone.settings().legitMineIncludeDiagonals.get() && knownOreLocations.stream().anyMatch(ore -> ore.distanceSq(pos) <= 2 /* sq means this is pytha dist <= sqrt(2) */)) || RotationUtils.reachable(ctx.player(), pos, fakedBlockReachDistance).isPresent()) { + knownOreLocations.add(pos); + } } } } @@ -263,7 +266,6 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro .distinct() // remove any that are within loaded chunks that aren't actually what we want - .filter(pos -> !ctx.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ()) || mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos)) // remove any that are implausible to mine (encased in bedrock, or touching lava) From 503f2fb1975a3403dc72009cb13b432ba3f993c6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 10 Feb 2019 16:46:24 -0800 Subject: [PATCH 142/682] direct link to the top of the detail section since its not sorted alphabetically --- README.md | 2 +- USAGE.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e7e51c01..f2e4e456 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Here are some links to help to get started: - [Javadocs](https://baritone.leijurv.com/) -- [Settings](https://baritone.leijurv.com/baritone/api/Settings.html) +- [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#allowBreak) # Chat control diff --git a/USAGE.md b/USAGE.md index a34244ce..391e5e45 100644 --- a/USAGE.md +++ b/USAGE.md @@ -43,7 +43,7 @@ Some common examples: For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java). -All the settings and documentation are here. If you find HTML easier to read than Javadoc, you can look here. +All the settings and documentation are here. If you find HTML easier to read than Javadoc, you can look here. There are about a hundred settings, but here are some fun / interesting / important ones that you might want to look at changing in normal usage of Baritone. The documentation for each can be found at the above links. - `allowBreak` From 1d88564a7217e5aecebbd18c99152064fffe941a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 10 Feb 2019 16:50:54 -0800 Subject: [PATCH 143/682] clarify this setting since its got a similar name --- src/api/java/baritone/api/Settings.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 1182579f..0fb26134 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -308,6 +308,8 @@ public final class Settings { * Is it okay to sprint through a descend followed by a diagonal? * The player overshoots the landing, but not enough to fall off. And the diagonal ensures that there isn't * lava or anything that's !canWalkInto in that space, so it's technically safe, just a little sketchy. + *

+ * Note: this is *not* related to the allowDiagonalDescend setting, that is a completely different thing. */ public final Setting allowOvershootDiagonalDescend = new Setting<>(true); From 36f608c63c0e0d1a293fef331efe3b9f2f83cc50 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Feb 2019 19:21:08 -0800 Subject: [PATCH 144/682] add epic gamer address --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f2e4e456..71c6f6b8 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone Have committed at least once a day for the last 6 months =D 🦀 +1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2 + Here are some links to help to get started: - [Features](FEATURES.md) From cf38d593b88e374552b7a789055b3effbfc19310 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Feb 2019 22:20:59 -0800 Subject: [PATCH 145/682] thanks leafeon --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 97282a63..aa57e346 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -236,7 +236,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Queued " + count + " chunks for repacking"); return true; } - if (msg.equals("axis")) { + if (msg.equals("axis") || msg.equals("highway")) { customGoalProcess.setGoalAndPath(new GoalAxis()); return true; } From 24fa75c24e63af55c183f2e6e51cc2e89076cef7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Feb 2019 22:26:49 -0800 Subject: [PATCH 146/682] did someone say more badges --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 71c6f6b8..0cbaa642 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ [![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/) ![Code size](https://img.shields.io/github/languages/code-size/cabaletta/baritone.svg) ![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg) +![](https://tokei.rs/b1/github/cabaletta/baritone?category=code) +![](https://tokei.rs/b1/github/cabaletta/baritone?category=files) [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) From 8d481ba394b5ba4e193ab4dcdf645ad3f4e9d923 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Feb 2019 09:58:44 -0800 Subject: [PATCH 147/682] lol --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0cbaa642..eb96e9e4 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAnd ## Can I use Baritone as a library in my custom utility client? -Sure! (As long as usage is in compliance with the LGPL 3 License) +That's what it's for, sure! (As long as usage is in compliance with the LGPL 3 License) ## How is it so fast? From aac7ebf6dd11af83061405542579de67b68fccd4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Feb 2019 18:32:03 -0800 Subject: [PATCH 148/682] avoid creating callbackinfo at all costs --- .../launch/mixins/MixinChunkRenderContainer.java | 14 +++++++++----- .../baritone/launch/mixins/MixinRenderList.java | 8 ++++---- .../baritone/launch/mixins/MixinVboRenderList.java | 8 ++++---- 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index fef16d6b..511e1c14 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -22,27 +22,31 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ChunkRenderContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.chunk.RenderChunk; +import net.minecraft.util.math.BlockPos; import org.lwjgl.opengl.GL14; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.Redirect; import static org.lwjgl.opengl.GL11.*; @Mixin(ChunkRenderContainer.class) public class MixinChunkRenderContainer { - @Inject( + @Redirect( // avoid creating CallbackInfo at all costs; this is called 40k times per second method = "preRenderChunk", - at = @At("HEAD") + at = @At( + value = "INVOKE", + target = "net/minecraft/client/renderer/chunk/RenderChunk.getPosition()Lnet/minecraft/util/math/BlockPos;" + ) ) - private void preRenderChunk(RenderChunk renderChunkIn, CallbackInfo ci) { + private BlockPos getPosition(RenderChunk renderChunkIn) { if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { GlStateManager.enableAlpha(); GlStateManager.enableBlend(); GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.get()); GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); } + return renderChunkIn.getPosition(); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinRenderList.java b/src/launch/java/baritone/launch/mixins/MixinRenderList.java index 55d1da70..3d4d8a91 100644 --- a/src/launch/java/baritone/launch/mixins/MixinRenderList.java +++ b/src/launch/java/baritone/launch/mixins/MixinRenderList.java @@ -22,25 +22,25 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderList; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.Redirect; import static org.lwjgl.opengl.GL11.*; @Mixin(RenderList.class) public class MixinRenderList { - @Inject( + @Redirect( // avoid creating CallbackInfo at all costs; this is called 40k times per second method = "renderChunkLayer", at = @At( value = "INVOKE", target = "net/minecraft/client/renderer/GlStateManager.popMatrix()V" ) ) - private void renderChunkLayer(CallbackInfo info) { + private void popMatrix() { if (Baritone.settings().renderCachedChunks.get()) { // reset the blend func to normal (not dependent on constant alpha) GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } + GlStateManager.popMatrix(); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java b/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java index c2c9fd8c..70048c8c 100644 --- a/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java +++ b/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java @@ -22,25 +22,25 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.VboRenderList; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.Redirect; import static org.lwjgl.opengl.GL11.*; @Mixin(VboRenderList.class) public class MixinVboRenderList { - @Inject( + @Redirect( // avoid creating CallbackInfo at all costs; this is called 40k times per second method = "renderChunkLayer", at = @At( value = "INVOKE", target = "net/minecraft/client/renderer/GlStateManager.popMatrix()V" ) ) - private void renderChunkLayer(CallbackInfo info) { + private void popMatrix() { if (Baritone.settings().renderCachedChunks.get()) { // reset the blend func to normal (not dependent on constant alpha) GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } + GlStateManager.popMatrix(); } } From 4026b850f899080bac82f5a2a1e6cf411b47651e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Feb 2019 18:34:58 -0800 Subject: [PATCH 149/682] dont spam debug chat --- src/main/java/baritone/behavior/PathingBehavior.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 004f149f..d441c416 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -378,7 +378,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } if (MovementHelper.canWalkOn(ctx, possibleSupport.down()) && MovementHelper.canWalkThrough(ctx, possibleSupport) && MovementHelper.canWalkThrough(ctx, possibleSupport.up())) { // this is plausible - logDebug("Faking path start assuming player is standing off the edge of a block"); + //logDebug("Faking path start assuming player is standing off the edge of a block"); return possibleSupport; } } @@ -387,7 +387,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // !onGround // we're in the middle of a jump if (MovementHelper.canWalkOn(ctx, feet.down().down())) { - logDebug("Faking path start assuming player is midair and falling"); + //logDebug("Faking path start assuming player is midair and falling"); return feet.down(); } } From 99cb7f51422370e395f2eeb8e91eef1e56d1cd6d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Feb 2019 21:36:53 -0800 Subject: [PATCH 150/682] crucial performance optimization --- .../java/baritone/pathing/path/PathExecutor.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index fffae13f..c61ebc3d 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -195,17 +195,17 @@ public class PathExecutor implements IPathExecutor, Helper { continue; } Movement m = (Movement) path.movements().get(i); - HashSet prevBreak = new HashSet<>(m.toBreak(bsi)); - HashSet prevPlace = new HashSet<>(m.toPlace(bsi)); - HashSet prevWalkInto = new HashSet<>(m.toWalkInto(bsi)); + List prevBreak = m.toBreak(bsi); + List prevPlace = m.toPlace(bsi); + List prevWalkInto = m.toWalkInto(bsi); m.resetBlockCache(); - if (!prevBreak.equals(new HashSet<>(m.toBreak(bsi)))) { + if (!prevBreak.equals(m.toBreak(bsi))) { recalcBP = true; } - if (!prevPlace.equals(new HashSet<>(m.toPlace(bsi)))) { + if (!prevPlace.equals(m.toPlace(bsi))) { recalcBP = true; } - if (!prevWalkInto.equals(new HashSet<>(m.toWalkInto(bsi)))) { + if (!prevWalkInto.equals(m.toWalkInto(bsi))) { recalcBP = true; } } From 90a1fa83375ab5aefaf414311c4954775c780617 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Feb 2019 22:06:13 -0800 Subject: [PATCH 151/682] lol --- src/main/java/baritone/event/GameEventHandler.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 84bac80f..b1bb1182 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -50,7 +50,9 @@ public final class GameEventHandler implements IEventBus, Helper { if (event.getType() == TickEvent.Type.IN) { try { baritone.bsi = new BlockStateInterface(baritone.getPlayerContext(), true); - } catch (Exception ex) {} + } catch (Exception ex) { + baritone.bsi = null; + } } else { baritone.bsi = null; } From c473914d0528ec93b507355b44a5b568059095e9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 13:54:50 -0800 Subject: [PATCH 152/682] fix flashing backwards, fixes #265 --- src/api/java/baritone/api/utils/Rotation.java | 13 +++++++++++-- src/api/java/baritone/api/utils/RotationUtils.java | 7 +++++-- .../java/baritone/pathing/movement/Movement.java | 2 +- .../pathing/movement/movements/MovementFall.java | 4 ++-- .../pathing/movement/movements/MovementPillar.java | 2 +- .../movement/movements/MovementTraverse.java | 6 +++--- 6 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/api/java/baritone/api/utils/Rotation.java b/src/api/java/baritone/api/utils/Rotation.java index 7f93547b..54f63ebf 100644 --- a/src/api/java/baritone/api/utils/Rotation.java +++ b/src/api/java/baritone/api/utils/Rotation.java @@ -117,8 +117,12 @@ public class Rotation { * @return are they really close */ public boolean isReallyCloseTo(Rotation other) { - float yawDiff = Math.abs(this.yaw - other.yaw); // you cant fool me - return (yawDiff < 0.01 || yawDiff > 359.9) && Math.abs(this.pitch - other.pitch) < 0.01; + return yawIsReallyClose(other) && Math.abs(this.pitch - other.pitch) < 0.01; + } + + public boolean yawIsReallyClose(Rotation other) { + float yawDiff = Math.abs(normalizeYaw(yaw) - normalizeYaw(other.yaw)); // you cant fool me + return (yawDiff < 0.01 || yawDiff > 359.99); } /** @@ -147,4 +151,9 @@ public class Rotation { } return newYaw; } + + @Override + public String toString() { + return "Yaw: " + yaw + ", Pitch: " + pitch; + } } diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index 9352b7fe..3010d283 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -78,6 +78,9 @@ public final class RotationUtils { * @return The wrapped angles */ public static Rotation wrapAnglesToRelative(Rotation current, Rotation target) { + if (current.yawIsReallyClose(target)) { + return new Rotation(current.getYaw(), target.getPitch()); + } return target.subtract(current).normalize().add(current); } @@ -102,7 +105,7 @@ public final class RotationUtils { * @param dest The destination position * @return The rotation from the origin to the destination */ - public static Rotation calcRotationFromVec3d(Vec3d orig, Vec3d dest) { + private static Rotation calcRotationFromVec3d(Vec3d orig, Vec3d dest) { double[] delta = {orig.x - dest.x, orig.y - dest.y, orig.z - dest.z}; double yaw = MathHelper.atan2(delta[0], -delta[2]); double dist = Math.sqrt(delta[0] * delta[0] + delta[2] * delta[2]); @@ -196,7 +199,7 @@ public final class RotationUtils { * @return The optional rotation */ public static Optional reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance) { - Rotation rotation = calcRotationFromVec3d(entity.getPositionEyes(1.0F), offsetPos); + Rotation rotation = calcRotationFromVec3d(entity.getPositionEyes(1.0F), offsetPos, new Rotation(entity.rotationYaw, entity.rotationPitch)); RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance); //System.out.println(result); if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 4599637a..15f4fa24 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -160,7 +160,7 @@ public abstract class Movement implements IMovement, MovementHelper { //i dont care if theres snow in the way!!!!!!! //you dont own me!!!! state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.player().getPositionEyes(1.0F), - VecUtils.getBlockPosCenter(blockPos)), true) + VecUtils.getBlockPosCenter(blockPos), ctx.playerRotations()), true) ); // don't check selectedblock on this one, this is a fallback when we can't see any face directly, it's intended to be breaking the "incorrect" block state.setInput(Input.CLICK_LEFT, true); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 729a2f1d..b0674887 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -78,7 +78,7 @@ public class MovementFall extends Movement { } BlockPos playerFeet = ctx.playerFeet(); - Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)); + Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest),ctx.playerRotations()); Rotation targetRotation = null; Block destBlock = ctx.world().getBlockState(dest).getBlock(); boolean isWater = destBlock == Blocks.WATER || destBlock == Blocks.FLOWING_WATER; @@ -141,7 +141,7 @@ public class MovementFall extends Movement { } if (targetRotation == null) { Vec3d destCenterOffset = new Vec3d(destCenter.x + 0.125 * avoid.getX(), destCenter.y, destCenter.z + 0.125 * avoid.getZ()); - state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), destCenterOffset), false)); + state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), destCenterOffset,ctx.playerRotations()), false)); } 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 03bdb6f7..d8c03b12 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -151,7 +151,7 @@ public class MovementPillar extends Movement { IBlockState fromDown = BlockStateInterface.get(ctx, src); if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(ctx, dest)) { // stay centered while swimming up a water column - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)), false)); + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest),ctx.playerRotations()), false)); Vec3d destCenter = VecUtils.getBlockPosCenter(dest); if (Math.abs(ctx.player().posX - destCenter.x) > 0.2 || Math.abs(ctx.player().posZ - destCenter.z) > 0.2) { state.setInput(Input.MOVE_FORWARD, true); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 74e4b6f3..f780c76a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -174,7 +174,7 @@ public class MovementTraverse extends Movement { // combine the yaw to the center of the destination, and the pitch to the specific block we're trying to break // it's safe to do this since the two blocks we break (in a traverse) are right on top of each other and so will have the same yaw - float yawToDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), dest)).getYaw(); + float yawToDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), dest), ctx.playerRotations()).getYaw(); float pitchToBreak = state.getTarget().getRotation().get().getPitch(); state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true)); @@ -198,7 +198,7 @@ public class MovementTraverse extends Movement { isDoorActuallyBlockingUs = true; } if (isDoorActuallyBlockingUs && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { - return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0])), true)) + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0]), ctx.playerRotations()), true)) .setInput(Input.CLICK_RIGHT, true); } } @@ -212,7 +212,7 @@ public class MovementTraverse extends Movement { } if (blocked != null) { - return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), blocked)), true)) + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), blocked), ctx.playerRotations()), true)) .setInput(Input.CLICK_RIGHT, true); } } From 0b4efb24aea3d63de75cf01cc53e0c9dce96699b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 13:57:33 -0800 Subject: [PATCH 153/682] momentous occasion: turning that crap off --- 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 0fb26134..95d56a0e 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -395,7 +395,7 @@ public final class Settings { /** * Print all the debug messages to chat */ - public final Setting chatDebug = new Setting<>(true); + public final Setting chatDebug = new Setting<>(false); /** * Allow chat based control of Baritone. Most likely should be disabled when Baritone is imported for use in From a21ec54d4f203eb7880a229e5d2503c7572638fc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 14:05:14 -0800 Subject: [PATCH 154/682] stop breaking block when you let go of left click lol --- .../java/baritone/launch/mixins/MixinKeyBinding.java | 2 +- src/main/java/baritone/behavior/PathingBehavior.java | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java index 6814b6d6..d61537c9 100644 --- a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java +++ b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java @@ -62,7 +62,7 @@ public class MixinKeyBinding { private void isPressed(CallbackInfoReturnable cir) { // only the primary baritone forces keys Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this); - if (pressTime > 0 && (KeyBinding) (Object) this == Minecraft.getMinecraft().gameSettings.keyBindAttack && Baritone.settings().clickCancel.get()) { + if (pressTime > 0 && (KeyBinding) (Object) this == Minecraft.getMinecraft().gameSettings.keyBindAttack && Baritone.settings().clickCancel.get() && BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().isPathing()) { Helper.HELPER.logDirect("Cancelling path on left click since the clickCancel setting is enabled!"); BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().cancelEverything(); return; diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index d441c416..bf96fd03 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -301,12 +301,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, public void secretInternalSegmentCancel() { queuePathEvent(PathEvent.CANCELED); synchronized (pathPlanLock) { - current = null; - next = null; + if (current != null) { + current = null; + next = null; + baritone.getInputOverrideHandler().clearAllKeys(); + getInProgress().ifPresent(AbstractNodeCostSearch::cancel); + baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); + } } - baritone.getInputOverrideHandler().clearAllKeys(); - getInProgress().ifPresent(AbstractNodeCostSearch::cancel); - baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); } public void forceCancel() { // NOT exposed on public api From f1bacd621092f49ff75c1c07f01f7335ef400e96 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 16:22:49 -0800 Subject: [PATCH 155/682] fix cancellation of unusable segments --- .../baritone/behavior/PathingBehavior.java | 45 ++++++++++--------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index bf96fd03..899a328f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -114,11 +114,27 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, cancelRequested = false; baritone.getInputOverrideHandler().clearAllKeys(); } - if (current == null) { - return; - } - safeToCancel = current.onTick(); synchronized (pathPlanLock) { + synchronized (pathCalcLock) { + if (inProgress != null) { + // we are calculating + // are we calculating the right thing though? 🤔 + BetterBlockPos calcFrom = inProgress.getStart(); + Optional currentBest = inProgress.bestPathSoFar(); + if ((current == null || !current.getPath().getDest().equals(calcFrom)) // if current ends in inProgress's start, then we're ok + && !calcFrom.equals(ctx.playerFeet()) && !calcFrom.equals(expectedSegmentStart) // if current starts in our playerFeet or pathStart, then we're ok + && (!currentBest.isPresent() || (!currentBest.get().positions().contains(ctx.playerFeet()) && !currentBest.get().positions().contains(expectedSegmentStart))) // if + ) { + // when it was *just* started, currentBest will be empty so we need to also check calcFrom since that's always present + inProgress.cancel(); // cancellation doesn't dispatch any events + inProgress = null; // this is safe since we hold both locks + } + } + } + if (current == null) { + return; + } + safeToCancel = current.onTick(); if (current.failed() || current.finished()) { current = null; if (goal == null || goal.isInGoal(ctx.playerFeet())) { @@ -127,7 +143,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, next = null; return; } - if (next != null && !next.getPath().positions().contains(ctx.playerFeet()) && !next.getPath().positions().contains(pathStart())) { // can contain either one + if (next != null && !next.getPath().positions().contains(ctx.playerFeet()) && !next.getPath().positions().contains(expectedSegmentStart)) { // can contain either one // if the current path failed, we may not actually be on the next one, so make sure logDebug("Discarding next path as it does not contain current position"); // for example if we had a nicely planned ahead path that starts where current ends @@ -149,23 +165,12 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // at this point, current just ended, but we aren't in the goal and have no plan for the future synchronized (pathCalcLock) { if (inProgress != null) { - // we are calculating - // are we calculating the right thing though? 🤔 - BetterBlockPos calcFrom = inProgress.getStart(); - // if current just succeeded, we should be standing in calcFrom, so that's cool and good - // but if current just failed, we should discard this calculation since it doesn't start from where we're standing - if (calcFrom.equals(ctx.playerFeet()) || calcFrom.equals(pathStart())) { - // cool and good - queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING); - return; - } - // oh noes - inProgress.cancel(); // cancellation doesn't dispatch any events - inProgress = null; // this is safe since we hold both locks + queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING); + return; } // we aren't calculating queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true); + findPathInNewThread(expectedSegmentStart, true); } return; } @@ -340,7 +345,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return false; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true); + findPathInNewThread(expectedSegmentStart, true); return true; } } From 9ecd24c7553b56f357c8c5e38ec66b898063f665 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 16:30:41 -0800 Subject: [PATCH 156/682] remove toxic cloud --- src/main/java/baritone/pathing/path/PathExecutor.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index c61ebc3d..9ff27afc 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -104,14 +104,6 @@ public class PathExecutor implements IPathExecutor, Helper { BetterBlockPos whereShouldIBe = path.positions().get(pathPosition); BetterBlockPos whereAmI = ctx.playerFeet(); if (!whereShouldIBe.equals(whereAmI)) { - - if (pathPosition == 0 && whereAmI.equals(whereShouldIBe.up()) && Math.abs(ctx.player().motionY) < 0.1 && !(path.movements().get(0) instanceof MovementAscend) && !(path.movements().get(0) instanceof MovementPillar)) { - // avoid the Wrong Y coordinate bug - // TODO add a timer here - new MovementDownward(behavior.baritone, whereAmI, whereShouldIBe).update(); - return false; - } - if (!Blocks.AIR.equals(BlockStateInterface.getBlock(ctx, whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks if (whereAmI.equals(path.positions().get(i))) { @@ -408,6 +400,7 @@ public class PathExecutor implements IPathExecutor, Helper { if (next instanceof MovementAscend && current.getDirection().up().equals(next.getDirection().down())) { // a descend then an ascend in the same direction pathPosition++; + onChangeInPathPosition(); // okay to skip clearKeys and / or onChangeInPathPosition here since this isn't possible to repeat, since it's asymmetric logDebug("Skipping descend to straight ascend"); return true; From b2583773d57afc978f74cbeb566f0517c767f847 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 16:30:53 -0800 Subject: [PATCH 157/682] discard next segment properly --- src/main/java/baritone/behavior/PathingBehavior.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 899a328f..e9e4d480 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -463,8 +463,12 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } else { if (next == null) { if (executor.isPresent()) { - queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_FINISHED); - next = executor.get(); + if (executor.get().getPath().getSrc().equals(current.getPath().getDest())) { + queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_FINISHED); + next = executor.get(); + } else { + logDebug("Warning: discarding orphan next segment with incorrect start"); + } } else { queuePathEvent(PathEvent.NEXT_CALC_FAILED); } From e8d3bf509c539a4f1dcb789d37a003cb3760ceba Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 16:33:27 -0800 Subject: [PATCH 158/682] clarify --- src/main/java/baritone/pathing/path/PathExecutor.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 9ff27afc..e78b5d7e 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -405,7 +405,7 @@ public class PathExecutor implements IPathExecutor, Helper { logDebug("Skipping descend to straight ascend"); return true; } - if (canSprintInto(ctx, current, next)) { + if (canSprintFromDescendInto(ctx, current, next)) { if (ctx.playerFeet().equals(current.getDest())) { pathPosition++; onChangeInPathPosition(); @@ -429,7 +429,7 @@ public class PathExecutor implements IPathExecutor, Helper { return false; } - private static boolean canSprintInto(IPlayerContext ctx, IMovement current, IMovement next) { + private static boolean canSprintFromDescendInto(IPlayerContext ctx, IMovement current, IMovement next) { if (next instanceof MovementDescend && next.getDirection().equals(current.getDirection())) { return true; } From a84b3bfc7a8fae5e25d1a9a3207d66b79347243f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 16:55:08 -0800 Subject: [PATCH 159/682] sprint through ascends whenever possible, fixes #149 --- .../movement/movements/MovementAscend.java | 2 +- .../baritone/pathing/path/PathExecutor.java | 47 ++++++++++++++++++- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 97eaa7fb..f2697016 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -200,7 +200,7 @@ public class MovementAscend extends Movement { return state.setInput(Input.JUMP, true); } - private boolean headBonkClear() { + public boolean headBonkClear() { BetterBlockPos startUp = src.up(2); for (int i = 0; i < 4; i++) { BetterBlockPos check = startUp.offset(EnumFacing.byHorizontalIndex(i)); diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index e78b5d7e..23b5861b 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -380,14 +380,26 @@ public class PathExecutor implements IPathExecutor, Helper { if (!new CalculationContext(behavior.baritone).canSprint) { return false; } + IMovement current = path.movements().get(pathPosition); + + // traverse requests sprinting, so we need to do this check first + if (current instanceof MovementTraverse && pathPosition < path.length() - 2) { + IMovement next = path.movements().get(pathPosition + 1); + if (next instanceof MovementAscend && sprintableAscend(ctx, (MovementTraverse) current, (MovementAscend) next)) { + logDebug("Skipping traverse to straight ascend"); + pathPosition++; + onChangeInPathPosition(); + onTick(); + return true; + } + } // if the movement requested sprinting, then we're done if (requested) { return true; } - // however, descend doesn't request sprinting, beceause it doesn't know the context of what movement comes after it - IMovement current = path.movements().get(pathPosition); + // however, descend and ascend don't request sprinting, because they don't know the context of what movement comes after it if (current instanceof MovementDescend) { if (((MovementDescend) current).safeMode() && !((MovementDescend) current).skipToAscend()) { @@ -401,6 +413,7 @@ public class PathExecutor implements IPathExecutor, Helper { // a descend then an ascend in the same direction pathPosition++; onChangeInPathPosition(); + onTick(); // okay to skip clearKeys and / or onChangeInPathPosition here since this isn't possible to repeat, since it's asymmetric logDebug("Skipping descend to straight ascend"); return true; @@ -425,10 +438,40 @@ public class PathExecutor implements IPathExecutor, Helper { return true; } } + if (prev instanceof MovementTraverse && sprintableAscend(ctx, (MovementTraverse) prev, (MovementAscend) current)) { + return true; + } } return false; } + private static boolean sprintableAscend(IPlayerContext ctx, MovementTraverse current, MovementAscend next) { + if (!current.getDirection().equals(next.getDirection().down())) { + return false; + } + if (!MovementHelper.canWalkOn(ctx, current.getDest().down())) { + return false; + } + if (!next.headBonkClear()) { + return false; + } + for (int x = 0; x < 2; x++) { + for (int y = 0; y < 3; y++) { + BlockPos chk = current.getSrc().up(y); + if (x == 1) { + chk = chk.add(current.getDirection()); + } + if (!MovementHelper.fullyPassable(ctx.world().getBlockState(chk))) { + return false; + } + } + } + if (MovementHelper.avoidWalkingInto(ctx.world().getBlockState(current.getSrc().up(3)).getBlock())) { + return false; + } + return true; + } + private static boolean canSprintFromDescendInto(IPlayerContext ctx, IMovement current, IMovement next) { if (next instanceof MovementDescend && next.getDirection().equals(current.getDirection())) { return true; From dbd760fbcb0c9ac97411c6cdcf2dafb2958de17d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 18:26:30 -0800 Subject: [PATCH 160/682] some polish on ascend sprinting --- src/api/java/baritone/api/Settings.java | 5 +++ .../baritone/pathing/path/PathExecutor.java | 36 ++++++++++++++----- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 95d56a0e..97ee278e 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -164,6 +164,11 @@ public final class Settings { */ public final Setting considerPotionEffects = new Setting<>(true); + /** + * Sprint and jump a block early on ascends wherever possible + */ + public final Setting sprintAscends = new Setting<>(true); + /** * This is the big A* setting. * As long as your cost heuristic is an *underestimate*, it's guaranteed to find you the best path. diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 23b5861b..4321eba2 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -386,11 +386,16 @@ public class PathExecutor implements IPathExecutor, Helper { if (current instanceof MovementTraverse && pathPosition < path.length() - 2) { IMovement next = path.movements().get(pathPosition + 1); if (next instanceof MovementAscend && sprintableAscend(ctx, (MovementTraverse) current, (MovementAscend) next)) { - logDebug("Skipping traverse to straight ascend"); - pathPosition++; - onChangeInPathPosition(); - onTick(); - return true; + if (skipNow(ctx, current, next)) { + logDebug("Skipping traverse to straight ascend"); + pathPosition++; + onChangeInPathPosition(); + onTick(); + behavior.baritone.getInputOverrideHandler().setInputForceState(Input.JUMP, true); + return true; + } else { + logDebug("Too far to the side to safely sprint ascend"); + } } } @@ -445,16 +450,31 @@ public class PathExecutor implements IPathExecutor, Helper { return false; } + private static boolean skipNow(IPlayerContext ctx, IMovement current, IMovement next) { + double offTarget = Math.abs(current.getDirection().getX() * (current.getSrc().z + 0.5D - ctx.player().posZ)) + Math.abs(current.getDirection().getZ() * (current.getSrc().x + 0.5D - ctx.player().posX)); + if (offTarget > 0.1) { + return false; + } + // we are centered + BlockPos headBonk = current.getSrc().subtract(current.getDirection()).up(2); + if (MovementHelper.fullyPassable(ctx.world().getBlockState(headBonk))) { + return true; + } + // wait 0.3 + double flatDist = Math.abs(current.getDirection().getX() * (headBonk.getX() + 0.5D - ctx.player().posX)) + Math.abs(current.getDirection().getZ() * (headBonk.getZ() + 0.5 - ctx.player().posZ)); + return flatDist > 0.8; + } + private static boolean sprintableAscend(IPlayerContext ctx, MovementTraverse current, MovementAscend next) { + if (!Baritone.settings().sprintAscends.get()) { + return false; + } if (!current.getDirection().equals(next.getDirection().down())) { return false; } if (!MovementHelper.canWalkOn(ctx, current.getDest().down())) { return false; } - if (!next.headBonkClear()) { - return false; - } for (int x = 0; x < 2; x++) { for (int y = 0; y < 3; y++) { BlockPos chk = current.getSrc().up(y); From bffeb9c86287728e39c3c7b784de4a60d5ac2c03 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 18:38:46 -0800 Subject: [PATCH 161/682] forgot one extra check --- src/main/java/baritone/pathing/path/PathExecutor.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 4321eba2..468dcfa6 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -489,6 +489,9 @@ public class PathExecutor implements IPathExecutor, Helper { if (MovementHelper.avoidWalkingInto(ctx.world().getBlockState(current.getSrc().up(3)).getBlock())) { return false; } + if (MovementHelper.avoidWalkingInto(ctx.world().getBlockState(next.getDest().up(2)).getBlock())) { + return false; + } return true; } From d0548b27159145d854acfb6b48c32c785726e05d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 18:39:26 -0800 Subject: [PATCH 162/682] add a warning --- 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 97ee278e..25244007 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -479,7 +479,7 @@ public final class Settings { public final Setting pathThroughCachedOnly = new Setting<>(false); /** - * 😎 Render cached chunks as semitransparent. Doesn't work with OptiFine 😭 + * 😎 Render cached chunks as semitransparent. Doesn't work with OptiFine 😭 Rarely randomly crashes, see this issue. *

* Can be very useful on servers with low render distance. After enabling, you may need to reload the world in order for it to have an effect * (e.g. disconnect and reconnect, enter then exit the nether, die and respawn, etc). This may literally kill your FPS and CPU because From 5b8a83853d5b03bb77b2fd04ba0e1bb804d065d6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 19:23:16 -0800 Subject: [PATCH 163/682] add setting to sprint in water --- src/api/java/baritone/api/Settings.java | 5 +++++ .../pathing/movement/movements/MovementDiagonal.java | 3 ++- .../pathing/movement/movements/MovementTraverse.java | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 25244007..b4e595ac 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -478,6 +478,11 @@ public final class Settings { */ public final Setting pathThroughCachedOnly = new Setting<>(false); + /** + * Continue sprinting while in water + */ + public final Setting sprintInWater = new Setting<>(true); + /** * 😎 Render cached chunks as semitransparent. Doesn't work with OptiFine 😭 Rarely randomly crashes, see this issue. *

diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index f34e9468..f156ff1b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -17,6 +17,7 @@ package baritone.pathing.movement.movements; +import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; @@ -181,7 +182,7 @@ public class MovementDiagonal extends Movement { } public boolean sprint() { - if (MovementHelper.isLiquid(ctx, ctx.playerFeet())) { + if (MovementHelper.isLiquid(ctx, ctx.playerFeet()) && !Baritone.settings().sprintInWater.get()) { return false; } for (int i = 0; i < 4; i++) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index f780c76a..65dec97d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -234,7 +234,7 @@ public class MovementTraverse extends Movement { BlockPos into = dest.subtract(src).add(dest); Block intoBelow = BlockStateInterface.get(ctx, into).getBlock(); Block intoAbove = BlockStateInterface.get(ctx, into.up()).getBlock(); - if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(ctx, ctx.playerFeet()) && !MovementHelper.avoidWalkingInto(intoBelow) && !MovementHelper.avoidWalkingInto(intoAbove)) { + if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, ctx.playerFeet()) || Baritone.settings().sprintInWater.get()) && !MovementHelper.avoidWalkingInto(intoBelow) && !MovementHelper.avoidWalkingInto(intoAbove)) { state.setInput(Input.SPRINT, true); } Block destDown = BlockStateInterface.get(ctx, dest.down()).getBlock(); From b27d95a61554e3d92150c93f3bafc8fc337c03c9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 21:11:13 -0800 Subject: [PATCH 164/682] proper fall overshooting --- .../pathing/movement/MovementHelper.java | 5 +- .../baritone/pathing/path/PathExecutor.java | 61 +++++++++++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index f91103d0..0f6659b9 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -439,11 +439,10 @@ public interface MovementHelper extends ActionCosts, Helper { } static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) { - EntityPlayerSP player = ctx.player(); state.setTarget(new MovementTarget( - new Rotation(RotationUtils.calcRotationFromVec3d(player.getPositionEyes(1.0F), + new Rotation(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(pos), - new Rotation(player.rotationYaw, player.rotationPitch)).getYaw(), player.rotationPitch), + ctx.playerRotations()).getYaw(), ctx.player().rotationPitch), false )).setInput(Input.MOVE_FORWARD, true); } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 468dcfa6..db46d2fb 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -25,6 +25,7 @@ import baritone.api.pathing.movement.MovementStatus; import baritone.api.pathing.path.IPathExecutor; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.IPlayerContext; +import baritone.api.utils.RotationUtils; import baritone.api.utils.VecUtils; import baritone.api.utils.input.Input; import baritone.behavior.PathingBehavior; @@ -39,6 +40,8 @@ import net.minecraft.block.BlockLiquid; import net.minecraft.init.Blocks; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.Vec3i; import java.util.*; @@ -114,6 +117,7 @@ public class PathExecutor implements IPathExecutor, Helper { path.movements().get(j).reset(); } onChangeInPathPosition(); + onTick(); return false; } } @@ -126,6 +130,7 @@ public class PathExecutor implements IPathExecutor, Helper { //System.out.println("Double skip sundae"); pathPosition = i - 1; onChangeInPathPosition(); + onTick(); return false; } } @@ -447,9 +452,65 @@ public class PathExecutor implements IPathExecutor, Helper { return true; } } + if (current instanceof MovementFall) { + Tuple data = overrideFall((MovementFall) current); + if (data != null) { + BlockPos fallDest = data.getSecond(); + if (!path.positions().contains(fallDest)) { + throw new IllegalStateException(); + } + if (ctx.playerFeet().equals(fallDest)) { + pathPosition = path.positions().indexOf(fallDest); + onChangeInPathPosition(); + onTick(); + return true; + } + logDebug("Skipping fall to " + fallDest + " " + data.getFirst()); + clearKeys(); + behavior.baritone.getLookBehavior().updateTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), data.getFirst(), ctx.playerRotations()), false); + behavior.baritone.getInputOverrideHandler().setInputForceState(Input.MOVE_FORWARD, true); + return true; + } + } return false; } + private Tuple overrideFall(MovementFall movement) { + Vec3i dir = movement.getDirection(); + if (dir.getY() < -3) { + return null; + } + Vec3i flatDir = new Vec3i(dir.getX(), 0, dir.getZ()); + int i; + outer: + for (i = pathPosition + 1; i < path.length() - 1 && i < pathPosition + 3; i++) { + IMovement next = path.movements().get(i); + if (!(next instanceof MovementTraverse)) { + break; + } + if (!flatDir.equals(next.getDirection())) { + break; + } + for (int y = next.getDest().y; y <= movement.getSrc().y + 1; y++) { + BlockPos chk = new BlockPos(next.getDest().x, y, next.getDest().z); + if (!MovementHelper.fullyPassable(ctx.world().getBlockState(chk))) { + break outer; + } + } + if (!MovementHelper.canWalkOn(ctx, next.getDest().down())) { + break; + } + } + i--; + if (i == pathPosition) { + return null; // no valid extension exists + } + double len = i - pathPosition - 0.4; + return new Tuple<>( + new Vec3d(flatDir.getX() * len + movement.getDest().x + 0.5, movement.getDest().y, flatDir.getZ() * len + movement.getDest().z + 0.5), + movement.getDest().add(flatDir.getX() * (i - pathPosition), 0, flatDir.getZ() * (i - pathPosition))); + } + private static boolean skipNow(IPlayerContext ctx, IMovement current, IMovement next) { double offTarget = Math.abs(current.getDirection().getX() * (current.getSrc().z + 0.5D - ctx.player().posZ)) + Math.abs(current.getDirection().getZ() * (current.getSrc().x + 0.5D - ctx.player().posX)); if (offTarget > 0.1) { From 41b1106c72daa60be78b6b88d3d6154c4490c1d2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 21:20:06 -0800 Subject: [PATCH 165/682] sprint in water for real --- .../baritone/pathing/movement/movements/MovementTraverse.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 65dec97d..c1d660d0 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -234,7 +234,7 @@ public class MovementTraverse extends Movement { BlockPos into = dest.subtract(src).add(dest); Block intoBelow = BlockStateInterface.get(ctx, into).getBlock(); Block intoAbove = BlockStateInterface.get(ctx, into.up()).getBlock(); - if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, ctx.playerFeet()) || Baritone.settings().sprintInWater.get()) && !MovementHelper.avoidWalkingInto(intoBelow) && !MovementHelper.avoidWalkingInto(intoAbove)) { + if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, ctx.playerFeet()) || Baritone.settings().sprintInWater.get()) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) { state.setInput(Input.SPRINT, true); } Block destDown = BlockStateInterface.get(ctx, dest.down()).getBlock(); From 3f1ee100bfd4f4554ad5bc5a7afd10eaaf195151 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 22:39:34 -0800 Subject: [PATCH 166/682] only sprint ascends that are followed in the same direction --- src/main/java/baritone/pathing/path/PathExecutor.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index db46d2fb..c84a4311 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -388,9 +388,9 @@ public class PathExecutor implements IPathExecutor, Helper { IMovement current = path.movements().get(pathPosition); // traverse requests sprinting, so we need to do this check first - if (current instanceof MovementTraverse && pathPosition < path.length() - 2) { + if (current instanceof MovementTraverse && pathPosition < path.length() - 3) { IMovement next = path.movements().get(pathPosition + 1); - if (next instanceof MovementAscend && sprintableAscend(ctx, (MovementTraverse) current, (MovementAscend) next)) { + if (next instanceof MovementAscend && sprintableAscend(ctx, (MovementTraverse) current, (MovementAscend) next, path.movements().get(pathPosition + 2))) { if (skipNow(ctx, current, next)) { logDebug("Skipping traverse to straight ascend"); pathPosition++; @@ -448,7 +448,7 @@ public class PathExecutor implements IPathExecutor, Helper { return true; } } - if (prev instanceof MovementTraverse && sprintableAscend(ctx, (MovementTraverse) prev, (MovementAscend) current)) { + if (pathPosition < path.length() - 2 && prev instanceof MovementTraverse && sprintableAscend(ctx, (MovementTraverse) prev, (MovementAscend) current, path.movements().get(pathPosition + 1))) { return true; } } @@ -526,13 +526,16 @@ public class PathExecutor implements IPathExecutor, Helper { return flatDist > 0.8; } - private static boolean sprintableAscend(IPlayerContext ctx, MovementTraverse current, MovementAscend next) { + private static boolean sprintableAscend(IPlayerContext ctx, MovementTraverse current, MovementAscend next, IMovement nextnext) { if (!Baritone.settings().sprintAscends.get()) { return false; } if (!current.getDirection().equals(next.getDirection().down())) { return false; } + if (nextnext.getDirection().getX() != next.getDirection().getX() || nextnext.getDirection().getZ() != next.getDirection().getZ()) { + return false; + } if (!MovementHelper.canWalkOn(ctx, current.getDest().down())) { return false; } From 5b6c9fc348e777ce0a346130e1f2f73ca0ad2a34 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 22:39:43 -0800 Subject: [PATCH 167/682] blacklist unreachable gettoblocks --- src/api/java/baritone/api/Settings.java | 6 +++ .../baritone/process/GetToBlockProcess.java | 54 ++++++++++++++----- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index b4e595ac..4e1cc9cd 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -483,6 +483,12 @@ public final class Settings { */ public final Setting sprintInWater = new Setting<>(true); + /** + * When GetToBlockProcess fails to calculate a path, instead of just giving up, mark the closest instances + * of that block as "unreachable" and go towards the next closest + */ + public final Setting blacklistOnGetToBlockFailure = new Setting<>(true); + /** * 😎 Render cached chunks as semitransparent. Doesn't work with OptiFine 😭 Rarely randomly crashes, see this issue. *

diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index a6e2e68b..6a0a44f7 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -32,15 +32,14 @@ import net.minecraft.init.Blocks; import net.minecraft.inventory.ContainerPlayer; import net.minecraft.util.math.BlockPos; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Optional; +import java.util.*; +import java.util.stream.Collectors; public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess { private Block gettingTo; private List knownLocations; + private List blacklist; // locations we failed to calc to private BlockPos start; private int tickCount = 0; @@ -54,6 +53,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl onLostControl(); gettingTo = block; start = ctx.playerFeet(); + blacklist = new ArrayList<>(); rescan(new ArrayList<>(), new CalculationContext(baritone)); } @@ -63,7 +63,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } @Override - public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + public synchronized PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (knownLocations == null) { rescan(new ArrayList<>(), new CalculationContext(baritone)); } @@ -84,11 +84,17 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } Goal goal = new GoalComposite(knownLocations.stream().map(this::createGoal).toArray(Goal[]::new)); if (calcFailed) { - logDirect("Unable to find any path to " + gettingTo + ", canceling GetToBlock"); - if (isSafeToCancel) { - onLostControl(); + if (Baritone.settings().blacklistOnGetToBlockFailure.get()) { + logDirect("Unable to find any path to " + gettingTo + ", blacklisting presumably unreachable closest instances"); + blacklistClosest(); + return onTick(false, isSafeToCancel); // gamer moment + } else { + logDirect("Unable to find any path to " + gettingTo + ", canceling GetToBlock"); + if (isSafeToCancel) { + onLostControl(); + } + return new PathingCommand(goal, PathingCommandType.CANCEL_AND_SET_GOAL); } - return new PathingCommand(goal, PathingCommandType.CANCEL_AND_SET_GOAL); } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain @@ -111,11 +117,33 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH); } + public synchronized void blacklistClosest() { + List newBlacklist = knownLocations.stream().sorted(Comparator.comparingDouble(ctx.player()::getDistanceSq)).collect(Collectors.toList()).subList(0, 1); + outer: + while (true) { + for (BlockPos known : knownLocations) { + for (BlockPos blacklist : newBlacklist) { + if (known.distanceSq(blacklist) == 1) { // directly adjacent + newBlacklist.add(known); + knownLocations.remove(known); + continue outer; + } + } + } + if (true) { + break; // codacy gets mad if i just end on a break LOL + } + } + logDebug("Blacklisting unreachable locations " + newBlacklist); + blacklist.addAll(newBlacklist); + } + @Override - public void onLostControl() { + public synchronized void onLostControl() { gettingTo = null; knownLocations = null; start = null; + blacklist = null; baritone.getInputOverrideHandler().clearAllKeys(); } @@ -124,8 +152,10 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl return "Get To Block " + gettingTo; } - private void rescan(List known, CalculationContext context) { - knownLocations = MineProcess.searchWorld(context, Collections.singletonList(gettingTo), 64, known); + private synchronized void rescan(List known, CalculationContext context) { + List positions = MineProcess.searchWorld(context, Collections.singletonList(gettingTo), 64, known); + positions.removeIf(blacklist::contains); + knownLocations = positions; } private Goal createGoal(BlockPos pos) { From f094e83e4dd149c14f56f96910b67de8d0236a48 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Feb 2019 22:41:18 -0800 Subject: [PATCH 168/682] codacy --- .../src/main/java/baritone/gradle/task/BaritoneGradleTask.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java index 4f7674f6..7e26dac1 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java @@ -17,8 +17,6 @@ package baritone.gradle.task; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; import org.gradle.api.DefaultTask; import java.io.File; @@ -26,7 +24,6 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.List; /** * @author Brady From 4fe9c180d5e0a063d625a8496dab470607c4b299 Mon Sep 17 00:00:00 2001 From: babbaj Date: Thu, 14 Feb 2019 07:03:22 -0500 Subject: [PATCH 169/682] Fix potential problems --- .../java/baritone/process/GetToBlockProcess.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 6a0a44f7..89f60da3 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -33,7 +33,6 @@ import net.minecraft.inventory.ContainerPlayer; import net.minecraft.util.math.BlockPos; import java.util.*; -import java.util.stream.Collectors; public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess { @@ -117,13 +116,15 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH); } + // blacklist the closest block and its adjacent blocks public synchronized void blacklistClosest() { - List newBlacklist = knownLocations.stream().sorted(Comparator.comparingDouble(ctx.player()::getDistanceSq)).collect(Collectors.toList()).subList(0, 1); + List newBlacklist = new ArrayList<>(); + knownLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(newBlacklist::add); outer: while (true) { for (BlockPos known : knownLocations) { for (BlockPos blacklist : newBlacklist) { - if (known.distanceSq(blacklist) == 1) { // directly adjacent + if (areAdjacent(known, blacklist)) { // directly adjacent newBlacklist.add(known); knownLocations.remove(known); continue outer; @@ -138,6 +139,14 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl blacklist.addAll(newBlacklist); } + // safer than direct double comparison from distanceSq + private boolean areAdjacent(BlockPos posA, BlockPos posB) { + int diffX = Math.abs(posA.getX() - posB.getX()); + int diffY = Math.abs(posA.getY() - posB.getY()); + int diffZ = Math.abs(posA.getZ() - posB.getZ()); + return (diffX + diffY + diffZ) == 1; + } + @Override public synchronized void onLostControl() { gettingTo = null; From 89b5ce4b6327d91495c2fb2f9893feb3f1c2c711 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 14 Feb 2019 14:47:38 -0800 Subject: [PATCH 170/682] properly detect failure --- src/main/java/baritone/process/GetToBlockProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 6a0a44f7..b6151f5c 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -68,7 +68,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl rescan(new ArrayList<>(), new CalculationContext(baritone)); } if (knownLocations.isEmpty()) { - if (Baritone.settings().exploreForBlocks.get()) { + if (Baritone.settings().exploreForBlocks.get() && !calcFailed) { return new PathingCommand(new GoalRunAway(1, start) { @Override public boolean isInGoal(int x, int y, int z) { From 46c2d8f7c7c38be3d888825dd6223b6cf6190931 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 15 Feb 2019 21:35:52 -0800 Subject: [PATCH 171/682] unneeded --- src/main/java/baritone/pathing/path/PathExecutor.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index c84a4311..1a221af3 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -465,7 +465,6 @@ public class PathExecutor implements IPathExecutor, Helper { onTick(); return true; } - logDebug("Skipping fall to " + fallDest + " " + data.getFirst()); clearKeys(); behavior.baritone.getLookBehavior().updateTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), data.getFirst(), ctx.playerRotations()), false); behavior.baritone.getInputOverrideHandler().setInputForceState(Input.MOVE_FORWARD, true); From 11af0a7aac65f0e061227d197870400c21e1d831 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 15 Feb 2019 21:36:34 -0800 Subject: [PATCH 172/682] v1.1.5 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index ceb024c1..d31ea10e 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.1.4' +version '1.1.5' buildscript { repositories { From 266e2dada9e5218ea94f4b102c5d104403a33aa2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 16 Feb 2019 20:49:38 -0800 Subject: [PATCH 173/682] cleanup --- src/main/java/baritone/utils/PathRenderer.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 9f07efdf..73bccbd5 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -57,8 +57,6 @@ public final class PathRenderer implements Helper { private PathRenderer() {} public static void render(RenderEvent event, PathingBehavior behavior) { - // System.out.println("Render passing"); - // System.out.println(event.getPartialTicks()); float partialTicks = event.getPartialTicks(); Goal goal = behavior.getGoal(); From 530cecea5b8f3877cf5af2392b45504dbd77a055 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 17 Feb 2019 21:41:54 -0800 Subject: [PATCH 174/682] it flows better this way --- src/main/java/baritone/utils/PathRenderer.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 73bccbd5..b9a6ad15 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -78,7 +78,7 @@ public final class PathRenderer implements Helper { } if (goal != null && Baritone.settings().renderGoal.value) { - drawLitDankGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.get()); + drawDankLitGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.get()); } if (!Baritone.settings().renderPath.get()) { return; @@ -259,7 +259,7 @@ public final class PathRenderer implements Helper { GlStateManager.disableBlend(); } - public static void drawLitDankGoalBox(Entity player, Goal goal, float partialTicks, Color color) { + public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTicks, Color color) { double renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks; double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; @@ -330,7 +330,7 @@ public final class PathRenderer implements Helper { maxY = 256 - renderPosY; } else if (goal instanceof GoalComposite) { for (Goal g : ((GoalComposite) goal).goals()) { - drawLitDankGoalBox(player, g, partialTicks, color); + drawDankLitGoalBox(player, g, partialTicks, color); } return; } else { From d2bb8c374ea9316739e7e7f08e535d80a2b0135e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 18 Feb 2019 21:18:37 -0800 Subject: [PATCH 175/682] explain --- src/main/java/baritone/cache/CachedWorld.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index b604ce48..db85339d 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -45,7 +45,7 @@ public final class CachedWorld implements ICachedWorld, Helper { /** * The maximum number of regions in any direction from (0,0) */ - private static final int REGION_MAX = 58594; + private static final int REGION_MAX = 30_000_000 / 512 + 1; /** * A map of all of the cached regions. From c486d8241e20cf36e77ccc5bf465f4cc316388be Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 07:53:36 -0800 Subject: [PATCH 176/682] continue --- src/main/java/baritone/utils/PlayerMovementInput.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/PlayerMovementInput.java b/src/main/java/baritone/utils/PlayerMovementInput.java index 4ffbef2b..c2e2db2a 100644 --- a/src/main/java/baritone/utils/PlayerMovementInput.java +++ b/src/main/java/baritone/utils/PlayerMovementInput.java @@ -31,7 +31,7 @@ public class PlayerMovementInput extends MovementInput { this.moveStrafe = 0.0F; this.moveForward = 0.0F; - jump = handler.isInputForcedDown(Input.JUMP); // oppa + jump = handler.isInputForcedDown(Input.JUMP); // oppa gangnam if (this.forwardKeyDown = handler.isInputForcedDown(Input.MOVE_FORWARD)) { this.moveForward++; From 6702b44b3ea4941884547e44d1baa0a3e4a2ef7f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 12:43:44 -0800 Subject: [PATCH 177/682] reformatted and fixed stuck on break fall --- .../baritone/pathing/movement/movements/MovementFall.java | 4 ++-- .../baritone/pathing/movement/movements/MovementPillar.java | 2 +- src/main/java/baritone/pathing/path/PathExecutor.java | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index b0674887..93f60f5d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -78,7 +78,7 @@ public class MovementFall extends Movement { } BlockPos playerFeet = ctx.playerFeet(); - Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest),ctx.playerRotations()); + Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()); Rotation targetRotation = null; Block destBlock = ctx.world().getBlockState(dest).getBlock(); boolean isWater = destBlock == Blocks.WATER || destBlock == Blocks.FLOWING_WATER; @@ -141,7 +141,7 @@ public class MovementFall extends Movement { } if (targetRotation == null) { Vec3d destCenterOffset = new Vec3d(destCenter.x + 0.125 * avoid.getX(), destCenter.y, destCenter.z + 0.125 * avoid.getZ()); - state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), destCenterOffset,ctx.playerRotations()), false)); + state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), destCenterOffset, ctx.playerRotations()), false)); } 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 d8c03b12..d430f8c5 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -151,7 +151,7 @@ public class MovementPillar extends Movement { IBlockState fromDown = BlockStateInterface.get(ctx, src); if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(ctx, dest)) { // stay centered while swimming up a water column - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest),ctx.playerRotations()), false)); + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()), false)); Vec3d destCenter = VecUtils.getBlockPosCenter(dest); if (Math.abs(ctx.player().posX - destCenter.x) > 0.2 || Math.abs(ctx.player().posZ - destCenter.z) > 0.2) { state.setInput(Input.MOVE_FORWARD, true); diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 1a221af3..44882b98 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -479,6 +479,9 @@ public class PathExecutor implements IPathExecutor, Helper { if (dir.getY() < -3) { return null; } + if (!movement.toBreakCached.isEmpty()) { + return null; // it's breaking + } Vec3i flatDir = new Vec3i(dir.getX(), 0, dir.getZ()); int i; outer: From ed2b0f0bb90a2ccfa6524197469a87ba86cf8c49 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 12:44:29 -0800 Subject: [PATCH 178/682] fix jump before place ascend --- src/main/java/baritone/pathing/path/PathExecutor.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 44882b98..07fe0943 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -541,6 +541,9 @@ public class PathExecutor implements IPathExecutor, Helper { if (!MovementHelper.canWalkOn(ctx, current.getDest().down())) { return false; } + if (!MovementHelper.canWalkOn(ctx, next.getDest().down())) { + return false; + } for (int x = 0; x < 2; x++) { for (int y = 0; y < 3; y++) { BlockPos chk = current.getSrc().up(y); From 76c4ca9ba6ef0089e038f77bdbfac641d3d1391a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 12:55:58 -0800 Subject: [PATCH 179/682] fix path reliability after lateral movement --- .../movement/movements/MovementAscend.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index f2697016..5bb6281f 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -181,14 +181,21 @@ public class MovementAscend extends Movement { return state; } - if (headBonkClear()) { - return state.setInput(Input.JUMP, true); - } - int xAxis = Math.abs(src.getX() - dest.getX()); // either 0 or 1 int zAxis = Math.abs(src.getZ() - dest.getZ()); // either 0 or 1 double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ); double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ); + + double lateralMotion = xAxis * ctx.player().motionZ + zAxis * ctx.player().motionX; + if (Math.abs(lateralMotion) > 0.1) { + return state; + } + + if (headBonkClear()) { + return state.setInput(Input.JUMP, true); + } + + // System.out.println(flatDistToNext + " " + sideDist); if (flatDistToNext > 1.2 || sideDist > 0.2) { return state; From a8ddb2fcf1254384cd4b7d191f51bff0d782de66 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 13:28:58 -0800 Subject: [PATCH 180/682] also disallow while breaking --- src/main/java/baritone/pathing/path/PathExecutor.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 07fe0943..d4897eec 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -544,6 +544,9 @@ public class PathExecutor implements IPathExecutor, Helper { if (!MovementHelper.canWalkOn(ctx, next.getDest().down())) { return false; } + if (!next.toBreakCached.isEmpty()) { + return false; // it's breaking + } for (int x = 0; x < 2; x++) { for (int y = 0; y < 3; y++) { BlockPos chk = current.getSrc().up(y); From 87705246790830c3ecf722b0cf81e00bcb1ebcce Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 14:29:08 -0800 Subject: [PATCH 181/682] fix weird angle forcing behavior, fixes #341 --- 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 c2d0326c..9ee059c6 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -103,7 +103,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior { @Override public void onPlayerRotationMove(RotationMoveEvent event) { - if (this.target != null && !this.force) { + if (this.target != null) { event.setYaw(this.target.getYaw()); From 5617c595b2259fa1838c356f1c37373b5135704c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 14:43:48 -0800 Subject: [PATCH 182/682] public init --- src/api/java/baritone/api/IBaritone.java | 7 +++++++ src/main/java/baritone/Baritone.java | 1 + 2 files changed, 8 insertions(+) diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index 6bdb7d10..21157eb1 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -76,4 +76,11 @@ public interface IBaritone { IPlayerContext getPlayerContext(); IEventBus getGameEventHandler(); + + /** + * Call as soon as Minecraft is ready. + *

+ * Or whenever your overeager utility client wants. + */ + void init(); } diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 3414fdf3..2eb69cba 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -92,6 +92,7 @@ public class Baritone implements IBaritone { this.gameEventHandler = new GameEventHandler(this); } + @Override public synchronized void init() { if (initialized) { return; From f7a9380b9dc2507e439f1fa9c57d1c082d8e6f21 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 14:53:43 -0800 Subject: [PATCH 183/682] v1.1.6 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index d31ea10e..996a8e0f 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.1.5' +version '1.1.6' buildscript { repositories { From 8fd687f9d77223a6b96527b390427252c0bdef41 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 15:04:18 -0800 Subject: [PATCH 184/682] more usage help --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index aa57e346..edd426a3 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -77,7 +77,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { "sethome - Sets \"home\"\n" + "home - Paths towards \"home\" \n" + "costs - (debug) all movement costs from current location\n" + - "damn - Daniel "; + "damn - Daniel\n" + + "Go to https://github.com/cabaletta/baritone/blob/master/USAGE.md for more information"; private static final String COMMAND_PREFIX = "#"; From 6d847577d8266f98eab3262e280440671831c6c8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 18:22:59 -0800 Subject: [PATCH 185/682] somehow missed those --- src/api/java/baritone/api/Settings.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 4e1cc9cd..2878e4d6 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -500,18 +500,18 @@ public final class Settings { *

* SOLID is rendered as stone in the overworld, netherrack in the nether, and end stone in the end */ - public Setting renderCachedChunks = new Setting<>(false); + public final Setting renderCachedChunks = new Setting<>(false); /** * 0.0f = not visible, fully transparent * 1.0f = fully opaque */ - public Setting cachedChunksOpacity = new Setting<>(0.5f); + public final Setting cachedChunksOpacity = new Setting<>(0.5f); /** * If true, Baritone will not allow you to left or right click while pathing */ - public Setting suppressClicks = new Setting<>(false); + public final Setting suppressClicks = new Setting<>(false); /** * Whether or not to use the "#" command prefix From d9625dfe78f1d0b66884eb8594e3def74f58a990 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 18:24:06 -0800 Subject: [PATCH 186/682] no longer needed crab rave --- scripts/proguard.pro | 3 --- 1 file changed, 3 deletions(-) diff --git a/scripts/proguard.pro b/scripts/proguard.pro index df6ad43a..dc08bd9e 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -21,9 +21,6 @@ -keep class baritone.BaritoneProvider -keep class baritone.api.IBaritoneProvider -# hack --keep class baritone.utils.ExampleBaritoneControl { *; } # have to include this string to remove this keep in the standalone build: # this is the keep api - # setting names are reflected from field names, so keep field names -keepclassmembers class baritone.api.Settings { public ; From 66356d53349dde6d9939b732cd46ab8b68758540 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 18:27:05 -0800 Subject: [PATCH 187/682] hmm --- src/main/java/baritone/utils/PathingControlManager.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index e748042e..54ed848a 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -82,6 +82,7 @@ public class PathingControlManager implements IPathingControlManager { public void preTick() { inControlLastTick = inControlThisTick; + inControlThisTick = null; PathingBehavior p = baritone.getPathingBehavior(); command = executeProcesses(); if (command == null) { From 70d216b29fbe4902edb0ff37a2ad3ccde4d42534 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 19 Feb 2019 21:00:14 -0600 Subject: [PATCH 188/682] Fix renderGoalXZBeacon path rendering incorrect color --- src/main/java/baritone/utils/PathRenderer.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index b9a6ad15..06e298be 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -295,6 +295,8 @@ public final class PathRenderer implements Helper { GoalXZ goalPos = (GoalXZ) goal; if (Baritone.settings().renderGoalXZBeacon.get()) { + glPushAttrib(GL_LIGHTING_BIT); + mc.getTextureManager().bindTexture(TileEntityBeaconRenderer.TEXTURE_BEACON_BEAM); if (Baritone.settings().renderGoalIgnoreDepth.get()) { @@ -316,6 +318,8 @@ public final class PathRenderer implements Helper { if (Baritone.settings().renderGoalIgnoreDepth.get()) { GlStateManager.enableDepth(); } + + glPopAttrib(); return; } From 84d8f826ff5372141c6c4a29e8b9a41144c005f3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 19:41:19 -0800 Subject: [PATCH 189/682] fine lol, fixes #340 --- .../baritone/pathing/movement/movements/MovementTraverse.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index c1d660d0..d618cf1a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -178,7 +178,7 @@ public class MovementTraverse extends Movement { float pitchToBreak = state.getTarget().getRotation().get().getPitch(); state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true)); - return state.setInput(Input.MOVE_FORWARD, true); + return state.setInput(Input.MOVE_FORWARD, true).setInput(Input.SPRINT, true); } //sneak may have been set to true in the PREPPING state while mining an adjacent block From a72040f83d6815bcc2dffbe2c8e8f757e9b1f806 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 19:52:11 -0800 Subject: [PATCH 190/682] imagine breaking the build --- scripts/proguard.pro | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/proguard.pro b/scripts/proguard.pro index dc08bd9e..e4189f7f 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -14,6 +14,7 @@ # lwjgl is weird -dontwarn org.lwjgl.opengl.GL14 +-dontwarn org.lwjgl.opengl.GL11 -keep class baritone.api.** { *; } # this is the keep api From 963641a818537a507bd20e09140fcfc609f3178d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 22:50:03 -0800 Subject: [PATCH 191/682] trim big schematics --- src/main/java/baritone/process/BuilderProcess.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 3db08d57..98e114c1 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -280,6 +280,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro onLostControl(); return null; } + trim(bcc); if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) { ticks = 5; } else { @@ -366,6 +367,14 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return !incorrectPositions.isEmpty(); } + public void trim(BuilderCalculationContext bcc) { + HashSet copy = new HashSet<>(incorrectPositions); + copy.removeIf(pos -> pos.distanceSq(ctx.player().posX, ctx.player().posY, ctx.player().posZ) > 200); + if (!copy.isEmpty()) { + incorrectPositions = copy; + } + } + public void recalcNearby(BuilderCalculationContext bcc) { BetterBlockPos center = ctx.playerFeet(); for (int dx = -5; dx <= 5; dx++) { From bf12763a100691035d20af5012f276771fb4c27b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 20 Feb 2019 08:08:52 -0800 Subject: [PATCH 192/682] fix a bunch of bugs with placement --- .../api/pathing/movement/IMovement.java | 4 ---- .../baritone/behavior/MemoryBehavior.java | 3 +-- .../baritone/behavior/PathingBehavior.java | 4 ++++ .../baritone/pathing/movement/Movement.java | 19 ++++++++----------- .../baritone/pathing/path/PathExecutor.java | 4 ++-- .../java/baritone/process/BuilderProcess.java | 3 +++ .../utils/ExampleBaritoneControl.java | 2 +- 7 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/api/java/baritone/api/pathing/movement/IMovement.java b/src/api/java/baritone/api/pathing/movement/IMovement.java index c9b9ea4b..dae8668d 100644 --- a/src/api/java/baritone/api/pathing/movement/IMovement.java +++ b/src/api/java/baritone/api/pathing/movement/IMovement.java @@ -45,10 +45,6 @@ public interface IMovement { */ boolean safeToCancel(); - double recalculateCost(); - - double calculateCostWithoutCaching(); - boolean calculatedWhileLoaded(); BetterBlockPos getSrc(); diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 390ac859..34fd6b41 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -25,7 +25,6 @@ import baritone.api.event.events.TickEvent; import baritone.api.event.events.type.EventState; import baritone.cache.ContainerMemory; import baritone.cache.Waypoint; -import baritone.pathing.movement.CalculationContext; import baritone.utils.BlockStateInterface; import net.minecraft.block.Block; import net.minecraft.block.BlockBed; @@ -196,7 +195,7 @@ public final class MemoryBehavior extends Behavior { } private BlockPos neighboringConnectedBlock(BlockPos in) { - BlockStateInterface bsi = new CalculationContext(baritone).bsi; + BlockStateInterface bsi = baritone.bsi; Block block = bsi.get0(in).getBlock(); if (block != Blocks.TRAPPED_CHEST && block != Blocks.CHEST) { return null; // other things that have contents, but can be placed adjacent without combining diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index bc3443a7..bda02de1 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -361,6 +361,10 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } } + public CalculationContext secretInternalGetCalculationContext() { + return context; + } + /** * See issue #209 * diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 07ee79aa..96b650e7 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -76,31 +76,28 @@ public abstract class Movement implements IMovement, MovementHelper { this(baritone, src, dest, toBreak, null); } - @Override - public double getCost() { + public double getCost() throws NullPointerException { + return cost; + } + + public double getCost(CalculationContext context) { if (cost == null) { - cost = calculateCost(new CalculationContext(baritone)); + cost = calculateCost(context); } return cost; } public abstract double calculateCost(CalculationContext context); - @Override - public double recalculateCost() { + public double recalculateCost(CalculationContext context) { cost = null; - return getCost(); + return getCost(context); } public void override(double cost) { this.cost = cost; } - @Override - public double calculateCostWithoutCaching() { - return calculateCost(new CalculationContext(baritone)); - } - /** * Handles the execution of the latest Movement * State, and offers a Status to the calling class. diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index d4897eec..4d3b5f3b 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -232,14 +232,14 @@ public class PathExecutor implements IPathExecutor, Helper { // do this only once, when the movement starts, and deliberately get the cost as cached when this path was calculated, not the cost as it is right now currentMovementOriginalCostEstimate = movement.getCost(); for (int i = 1; i < Baritone.settings().costVerificationLookahead.get() && pathPosition + i < path.length() - 1; i++) { - if (path.movements().get(pathPosition + i).calculateCostWithoutCaching() >= ActionCosts.COST_INF && canCancel) { + if (((Movement) path.movements().get(pathPosition + i)).calculateCost(behavior.secretInternalGetCalculationContext()) >= ActionCosts.COST_INF && canCancel) { logDebug("Something has changed in the world and a future movement has become impossible. Cancelling."); cancel(); return true; } } } - double currentCost = movement.recalculateCost(); + double currentCost = ((Movement) movement).recalculateCost(behavior.secretInternalGetCalculationContext()); if (currentCost >= ActionCosts.COST_INF && canCancel) { logDebug("Something has changed in the world and this movement has become impossible. Cancelling."); cancel(); diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 98e114c1..e7c2f65a 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -465,6 +465,9 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } public Goal placementgoal(BlockPos pos, BuilderCalculationContext bcc) { + if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) { + return new GoalPlace(pos); + } boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR; for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP) { if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ()).getBlock(), pos, false, facing, null)) { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index ccca14ba..d3626569 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -558,7 +558,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { while (moves.contains(null)) { moves.remove(null); } - moves.sort(Comparator.comparingDouble(Movement::getCost)); + moves.sort(Comparator.comparingDouble(move -> move.getCost(new CalculationContext(baritone)))); for (Movement move : moves) { String[] parts = move.getClass().toString().split("\\."); double cost = move.getCost(); From 1f52f706ede198eb541c7105761304fd94d76ce6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 20 Feb 2019 23:41:29 -0800 Subject: [PATCH 193/682] should fix anticheatcompat off on forge --- 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 9ee059c6..df0921cf 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -109,7 +109,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior { // If we have antiCheatCompatibility on, we're going to use the target value later in onPlayerUpdate() // Also the type has to be MOTION_UPDATE because that is called after JUMP - if (!Baritone.settings().antiCheatCompatibility.get() && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE) { + if (!Baritone.settings().antiCheatCompatibility.get() && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE && !this.force) { this.target = null; } } From 29a9e6e1d1d27bf3bfdc715d756ef9a77e362c1b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 21 Feb 2019 09:45:01 -0800 Subject: [PATCH 194/682] fine, forward alias to thisway --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index edd426a3..83a8df6c 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -385,7 +385,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Started mining blocks of type " + Arrays.toString(blockTypes)); return true; } - if (msg.startsWith("thisway")) { + if (msg.startsWith("thisway") || msg.startsWith("forward")) { try { Goal goal = GoalXZ.fromDirection(ctx.playerFeetAsVec(), ctx.player().rotationYaw, Double.parseDouble(msg.substring(7).trim())); customGoalProcess.setGoal(goal); From eb9f755b54e2d267302404fcaa2bc46c1b640b64 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 21 Feb 2019 10:03:03 -0800 Subject: [PATCH 195/682] disable rendercachedchunks in singleplayer, fixes #331 --- .../baritone/launch/mixins/MixinChunkRenderContainer.java | 2 +- .../java/baritone/launch/mixins/MixinChunkRenderWorker.java | 3 ++- src/launch/java/baritone/launch/mixins/MixinRenderChunk.java | 5 +++-- src/launch/java/baritone/launch/mixins/MixinRenderList.java | 3 ++- .../java/baritone/launch/mixins/MixinVboRenderList.java | 3 ++- 5 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index 511e1c14..0fc81487 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -41,7 +41,7 @@ public class MixinChunkRenderContainer { ) ) private BlockPos getPosition(RenderChunk renderChunkIn) { - if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { + if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { GlStateManager.enableAlpha(); GlStateManager.enableBlend(); GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.get()); diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java index a8247a9b..2bd1521c 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java @@ -20,6 +20,7 @@ package baritone.launch.mixins; import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.utils.IPlayerContext; +import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.chunk.ChunkRenderWorker; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -42,7 +43,7 @@ public abstract class MixinChunkRenderWorker { ) ) private boolean isChunkExisting(ChunkRenderWorker worker, BlockPos pos, World world) { - if (Baritone.settings().renderCachedChunks.get()) { + if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { diff --git a/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java b/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java index 4190ae59..754f523f 100644 --- a/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java +++ b/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java @@ -21,6 +21,7 @@ import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.utils.IPlayerContext; import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.chunk.RenderChunk; import net.minecraft.util.math.BlockPos; import net.minecraft.world.ChunkCache; @@ -46,7 +47,7 @@ public class MixinRenderChunk { if (!chunkCache.isEmpty()) { return false; } - if (Baritone.settings().renderCachedChunks.get()) { + if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { @@ -75,7 +76,7 @@ public class MixinRenderChunk { ) ) private IBlockState getBlockState(ChunkCache chunkCache, BlockPos pos) { - if (Baritone.settings().renderCachedChunks.get()) { + if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { diff --git a/src/launch/java/baritone/launch/mixins/MixinRenderList.java b/src/launch/java/baritone/launch/mixins/MixinRenderList.java index 3d4d8a91..e2f0ae90 100644 --- a/src/launch/java/baritone/launch/mixins/MixinRenderList.java +++ b/src/launch/java/baritone/launch/mixins/MixinRenderList.java @@ -18,6 +18,7 @@ package baritone.launch.mixins; import baritone.Baritone; +import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderList; import org.spongepowered.asm.mixin.Mixin; @@ -37,7 +38,7 @@ public class MixinRenderList { ) ) private void popMatrix() { - if (Baritone.settings().renderCachedChunks.get()) { + if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) { // reset the blend func to normal (not dependent on constant alpha) GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } diff --git a/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java b/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java index 70048c8c..f51d2234 100644 --- a/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java +++ b/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java @@ -18,6 +18,7 @@ package baritone.launch.mixins; import baritone.Baritone; +import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.VboRenderList; import org.spongepowered.asm.mixin.Mixin; @@ -37,7 +38,7 @@ public class MixinVboRenderList { ) ) private void popMatrix() { - if (Baritone.settings().renderCachedChunks.get()) { + if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) { // reset the blend func to normal (not dependent on constant alpha) GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } From 16dcd2f44d70368783aa2eac793517d8194d45f5 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 21 Feb 2019 11:25:03 -0800 Subject: [PATCH 196/682] blocks on top of chests, fixes #299 --- .../java/baritone/process/GetToBlockProcess.java | 16 +++++++++++++++- .../baritone/utils/InputOverrideHandler.java | 15 +++++++++++---- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 7796c029..0eb9f339 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -168,7 +168,13 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } private Goal createGoal(BlockPos pos) { - return walkIntoInsteadOfAdjacent(gettingTo) ? new GoalTwoBlocks(pos) : new GoalGetToBlock(pos); + if (walkIntoInsteadOfAdjacent(gettingTo)) { + return new GoalTwoBlocks(pos); + } + if (blockOnTopMustBeRemoved(gettingTo) && baritone.bsi.get0(pos.up()).isBlockNormalCube()) { + return new GoalBlock(pos.up()); + } + return new GoalGetToBlock(pos); } private boolean rightClick() { @@ -203,4 +209,12 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } return block == Blocks.CRAFTING_TABLE || block == Blocks.FURNACE || block == Blocks.ENDER_CHEST || block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST; } + + private boolean blockOnTopMustBeRemoved(Block block) { + if (!rightClickOnArrival(block)) { // only if we plan to actually open it on arrival + return false; + } + // only these chests; you can open a crafting table or furnace even with a block on top + return block == Blocks.ENDER_CHEST || block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST; + } } diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index f32bdaa4..f5ee0530 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -61,16 +61,23 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri @Override public final Boolean isInputForcedDown(KeyBinding key) { Input input = Input.getInputForBind(key); - if (input == null || !inControl()) { + if (input == null) { return null; } - if (input == Input.CLICK_LEFT) { + if (input == Input.CLICK_LEFT && inControl()) { + // only override left click off when pathing return false; } if (input == Input.CLICK_RIGHT) { - return isInputForcedDown(Input.CLICK_RIGHT); + if (isInputForcedDown(Input.CLICK_RIGHT)) { + // gettoblock and builder can right click even when not pathing; allow them to do so + return true; + } else if (inControl()) { + // but when we are pathing for real, force right click off + return false; + } } - return null; + return null; // dont force any inputs other than left and right click } /** From 2b672998e1ccff6953dfa6d9b1dcd403b4aa3936 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 21 Feb 2019 14:24:23 -0800 Subject: [PATCH 197/682] fix two weird ways of getting stuck --- .../java/baritone/process/BuilderProcess.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index e7c2f65a..9ff8102d 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -249,9 +249,9 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro private static Vec3d[] aabbSideMultipliers(EnumFacing side) { switch (side) { case UP: - return new Vec3d[]{new Vec3d(0.5, 1, 0.5)}; + return new Vec3d[]{new Vec3d(0.5, 1, 0.5), new Vec3d(0.1, 1, 0.5), new Vec3d(0.9, 1, 0.5), new Vec3d(0.5, 1, 0.1), new Vec3d(0.5, 1, 0.9)}; case DOWN: - return new Vec3d[]{new Vec3d(0.5, 0, 0.5)}; + return new Vec3d[]{new Vec3d(0.5, 0, 0.5), new Vec3d(0.1, 0, 0.5), new Vec3d(0.9, 0, 0.5), new Vec3d(0.5, 0, 0.1), new Vec3d(0.5, 0, 0.9)}; case NORTH: case SOUTH: case EAST: @@ -295,6 +295,12 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro BetterBlockPos pos = toBreak.get().getFirst(); baritone.getLookBehavior().updateTarget(rot, true); MovementHelper.switchToBestToolFor(ctx, bcc.get(pos)); + if (ctx.player().isSneaking()) { + // really horrible bug where a block is visible for breaking while sneaking but not otherwise + // so you can't see it, it goes to place something else, sneaks, then the next tick it tries to break + // and is unable since it's unsneaked in the intermediary tick + baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true); + } if (Objects.equals(ctx.objectMouseOver().getBlockPos(), pos) || ctx.playerRotations().isReallyCloseTo(rot)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); } @@ -445,6 +451,11 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro public double heuristic(int x, int y, int z) { return primary.heuristic(x, y, z); } + + @Override + public String toString() { + return "JankyComposite Primary: " + primary + " Fallback: " + fallback; + } } public static class GoalBreak extends GoalGetToBlock { From d32e822057913cdaf68ebb760230a1bdc32406ed Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 22 Feb 2019 12:13:19 -0800 Subject: [PATCH 198/682] settings overhaul --- USAGE.md | 2 +- src/api/java/baritone/api/Settings.java | 14 ++-- .../java/baritone/api/utils/SettingsUtil.java | 55 ++++++++++------ .../utils/ExampleBaritoneControl.java | 65 ++++++++++++------- 4 files changed, 83 insertions(+), 53 deletions(-) diff --git a/USAGE.md b/USAGE.md index 391e5e45..b73f4afb 100644 --- a/USAGE.md +++ b/USAGE.md @@ -21,7 +21,7 @@ Other clients like Kami and Asuna have their own custom things (like `-path`), a `help` for (rudimentary) help. You can see what it says [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java#L53). -To toggle a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `primaryTimeoutMS 250`). It's case insensitive. +To toggle a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `primaryTimeoutMS 250`). It's case insensitive. To reset a setting to its default value, say `acceptableThrowawayItems reset`. To reset all settings, say `reset`. To see all settings that have been modified from their default values, say `modified`. diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 2878e4d6..2879ba78 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -17,6 +17,7 @@ package baritone.api; +import baritone.api.utils.SettingsUtil; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.item.Item; @@ -704,12 +705,6 @@ public final class Settings { */ public final List> allSettings; - public void reset() { - for (Setting setting : allSettings) { - setting.value = setting.defaultValue; - } - } - public final class Setting { public T value; public final T defaultValue; @@ -739,8 +734,13 @@ public final class Settings { return klass; } + @Override public String toString() { - return name + ": " + value; + return SettingsUtil.settingToString(this); + } + + public void reset() { + value = defaultValue; } } diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 07b4cd98..84e9af68 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -27,10 +27,8 @@ import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; +import java.util.*; +import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import java.util.regex.Matcher; @@ -89,22 +87,8 @@ public class SettingsUtil { public static synchronized void save(Settings settings) { try (BufferedWriter out = Files.newBufferedWriter(SETTINGS_PATH)) { - for (Settings.Setting setting : settings.allSettings) { - if (setting.get() == null) { - System.out.println("NULL SETTING?" + setting.getName()); - continue; - } - if (setting.getName().equals("logger")) { - continue; // NO - } - if (setting.value == setting.defaultValue) { - continue; - } - SettingsIO io = map.get(setting.getValueClass()); - if (io == null) { - throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting + " " + setting.getName()); - } - out.write(setting.getName() + " " + io.toString.apply(setting.get()) + "\n"); + for (Settings.Setting setting : modifiedSettings(settings)) { + out.write(settingToString(setting) + "\n"); } } catch (Exception ex) { System.out.println("Exception thrown while saving Baritone settings!"); @@ -112,7 +96,36 @@ public class SettingsUtil { } } - private static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException { + public static List modifiedSettings(Settings settings) { + List modified = new ArrayList<>(); + for (Settings.Setting setting : settings.allSettings) { + if (setting.get() == null) { + System.out.println("NULL SETTING?" + setting.getName()); + continue; + } + if (setting.getName().equals("logger")) { + continue; // NO + } + if (setting.value == setting.defaultValue) { + continue; + } + modified.add(setting); + } + return modified; + } + + public static String settingToString(Settings.Setting setting) throws IllegalStateException { + if (setting.getName().equals("logger")) { + return "logger"; + } + SettingsIO io = map.get(setting.getValueClass()); + if (io == null) { + throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName()); + } + return setting.getName() + " " + io.toString.apply(setting.get()); + } + + public static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException { Settings.Setting setting = settings.byLowerName.get(settingName); if (setting == null) { throw new IllegalStateException("No setting by that name"); diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 83a8df6c..d8650471 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -117,12 +117,33 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } - if (msg.equals("baritone") || msg.equals("settings")) { - for (Settings.Setting setting : Baritone.settings().allSettings) { + if (msg.equals("baritone") || msg.equals("modifiedsettings") || msg.startsWith("settings m") || msg.equals("modified")) { + logDirect("All settings that have been modified from their default values:"); + for (Settings.Setting setting : SettingsUtil.modifiedSettings(Baritone.settings())) { logDirect(setting.toString()); } return true; } + if (msg.startsWith("settings")) { + String rest = msg.substring("settings".length()); + try { + int page = Integer.parseInt(rest.trim()); + int min = page * 10; + int max = Math.min(Baritone.settings().allSettings.size(), (page + 1) * 10); + logDirect("Settings " + min + " to " + (max - 1) + ":"); + for (int i = min; i < max; i++) { + logDirect(Baritone.settings().allSettings.get(i).toString()); + } + } catch (Exception ex) { // NumberFormatException | ArrayIndexOutOfBoundsException and probably some others I'm forgetting lol + ex.printStackTrace(); + logDirect("All settings:"); + for (Settings.Setting setting : Baritone.settings().allSettings) { + logDirect(setting.toString()); + } + logDirect("To get one page of ten settings at a time, do settings "); + } + return true; + } if (msg.equals("") || msg.equals("help") || msg.equals("?")) { for (String line : HELP_MSG.split("\n")) { logDirect(line); @@ -130,31 +151,24 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.contains(" ")) { - String[] data = msg.split(" "); - if (data.length == 2) { - Settings.Setting setting = Baritone.settings().byLowerName.get(data[0]); - if (setting != null) { + String settingName = msg.substring(0, msg.indexOf(' ')); + String settingValue = msg.substring(msg.indexOf(' ') + 1); + Settings.Setting setting = Baritone.settings().byLowerName.get(settingName); + if (setting != null) { + if (settingValue.equals("reset")) { + logDirect("Resetting setting " + settingName + " to default value."); + setting.reset(); + } else { try { - if (setting.value.getClass() == Long.class) { - setting.value = Long.parseLong(data[1]); - } - if (setting.value.getClass() == Integer.class) { - setting.value = Integer.parseInt(data[1]); - } - if (setting.value.getClass() == Double.class) { - setting.value = Double.parseDouble(data[1]); - } - if (setting.value.getClass() == Float.class) { - setting.value = Float.parseFloat(data[1]); - } - } catch (NumberFormatException e) { - logDirect("Unable to parse " + data[1]); + SettingsUtil.parseAndApply(Baritone.settings(), settingName, settingValue); + } catch (Exception ex) { + logDirect("Unable to parse setting"); return true; } - SettingsUtil.save(Baritone.settings()); - logDirect(setting.toString()); - return true; } + SettingsUtil.save(Baritone.settings()); + logDirect(setting.toString()); + return true; } } if (Baritone.settings().byLowerName.containsKey(msg)) { @@ -278,7 +292,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("reset")) { - Baritone.settings().reset(); + for (Settings.Setting setting : Baritone.settings().allSettings) { + setting.reset(); + } + SettingsUtil.save(Baritone.settings()); logDirect("Baritone settings reset"); return true; } From e63b2f1bf1347d4639f53d0fef1bc6751802c23f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 22 Feb 2019 13:58:03 -0800 Subject: [PATCH 199/682] unused arg --- src/main/java/baritone/pathing/path/PathExecutor.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index d4897eec..4bc86cd4 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -391,7 +391,7 @@ public class PathExecutor implements IPathExecutor, Helper { if (current instanceof MovementTraverse && pathPosition < path.length() - 3) { IMovement next = path.movements().get(pathPosition + 1); if (next instanceof MovementAscend && sprintableAscend(ctx, (MovementTraverse) current, (MovementAscend) next, path.movements().get(pathPosition + 2))) { - if (skipNow(ctx, current, next)) { + if (skipNow(ctx, current)) { logDebug("Skipping traverse to straight ascend"); pathPosition++; onChangeInPathPosition(); @@ -513,7 +513,7 @@ public class PathExecutor implements IPathExecutor, Helper { movement.getDest().add(flatDir.getX() * (i - pathPosition), 0, flatDir.getZ() * (i - pathPosition))); } - private static boolean skipNow(IPlayerContext ctx, IMovement current, IMovement next) { + private static boolean skipNow(IPlayerContext ctx, IMovement current) { double offTarget = Math.abs(current.getDirection().getX() * (current.getSrc().z + 0.5D - ctx.player().posZ)) + Math.abs(current.getDirection().getZ() * (current.getSrc().x + 0.5D - ctx.player().posX)); if (offTarget > 0.1) { return false; From 3b46dbd6a1be8d584c706afabe704f0a1f431a5b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 22 Feb 2019 14:05:29 -0800 Subject: [PATCH 200/682] appease codacy --- .../baritone/pathing/path/PathExecutor.java | 51 +++++++++---------- .../baritone/process/GetToBlockProcess.java | 7 ++- 2 files changed, 28 insertions(+), 30 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 4bc86cd4..b025f689 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -106,33 +106,31 @@ public class PathExecutor implements IPathExecutor, Helper { } BetterBlockPos whereShouldIBe = path.positions().get(pathPosition); BetterBlockPos whereAmI = ctx.playerFeet(); - if (!whereShouldIBe.equals(whereAmI)) { - if (!Blocks.AIR.equals(BlockStateInterface.getBlock(ctx, whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip - for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks - if (whereAmI.equals(path.positions().get(i))) { - logDebug("Skipping back " + (pathPosition - i) + " steps, to " + i); - int previousPos = pathPosition; - pathPosition = Math.max(i - 1, 0); // previous step might not actually be done - for (int j = pathPosition; j <= previousPos; j++) { - path.movements().get(j).reset(); - } - onChangeInPathPosition(); - onTick(); - return false; + if (!whereShouldIBe.equals(whereAmI) && !Blocks.AIR.equals(BlockStateInterface.getBlock(ctx, whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip + for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks + if (whereAmI.equals(path.positions().get(i))) { + logDebug("Skipping back " + (pathPosition - i) + " steps, to " + i); + int previousPos = pathPosition; + pathPosition = Math.max(i - 1, 0); // previous step might not actually be done + for (int j = pathPosition; j <= previousPos; j++) { + path.movements().get(j).reset(); } + onChangeInPathPosition(); + onTick(); + return false; } - for (int i = pathPosition + 3; i < path.length(); i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing) - // also don't check pathPosition+2 because reasons - if (whereAmI.equals(path.positions().get(i))) { - if (i - pathPosition > 2) { - logDebug("Skipping forward " + (i - pathPosition) + " steps, to " + i); - } - //System.out.println("Double skip sundae"); - pathPosition = i - 1; - onChangeInPathPosition(); - onTick(); - return false; + } + for (int i = pathPosition + 3; i < path.length(); i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing) + // also don't check pathPosition+2 because reasons + if (whereAmI.equals(path.positions().get(i))) { + if (i - pathPosition > 2) { + logDebug("Skipping forward " + (i - pathPosition) + " steps, to " + i); } + //System.out.println("Double skip sundae"); + pathPosition = i - 1; + onChangeInPathPosition(); + onTick(); + return false; } } } @@ -561,10 +559,7 @@ public class PathExecutor implements IPathExecutor, Helper { if (MovementHelper.avoidWalkingInto(ctx.world().getBlockState(current.getSrc().up(3)).getBlock())) { return false; } - if (MovementHelper.avoidWalkingInto(ctx.world().getBlockState(next.getDest().up(2)).getBlock())) { - return false; - } - return true; + return !MovementHelper.avoidWalkingInto(ctx.world().getBlockState(next.getDest().up(2)).getBlock()); // codacy smh my head } private static boolean canSprintFromDescendInto(IPlayerContext ctx, IMovement current, IMovement next) { diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 0eb9f339..cb80926b 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -131,8 +131,11 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } } } - if (true) { - break; // codacy gets mad if i just end on a break LOL + // i can't do break; (codacy gets mad), and i can't do if(true){break}; (codacy gets mad) + // so i will do this + switch (newBlacklist.size()) { + default: + break outer; } } logDebug("Blacklisting unreachable locations " + newBlacklist); From c808d5a42dd8b07d569eef82c6b438c783d69b47 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 22 Feb 2019 18:12:04 -0600 Subject: [PATCH 201/682] Small build.gradle cleanup and README update --- README.md | 12 ++- build.gradle | 266 +++++++++++++++++++++++++-------------------------- 2 files changed, 141 insertions(+), 137 deletions(-) diff --git a/README.md b/README.md index eb96e9e4..1039f0f6 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,8 @@ Have committed at least once a day for the last 6 months =D 🦀 1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2 +# Getting Started + Here are some links to help to get started: - [Features](FEATURES.md) @@ -46,11 +48,15 @@ Here are some links to help to get started: - [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#allowBreak) -# Chat control - - [Baritone chat control usage](USAGE.md) -# API example +# API + +The API is heavily documented, you can find the Javadocs for the latest release [here](https://baritone.leijurv.com/). +Please note that usage of anything located outside of the ``baritone.api`` package is not supported by the API release +jar. + +Below is an example of basic usage for changing some settings, and then pathing to a X/Z goal. ``` BaritoneAPI.getSettings().allowSprint.value = true; diff --git a/build.gradle b/build.gradle index 996a8e0f..dabc0367 100755 --- a/build.gradle +++ b/build.gradle @@ -1,134 +1,132 @@ -/* - * 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 . - */ - -group 'baritone' -version '1.1.6' - -buildscript { - repositories { - maven { - name = 'forge' - url = 'http://files.minecraftforge.net/maven' - } - maven { - name = 'SpongePowered' - url = 'http://repo.spongepowered.org/maven' - } - jcenter() - } - - dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' - classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT' - } -} - - -import baritone.gradle.task.CreateDistTask -import baritone.gradle.task.ProguardTask - -apply plugin: 'java' -apply plugin: 'net.minecraftforge.gradle.tweaker-client' -apply plugin: 'org.spongepowered.mixin' - -sourceCompatibility = targetCompatibility = '1.8' -compileJava { - sourceCompatibility = targetCompatibility = '1.8' - options.encoding = "UTF-8" // allow emoji in comments :^) -} - -sourceSets { - launch { - compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output - } -} - -minecraft { - version = '1.12.2' - mappings = 'stable_39' - tweakClass = 'baritone.launch.BaritoneTweaker' - runDir = 'run' - - // The sources jar should use SRG names not MCP to ensure compatibility with all mappings - makeObfSourceJar = true -} - -repositories { - mavenCentral() - - maven { - name = 'spongepowered-repo' - url = 'http://repo.spongepowered.org/maven/' - } - - maven { - name = 'impactdevelopment-repo' - url = 'https://impactdevelopment.github.io/maven/' - } -} - -dependencies { - runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.2') - runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') { - // Mixin includes a lot of dependencies that are too up-to-date - exclude module: 'launchwrapper' - exclude module: 'guava' - exclude module: 'gson' - exclude module: 'commons-io' - exclude module: 'log4j-core' - } - testImplementation 'junit:junit:4.12' -} - -mixin { - defaultObfuscationEnv searge - add sourceSets.launch, 'mixins.baritone.refmap.json' -} - -javadoc { - options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error - options.linkSource true - options.encoding "UTF-8" // allow emoji in comments :^) - source += sourceSets.api.allJava - classpath += sourceSets.api.compileClasspath -} - -jar { - from sourceSets.launch.output, sourceSets.api.output - preserveFileTimestamps = false - reproducibleFileOrder = true -} - -jar { - manifest { - attributes( - 'MixinConfigs': 'mixins.baritone.json', - - 'Implementation-Title': 'Baritone', - 'Implementation-Version': version - ) - } -} - -task proguard(type: ProguardTask) { - url 'https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip' - extract 'proguard6.0.3/lib/proguard.jar' -} - -task createDist(type: CreateDistTask, dependsOn: proguard) - -build.finalizedBy(createDist) +/* + * 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 . + */ + +group 'baritone' +version '1.1.6' + +buildscript { + repositories { + maven { + name = 'forge' + url = 'http://files.minecraftforge.net/maven' + } + maven { + name = 'SpongePowered' + url = 'http://repo.spongepowered.org/maven' + } + jcenter() + } + + dependencies { + classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' + classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT' + } +} + + +import baritone.gradle.task.CreateDistTask +import baritone.gradle.task.ProguardTask + +apply plugin: 'java' +apply plugin: 'net.minecraftforge.gradle.tweaker-client' +apply plugin: 'org.spongepowered.mixin' + +sourceCompatibility = targetCompatibility = '1.8' +compileJava { + sourceCompatibility = targetCompatibility = '1.8' + options.encoding = "UTF-8" // allow emoji in comments :^) +} + +sourceSets { + launch { + compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output + } +} + +minecraft { + version = '1.12.2' + mappings = 'stable_39' + tweakClass = 'baritone.launch.BaritoneTweaker' + runDir = 'run' + + // The sources jar should use SRG names not MCP to ensure compatibility with all mappings + makeObfSourceJar = true +} + +repositories { + mavenCentral() + + maven { + name = 'spongepowered-repo' + url = 'http://repo.spongepowered.org/maven/' + } + + maven { + name = 'impactdevelopment-repo' + url = 'https://impactdevelopment.github.io/maven/' + } +} + +dependencies { + runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.2') + runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') { + // Mixin includes a lot of dependencies that are too up-to-date + exclude module: 'launchwrapper' + exclude module: 'guava' + exclude module: 'gson' + exclude module: 'commons-io' + exclude module: 'log4j-core' + } + testImplementation 'junit:junit:4.12' +} + +mixin { + defaultObfuscationEnv searge + add sourceSets.launch, 'mixins.baritone.refmap.json' +} + +javadoc { + options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error + options.linkSource true + options.encoding "UTF-8" // allow emoji in comments :^) + source += sourceSets.api.allJava + classpath += sourceSets.api.compileClasspath +} + +jar { + from sourceSets.launch.output, sourceSets.api.output + preserveFileTimestamps = false + reproducibleFileOrder = true + + manifest { + attributes( + 'MixinConfigs': 'mixins.baritone.json', + + 'Implementation-Title': 'Baritone', + 'Implementation-Version': version + ) + } +} + +task proguard(type: ProguardTask) { + url 'https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip' + extract 'proguard6.0.3/lib/proguard.jar' +} + +task createDist(type: CreateDistTask, dependsOn: proguard) + +build.finalizedBy(createDist) From 5427911da3f37115826707f2c5212dad47a2df78 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 22 Feb 2019 23:29:08 -0800 Subject: [PATCH 202/682] only api in javadoc i guess --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index dabc0367..b0173f5d 100755 --- a/build.gradle +++ b/build.gradle @@ -103,7 +103,7 @@ javadoc { options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error options.linkSource true options.encoding "UTF-8" // allow emoji in comments :^) - source += sourceSets.api.allJava + source = sourceSets.api.allJava classpath += sourceSets.api.compileClasspath } From cc4335e48e39893b7d6327363e77619b7830d75a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 22 Feb 2019 23:32:23 -0800 Subject: [PATCH 203/682] better links --- README.md | 2 +- USAGE.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1039f0f6..8090c904 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Here are some links to help to get started: - [Javadocs](https://baritone.leijurv.com/) -- [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#allowBreak) +- [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#field.detail) - [Baritone chat control usage](USAGE.md) diff --git a/USAGE.md b/USAGE.md index b73f4afb..de5b836d 100644 --- a/USAGE.md +++ b/USAGE.md @@ -43,7 +43,7 @@ Some common examples: For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java). -All the settings and documentation are here. If you find HTML easier to read than Javadoc, you can look here. +All the settings and documentation are here. If you find HTML easier to read than Javadoc, you can look here. There are about a hundred settings, but here are some fun / interesting / important ones that you might want to look at changing in normal usage of Baritone. The documentation for each can be found at the above links. - `allowBreak` From e8e00e8dfb514bd4c1e34184ec66ded88f317d90 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 23 Feb 2019 12:27:24 -0600 Subject: [PATCH 204/682] CRLF -> LF It was inconsistent across the board --- gradle/wrapper/gradle-wrapper.properties | 12 +- gradlew.bat | 168 +++---- settings.gradle | 38 +- src/main/java/baritone/Baritone.java | 422 +++++++++--------- src/main/java/baritone/utils/Helper.java | 144 +++--- .../baritone/utils/InputOverrideHandler.java | 280 ++++++------ 6 files changed, 532 insertions(+), 532 deletions(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 59006a9e..599a02b7 100755 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Tue Jul 31 21:56:56 PDT 2018 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip +#Tue Jul 31 21:56:56 PDT 2018 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip diff --git a/gradlew.bat b/gradlew.bat index e95643d6..f9553162 100755 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,84 +1,84 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle index baa9dfc9..567f8411 100755 --- a/settings.gradle +++ b/settings.gradle @@ -1,19 +1,19 @@ -/* - * 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 . - */ - -rootProject.name = 'baritone' - +/* + * 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 . + */ + +rootProject.name = 'baritone' + diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 2eb69cba..51a6ff69 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -1,211 +1,211 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone; - -import baritone.api.BaritoneAPI; -import baritone.api.IBaritone; -import baritone.api.Settings; -import baritone.api.event.listener.IEventBus; -import baritone.api.utils.IPlayerContext; -import baritone.behavior.*; -import baritone.cache.WorldProvider; -import baritone.event.GameEventHandler; -import baritone.process.CustomGoalProcess; -import baritone.process.FollowProcess; -import baritone.process.GetToBlockProcess; -import baritone.process.MineProcess; -import baritone.utils.*; -import baritone.utils.player.PrimaryPlayerContext; -import net.minecraft.client.Minecraft; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Executor; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author Brady - * @since 7/31/2018 - */ -public class Baritone implements IBaritone { - - private static ThreadPoolExecutor threadPool; - private static File dir; - - static { - threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); - - dir = new File(Minecraft.getMinecraft().gameDir, "baritone"); - if (!Files.exists(dir.toPath())) { - try { - Files.createDirectories(dir.toPath()); - } catch (IOException ignored) {} - } - } - - /** - * Whether or not {@link Baritone#init()} has been called yet - */ - private boolean initialized; - - private GameEventHandler gameEventHandler; - - private List behaviors; - private PathingBehavior pathingBehavior; - private LookBehavior lookBehavior; - private MemoryBehavior memoryBehavior; - private InputOverrideHandler inputOverrideHandler; - - private FollowProcess followProcess; - private MineProcess mineProcess; - private GetToBlockProcess getToBlockProcess; - private CustomGoalProcess customGoalProcess; - - private PathingControlManager pathingControlManager; - - private IPlayerContext playerContext; - private WorldProvider worldProvider; - - public BlockStateInterface bsi; - - Baritone() { - this.gameEventHandler = new GameEventHandler(this); - } - - @Override - public synchronized void init() { - if (initialized) { - return; - } - - // Define this before behaviors try and get it, or else it will be null and the builds will fail! - this.playerContext = PrimaryPlayerContext.INSTANCE; - - this.behaviors = new ArrayList<>(); - { - // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist - pathingBehavior = new PathingBehavior(this); - lookBehavior = new LookBehavior(this); - memoryBehavior = new MemoryBehavior(this); - new InventoryBehavior(this); - inputOverrideHandler = new InputOverrideHandler(this); - new ExampleBaritoneControl(this); - } - - this.pathingControlManager = new PathingControlManager(this); - { - followProcess = new FollowProcess(this); - mineProcess = new MineProcess(this); - customGoalProcess = new CustomGoalProcess(this); // very high iq - getToBlockProcess = new GetToBlockProcess(this); - } - - this.worldProvider = new WorldProvider(); - - if (BaritoneAutoTest.ENABLE_AUTO_TEST) { - this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE); - } - - this.initialized = true; - } - - @Override - public PathingControlManager getPathingControlManager() { - return this.pathingControlManager; - } - - public List getBehaviors() { - return this.behaviors; - } - - public void registerBehavior(Behavior behavior) { - this.behaviors.add(behavior); - this.gameEventHandler.registerEventListener(behavior); - } - - @Override - public InputOverrideHandler getInputOverrideHandler() { - return this.inputOverrideHandler; - } - - @Override - public CustomGoalProcess getCustomGoalProcess() { // Iffy - return this.customGoalProcess; - } - - @Override - public GetToBlockProcess getGetToBlockProcess() { // Iffy - return this.getToBlockProcess; - } - - @Override - public IPlayerContext getPlayerContext() { - return this.playerContext; - } - - public MemoryBehavior getMemoryBehavior() { - return this.memoryBehavior; - } - - @Override - public FollowProcess getFollowProcess() { - return this.followProcess; - } - - @Override - public LookBehavior getLookBehavior() { - return this.lookBehavior; - } - - @Override - public MineProcess getMineProcess() { - return this.mineProcess; - } - - @Override - public PathingBehavior getPathingBehavior() { - return this.pathingBehavior; - } - - @Override - public WorldProvider getWorldProvider() { - return this.worldProvider; - } - - @Override - public IEventBus getGameEventHandler() { - return this.gameEventHandler; - } - - public static Settings settings() { - return BaritoneAPI.getSettings(); - } - - public static File getDir() { - return dir; - } - - public static Executor getExecutor() { - return threadPool; - } -} +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone; + +import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; +import baritone.api.Settings; +import baritone.api.event.listener.IEventBus; +import baritone.api.utils.IPlayerContext; +import baritone.behavior.*; +import baritone.cache.WorldProvider; +import baritone.event.GameEventHandler; +import baritone.process.CustomGoalProcess; +import baritone.process.FollowProcess; +import baritone.process.GetToBlockProcess; +import baritone.process.MineProcess; +import baritone.utils.*; +import baritone.utils.player.PrimaryPlayerContext; +import net.minecraft.client.Minecraft; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Executor; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author Brady + * @since 7/31/2018 + */ +public class Baritone implements IBaritone { + + private static ThreadPoolExecutor threadPool; + private static File dir; + + static { + threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); + + dir = new File(Minecraft.getMinecraft().gameDir, "baritone"); + if (!Files.exists(dir.toPath())) { + try { + Files.createDirectories(dir.toPath()); + } catch (IOException ignored) {} + } + } + + /** + * Whether or not {@link Baritone#init()} has been called yet + */ + private boolean initialized; + + private GameEventHandler gameEventHandler; + + private List behaviors; + private PathingBehavior pathingBehavior; + private LookBehavior lookBehavior; + private MemoryBehavior memoryBehavior; + private InputOverrideHandler inputOverrideHandler; + + private FollowProcess followProcess; + private MineProcess mineProcess; + private GetToBlockProcess getToBlockProcess; + private CustomGoalProcess customGoalProcess; + + private PathingControlManager pathingControlManager; + + private IPlayerContext playerContext; + private WorldProvider worldProvider; + + public BlockStateInterface bsi; + + Baritone() { + this.gameEventHandler = new GameEventHandler(this); + } + + @Override + public synchronized void init() { + if (initialized) { + return; + } + + // Define this before behaviors try and get it, or else it will be null and the builds will fail! + this.playerContext = PrimaryPlayerContext.INSTANCE; + + this.behaviors = new ArrayList<>(); + { + // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist + pathingBehavior = new PathingBehavior(this); + lookBehavior = new LookBehavior(this); + memoryBehavior = new MemoryBehavior(this); + new InventoryBehavior(this); + inputOverrideHandler = new InputOverrideHandler(this); + new ExampleBaritoneControl(this); + } + + this.pathingControlManager = new PathingControlManager(this); + { + followProcess = new FollowProcess(this); + mineProcess = new MineProcess(this); + customGoalProcess = new CustomGoalProcess(this); // very high iq + getToBlockProcess = new GetToBlockProcess(this); + } + + this.worldProvider = new WorldProvider(); + + if (BaritoneAutoTest.ENABLE_AUTO_TEST) { + this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE); + } + + this.initialized = true; + } + + @Override + public PathingControlManager getPathingControlManager() { + return this.pathingControlManager; + } + + public List getBehaviors() { + return this.behaviors; + } + + public void registerBehavior(Behavior behavior) { + this.behaviors.add(behavior); + this.gameEventHandler.registerEventListener(behavior); + } + + @Override + public InputOverrideHandler getInputOverrideHandler() { + return this.inputOverrideHandler; + } + + @Override + public CustomGoalProcess getCustomGoalProcess() { // Iffy + return this.customGoalProcess; + } + + @Override + public GetToBlockProcess getGetToBlockProcess() { // Iffy + return this.getToBlockProcess; + } + + @Override + public IPlayerContext getPlayerContext() { + return this.playerContext; + } + + public MemoryBehavior getMemoryBehavior() { + return this.memoryBehavior; + } + + @Override + public FollowProcess getFollowProcess() { + return this.followProcess; + } + + @Override + public LookBehavior getLookBehavior() { + return this.lookBehavior; + } + + @Override + public MineProcess getMineProcess() { + return this.mineProcess; + } + + @Override + public PathingBehavior getPathingBehavior() { + return this.pathingBehavior; + } + + @Override + public WorldProvider getWorldProvider() { + return this.worldProvider; + } + + @Override + public IEventBus getGameEventHandler() { + return this.gameEventHandler; + } + + public static Settings settings() { + return BaritoneAPI.getSettings(); + } + + public static File getDir() { + return dir; + } + + public static Executor getExecutor() { + return threadPool; + } +} diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index 9ee6ed59..f85f240c 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -1,72 +1,72 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.utils; - -import baritone.Baritone; -import net.minecraft.client.Minecraft; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.util.text.TextFormatting; - -/** - * @author Brady - * @since 8/1/2018 - */ -public interface Helper { - - /** - * Instance of {@link Helper}. Used for static-context reference. - */ - Helper HELPER = new Helper() {}; - - ITextComponent MESSAGE_PREFIX = new TextComponentString(String.format( - "%s[%sBaritone%s]%s", - TextFormatting.DARK_PURPLE, - TextFormatting.LIGHT_PURPLE, - TextFormatting.DARK_PURPLE, - TextFormatting.GRAY - )); - - Minecraft mc = Minecraft.getMinecraft(); - - /** - * Send a message to chat only if chatDebug is on - * - * @param message The message to display in chat - */ - default void logDebug(String message) { - if (!Baritone.settings().chatDebug.get()) { - //System.out.println("Suppressed debug message:"); - //System.out.println(message); - return; - } - logDirect(message); - } - - /** - * Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command) - * - * @param message The message to display in chat - */ - default void logDirect(String message) { - ITextComponent component = MESSAGE_PREFIX.createCopy(); - component.getStyle().setColor(TextFormatting.GRAY); - component.appendSibling(new TextComponentString(" " + message)); - Minecraft.getMinecraft().addScheduledTask(() -> Baritone.settings().logger.get().accept(component)); - } -} +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import baritone.Baritone; +import net.minecraft.client.Minecraft; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.TextFormatting; + +/** + * @author Brady + * @since 8/1/2018 + */ +public interface Helper { + + /** + * Instance of {@link Helper}. Used for static-context reference. + */ + Helper HELPER = new Helper() {}; + + ITextComponent MESSAGE_PREFIX = new TextComponentString(String.format( + "%s[%sBaritone%s]%s", + TextFormatting.DARK_PURPLE, + TextFormatting.LIGHT_PURPLE, + TextFormatting.DARK_PURPLE, + TextFormatting.GRAY + )); + + Minecraft mc = Minecraft.getMinecraft(); + + /** + * Send a message to chat only if chatDebug is on + * + * @param message The message to display in chat + */ + default void logDebug(String message) { + if (!Baritone.settings().chatDebug.get()) { + //System.out.println("Suppressed debug message:"); + //System.out.println(message); + return; + } + logDirect(message); + } + + /** + * Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command) + * + * @param message The message to display in chat + */ + default void logDirect(String message) { + ITextComponent component = MESSAGE_PREFIX.createCopy(); + component.getStyle().setColor(TextFormatting.GRAY); + component.appendSibling(new TextComponentString(" " + message)); + Minecraft.getMinecraft().addScheduledTask(() -> Baritone.settings().logger.get().accept(component)); + } +} diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index f5ee0530..6b0a96e7 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -1,140 +1,140 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.utils; - -import baritone.Baritone; -import baritone.api.BaritoneAPI; -import baritone.api.event.events.TickEvent; -import baritone.api.utils.IInputOverrideHandler; -import baritone.api.utils.input.Input; -import baritone.behavior.Behavior; -import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.KeyBinding; -import net.minecraft.util.MovementInputFromOptions; - -import java.util.HashMap; -import java.util.Map; - -/** - * An interface with the game's control system allowing the ability to - * force down certain controls, having the same effect as if we were actually - * physically forcing down the assigned key. - * - * @author Brady - * @since 7/31/2018 - */ -public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler { - - /** - * Maps inputs to whether or not we are forcing their state down. - */ - private final Map inputForceStateMap = new HashMap<>(); - - private final BlockBreakHelper blockBreakHelper; - - public InputOverrideHandler(Baritone baritone) { - super(baritone); - this.blockBreakHelper = new BlockBreakHelper(baritone.getPlayerContext()); - } - - /** - * Returns whether or not we are forcing down the specified {@link KeyBinding}. - * - * @param key The KeyBinding object - * @return Whether or not it is being forced down - */ - @Override - public final Boolean isInputForcedDown(KeyBinding key) { - Input input = Input.getInputForBind(key); - if (input == null) { - return null; - } - if (input == Input.CLICK_LEFT && inControl()) { - // only override left click off when pathing - return false; - } - if (input == Input.CLICK_RIGHT) { - if (isInputForcedDown(Input.CLICK_RIGHT)) { - // gettoblock and builder can right click even when not pathing; allow them to do so - return true; - } else if (inControl()) { - // but when we are pathing for real, force right click off - return false; - } - } - return null; // dont force any inputs other than left and right click - } - - /** - * Returns whether or not we are forcing down the specified {@link Input}. - * - * @param input The input - * @return Whether or not it is being forced down - */ - @Override - public final boolean isInputForcedDown(Input input) { - return input == null ? false : this.inputForceStateMap.getOrDefault(input, false); - } - - /** - * Sets whether or not the specified {@link Input} is being forced down. - * - * @param input The {@link Input} - * @param forced Whether or not the state is being forced - */ - @Override - public final void setInputForceState(Input input, boolean forced) { - this.inputForceStateMap.put(input, forced); - } - - /** - * Clears the override state for all keys - */ - @Override - public final void clearAllKeys() { - this.inputForceStateMap.clear(); - } - - @Override - public final void onTick(TickEvent event) { - if (event.getType() == TickEvent.Type.OUT) { - return; - } - blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT)); - - if (inControl()) { - if (ctx.player().movementInput.getClass() != PlayerMovementInput.class) { - ctx.player().movementInput = new PlayerMovementInput(this); - } - } 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); - } - } - // only set it if it was previously incorrect - // gotta do it this way, or else it constantly thinks you're beginning a double tap W sprint lol - } - - private boolean inControl() { - return baritone.getPathingBehavior().isPathing() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone(); - } - - public BlockBreakHelper getBlockBreakHelper() { - return blockBreakHelper; - } -} +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.event.events.TickEvent; +import baritone.api.utils.IInputOverrideHandler; +import baritone.api.utils.input.Input; +import baritone.behavior.Behavior; +import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.KeyBinding; +import net.minecraft.util.MovementInputFromOptions; + +import java.util.HashMap; +import java.util.Map; + +/** + * An interface with the game's control system allowing the ability to + * force down certain controls, having the same effect as if we were actually + * physically forcing down the assigned key. + * + * @author Brady + * @since 7/31/2018 + */ +public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler { + + /** + * Maps inputs to whether or not we are forcing their state down. + */ + private final Map inputForceStateMap = new HashMap<>(); + + private final BlockBreakHelper blockBreakHelper; + + public InputOverrideHandler(Baritone baritone) { + super(baritone); + this.blockBreakHelper = new BlockBreakHelper(baritone.getPlayerContext()); + } + + /** + * Returns whether or not we are forcing down the specified {@link KeyBinding}. + * + * @param key The KeyBinding object + * @return Whether or not it is being forced down + */ + @Override + public final Boolean isInputForcedDown(KeyBinding key) { + Input input = Input.getInputForBind(key); + if (input == null) { + return null; + } + if (input == Input.CLICK_LEFT && inControl()) { + // only override left click off when pathing + return false; + } + if (input == Input.CLICK_RIGHT) { + if (isInputForcedDown(Input.CLICK_RIGHT)) { + // gettoblock and builder can right click even when not pathing; allow them to do so + return true; + } else if (inControl()) { + // but when we are pathing for real, force right click off + return false; + } + } + return null; // dont force any inputs other than left and right click + } + + /** + * Returns whether or not we are forcing down the specified {@link Input}. + * + * @param input The input + * @return Whether or not it is being forced down + */ + @Override + public final boolean isInputForcedDown(Input input) { + return input == null ? false : this.inputForceStateMap.getOrDefault(input, false); + } + + /** + * Sets whether or not the specified {@link Input} is being forced down. + * + * @param input The {@link Input} + * @param forced Whether or not the state is being forced + */ + @Override + public final void setInputForceState(Input input, boolean forced) { + this.inputForceStateMap.put(input, forced); + } + + /** + * Clears the override state for all keys + */ + @Override + public final void clearAllKeys() { + this.inputForceStateMap.clear(); + } + + @Override + public final void onTick(TickEvent event) { + if (event.getType() == TickEvent.Type.OUT) { + return; + } + blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT)); + + if (inControl()) { + if (ctx.player().movementInput.getClass() != PlayerMovementInput.class) { + ctx.player().movementInput = new PlayerMovementInput(this); + } + } 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); + } + } + // only set it if it was previously incorrect + // gotta do it this way, or else it constantly thinks you're beginning a double tap W sprint lol + } + + private boolean inControl() { + return baritone.getPathingBehavior().isPathing() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone(); + } + + public BlockBreakHelper getBlockBreakHelper() { + return blockBreakHelper; + } +} From 0bce801a3f97821d9a40b738823d121173dca649 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 23 Feb 2019 14:32:10 -0600 Subject: [PATCH 205/682] Minor javadoc changes --- src/api/java/baritone/api/BaritoneAPI.java | 4 +- src/api/java/baritone/api/IBaritone.java | 84 ++++++++++++------- .../java/baritone/api/IBaritoneProvider.java | 7 +- src/api/java/baritone/api/Settings.java | 2 +- .../java/baritone/api/behavior/IBehavior.java | 5 ++ 5 files changed, 67 insertions(+), 35 deletions(-) diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index c1227830..4ea6ef3e 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -23,9 +23,7 @@ import java.util.Iterator; import java.util.ServiceLoader; /** - * API exposure for various things implemented in Baritone. - *

- * W.I.P + * Exposes the {@link IBaritoneProvider} instance and the {@link Settings} instance for API usage. * * @author Brady * @since 9/23/2018 diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index 21157eb1..e88f600e 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -22,10 +22,7 @@ import baritone.api.behavior.IPathingBehavior; import baritone.api.cache.IWorldProvider; import baritone.api.event.listener.IEventBus; import baritone.api.pathing.calc.IPathingControlManager; -import baritone.api.process.ICustomGoalProcess; -import baritone.api.process.IFollowProcess; -import baritone.api.process.IGetToBlockProcess; -import baritone.api.process.IMineProcess; +import baritone.api.process.*; import baritone.api.utils.IInputOverrideHandler; import baritone.api.utils.IPlayerContext; @@ -36,22 +33,13 @@ import baritone.api.utils.IPlayerContext; public interface IBaritone { /** - * @return The {@link IFollowProcess} instance - * @see IFollowProcess + * Call as soon as Minecraft is ready, initializes all of the processes, behaviors, etc. This will + * only effectively be ran once, any additional calls are redundant because the initialization state + * is saved. + *

+ * Or whenever your overeager utility client wants. */ - IFollowProcess getFollowProcess(); - - /** - * @return The {@link ILookBehavior} instance - * @see ILookBehavior - */ - ILookBehavior getLookBehavior(); - - /** - * @return The {@link IMineProcess} instance - * @see IMineProcess - */ - IMineProcess getMineProcess(); + void init(); /** * @return The {@link IPathingBehavior} instance @@ -59,28 +47,66 @@ public interface IBaritone { */ IPathingBehavior getPathingBehavior(); + /** + * @return The {@link ILookBehavior} instance + * @see ILookBehavior + */ + ILookBehavior getLookBehavior(); + + /** + * @return The {@link IFollowProcess} instance + * @see IFollowProcess + */ + IFollowProcess getFollowProcess(); + + /** + * @return The {@link IMineProcess} instance + * @see IMineProcess + */ + IMineProcess getMineProcess(); + + /** + * @return The {@link ICustomGoalProcess} instance + * @see ICustomGoalProcess + */ + ICustomGoalProcess getCustomGoalProcess(); + + /** + * @return The {@link IGetToBlockProcess} instance + * @see IGetToBlockProcess + */ + IGetToBlockProcess getGetToBlockProcess(); + /** * @return The {@link IWorldProvider} instance * @see IWorldProvider */ IWorldProvider getWorldProvider(); + /** + * Returns the {@link IPathingControlManager} for this {@link IBaritone} instance, which is responsible + * for managing the {@link IBaritoneProcess}es which control the {@link IPathingBehavior} state. + * + * @return The {@link IPathingControlManager} instance + * @see IPathingControlManager + */ IPathingControlManager getPathingControlManager(); + /** + * @return The {@link IInputOverrideHandler} instance + * @see IInputOverrideHandler + */ IInputOverrideHandler getInputOverrideHandler(); - ICustomGoalProcess getCustomGoalProcess(); - - IGetToBlockProcess getGetToBlockProcess(); - + /** + * @return The {@link IPlayerContext} instance + * @see IPlayerContext + */ IPlayerContext getPlayerContext(); - IEventBus getGameEventHandler(); - /** - * Call as soon as Minecraft is ready. - *

- * Or whenever your overeager utility client wants. + * @return The {@link IEventBus} instance + * @see IEventBus */ - void init(); + IEventBus getGameEventHandler(); } diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index d17e8e00..34a3aa21 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -23,7 +23,9 @@ import net.minecraft.client.entity.EntityPlayerSP; import java.util.List; /** - * @author Leijurv + * Provides the present {@link IBaritone} instances + * + * @author leijurv */ public interface IBaritoneProvider { @@ -47,7 +49,8 @@ public interface IBaritoneProvider { /** * Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. This will likely be - * replaced with {@code #getBaritoneForUser(IBaritoneUser)} when {@code bot-system} is merged. + * replaced with or be overloaded in addition to {@code #getBaritoneForUser(IBaritoneUser)} when + * {@code bot-system} is merged into {@code master}. * * @param player The player * @return The {@link IBaritone} instance. diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 2879ba78..2d67dbe3 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -30,7 +30,7 @@ import java.util.List; import java.util.function.Consumer; /** - * Baritone's settings + * Baritone's settings. Settings apply to all Baritone instances. * * @author leijurv */ diff --git a/src/api/java/baritone/api/behavior/IBehavior.java b/src/api/java/baritone/api/behavior/IBehavior.java index 248148e7..fbef5258 100644 --- a/src/api/java/baritone/api/behavior/IBehavior.java +++ b/src/api/java/baritone/api/behavior/IBehavior.java @@ -18,8 +18,13 @@ package baritone.api.behavior; import baritone.api.event.listener.AbstractGameEventListener; +import baritone.api.event.listener.IGameEventListener; /** + * A behavior is simply a type that is able to listen to events. + * + * @see IGameEventListener + * * @author Brady * @since 9/23/2018 */ From 73ec110b22216c3d877887dd2122c323b547443f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 23 Feb 2019 14:03:47 -0800 Subject: [PATCH 206/682] not every player is a baritone --- .../java/baritone/api/IBaritoneProvider.java | 2 +- .../launch/mixins/MixinEntityLivingBase.java | 12 ++++-- .../launch/mixins/MixinEntityPlayerSP.java | 38 +++++++++++++++---- 3 files changed, 39 insertions(+), 13 deletions(-) diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index 34a3aa21..bdefb66f 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -61,7 +61,7 @@ public interface IBaritoneProvider { return baritone; } } - throw new IllegalStateException("No baritone for player " + player); + return null; } /** diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java index 460d8a27..0fd2436c 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -18,6 +18,7 @@ package baritone.launch.mixins; import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; import baritone.api.event.events.RotationMoveEvent; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; @@ -55,8 +56,11 @@ public abstract class MixinEntityLivingBase extends Entity { private void preMoveRelative(CallbackInfo ci) { // noinspection ConstantConditions if (EntityPlayerSP.class.isInstance(this)) { - this.jumpRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.JUMP, this.rotationYaw); - BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent); + 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); + } } } @@ -69,7 +73,7 @@ public abstract class MixinEntityLivingBase extends Entity { ) ) private float overrideYaw(EntityLivingBase self) { - if (self instanceof EntityPlayerSP) { + if (self instanceof EntityPlayerSP && BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this) != null) { return this.jumpRotationEvent.getYaw(); } return self.rotationYaw; @@ -84,7 +88,7 @@ public abstract class MixinEntityLivingBase extends Entity { ) private void travel(EntityLivingBase self, float strafe, float up, float forward, float friction) { // noinspection ConstantConditions - if (!EntityPlayerSP.class.isInstance(this)) { + if (!EntityPlayerSP.class.isInstance(this) || BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this) == null) { moveRelative(strafe, up, forward, friction); return; } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index 87cc6562..964641ad 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -19,7 +19,6 @@ package baritone.launch.mixins; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; -import baritone.api.behavior.IPathingBehavior; import baritone.api.event.events.ChatEvent; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.SprintStateEvent; @@ -41,6 +40,10 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(EntityPlayerSP.class) public class MixinEntityPlayerSP { + private IBaritone baritone() { + return + } + @Inject( method = "sendChatMessage", at = @At("HEAD"), @@ -48,7 +51,11 @@ public class MixinEntityPlayerSP { ) private void sendChatMessage(String msg, CallbackInfo ci) { ChatEvent event = new ChatEvent(msg); - BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onSendChatMessage(event); + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); + if (baritone == null) { + return; + } + baritone.getGameEventHandler().onSendChatMessage(event); if (event.isCancelled()) { ci.cancel(); } @@ -64,7 +71,10 @@ public class MixinEntityPlayerSP { ) ) private void onPreUpdate(CallbackInfo ci) { - BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.PRE)); + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); + if (baritone != null) { + baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.PRE)); + } } @Inject( @@ -77,7 +87,10 @@ public class MixinEntityPlayerSP { ) ) private void onPostUpdate(CallbackInfo ci) { - BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST)); + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); + if (baritone != null) { + baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST)); + } } @Redirect( @@ -88,8 +101,11 @@ public class MixinEntityPlayerSP { ) ) private boolean isAllowFlying(PlayerCapabilities capabilities) { - IPathingBehavior pathingBehavior = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getPathingBehavior(); - return !pathingBehavior.isPathing() && capabilities.allowFlying; + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); + if (baritone == null) { + return capabilities.allowFlying; + } + return !baritone.getPathingBehavior().isPathing() && capabilities.allowFlying; } @Redirect( @@ -100,8 +116,11 @@ public class MixinEntityPlayerSP { ) ) private boolean isKeyDown(KeyBinding keyBinding) { - SprintStateEvent event = new SprintStateEvent(); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); + if (baritone == null) { + return keyBinding.isKeyDown(); + } + SprintStateEvent event = new SprintStateEvent(); baritone.getGameEventHandler().onPlayerSprintState(event); if (event.getState() != null) { return event.getState(); @@ -120,6 +139,9 @@ public class MixinEntityPlayerSP { ) ) private void updateRidden(CallbackInfo cb) { - ((LookBehavior) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getLookBehavior()).pig(); + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); + if (baritone != null) { + ((LookBehavior) baritone.getLookBehavior()).pig(); + } } } From e4416f424a865f7e4c11fc1cd971e959973b43f9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 23 Feb 2019 14:13:27 -0800 Subject: [PATCH 207/682] interesting --- src/main/java/baritone/cache/CachedChunk.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index ebf0bfc9..d2737190 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -85,6 +85,7 @@ public final class CachedChunk { temp.add(Blocks.END_GATEWAY); temp.add(Blocks.WEB); temp.add(Blocks.NETHER_WART); + temp.add(Blocks.LADDER); BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(temp); } From bd65e32407651bdcad92a818b3a5e24d7c2e5f7e Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 23 Feb 2019 17:04:14 -0600 Subject: [PATCH 208/682] Fix the failing build --- .../java/baritone/launch/mixins/MixinEntityPlayerSP.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index 964641ad..7c1225b9 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -40,10 +40,6 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(EntityPlayerSP.class) public class MixinEntityPlayerSP { - private IBaritone baritone() { - return - } - @Inject( method = "sendChatMessage", at = @At("HEAD"), From f1084fab768522604911c71798aaf1f0725fa4e2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 23 Feb 2019 20:33:00 -0800 Subject: [PATCH 209/682] come --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index d8650471..31ee8ff1 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -251,6 +251,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Queued " + count + " chunks for repacking"); return true; } + if (msg.equals("come")) { + customGoalProcess.setGoalAndPath(new GoalBlock(new BlockPos(mc.getRenderViewEntity()))); + logDirect("Coming"); + return true; + } if (msg.equals("axis") || msg.equals("highway")) { customGoalProcess.setGoalAndPath(new GoalAxis()); return true; From 600c5b77ad02864a1fc8cd2de03925a0b36bf643 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 23 Feb 2019 20:43:29 -0800 Subject: [PATCH 210/682] v1.2.0 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index b0173f5d..7d9e0958 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.1.6' +version '1.2.0' buildscript { repositories { From 195c33407e264c525de516cf9bedf7ffb54052c2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 24 Feb 2019 13:43:53 -0800 Subject: [PATCH 211/682] cant walk through heads --- src/main/java/baritone/pathing/movement/MovementHelper.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 0f6659b9..07a983a3 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -74,7 +74,7 @@ public interface MovementHelper extends ActionCosts, Helper { if (block == Blocks.AIR) { // early return for most common case return true; } - if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.WEB || block == Blocks.END_PORTAL || block == Blocks.COCOA) { + if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.WEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof BlockSkull) { return false; } if (block instanceof BlockDoor || block instanceof BlockFenceGate) { @@ -157,7 +157,8 @@ public interface MovementHelper extends ActionCosts, Helper { || block instanceof BlockSnow || block instanceof BlockLiquid || block instanceof BlockTrapDoor - || block instanceof BlockEndPortal) { + || block instanceof BlockEndPortal + || block instanceof BlockSkull) { return false; } // door, fence gate, liquid, trapdoor have been accounted for, nothing else uses the world or pos parameters From 583ce800037c1f06bd28f19238ea72ca06588da9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 24 Feb 2019 13:57:33 -0800 Subject: [PATCH 212/682] not reliable enough with jesus to jump from water over a gap --- .../baritone/pathing/movement/movements/MovementParkour.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 74acac48..185167c6 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -28,6 +28,7 @@ import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; +import net.minecraft.block.BlockLiquid; import net.minecraft.block.BlockStairs; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -85,7 +86,7 @@ public class MovementParkour extends Movement { return; } IBlockState standingOn = context.get(x, y - 1, z); - if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || standingOn.getBlock() instanceof BlockStairs || MovementHelper.isBottomSlab(standingOn)) { + if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || standingOn.getBlock() instanceof BlockStairs || MovementHelper.isBottomSlab(standingOn) || standingOn.getBlock() instanceof BlockLiquid) { return; } int maxJump; From b19f241d81caee9b0520af4399a507ee4df8fce6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 25 Feb 2019 15:06:55 -0800 Subject: [PATCH 213/682] override for the first tick --- src/main/java/baritone/process/CustomGoalProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index 1c4e0311..00d3c802 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -81,7 +81,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG } return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL); case PATH_REQUESTED: - PathingCommand ret = new PathingCommand(this.goal, PathingCommandType.SET_GOAL_AND_PATH); + PathingCommand ret = new PathingCommand(this.goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); this.state = State.EXECUTING; return ret; case EXECUTING: From 7afe16fc1012f0240b096b4889aaa52546aa230e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 25 Feb 2019 16:26:17 -0800 Subject: [PATCH 214/682] dont reset every tick --- src/main/java/baritone/utils/BaritoneAutoTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index b7ae5fbb..c798c563 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -115,7 +115,9 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { } // Setup Baritone's pathing goal and (if needed) begin pathing - BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(GOAL); + if (!BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().isActive()) { + BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(GOAL); + } // If we have reached our goal, print a message and safely close the game if (GOAL.isInGoal(ctx.playerFeet())) { From fbb2d37634714ee99fc13f7ec3bd7e8654cf07b6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 25 Feb 2019 18:01:11 -0800 Subject: [PATCH 215/682] allow placing against replacable blocks --- .../java/baritone/pathing/movement/MovementHelper.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 07a983a3..a3fbf041 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -40,6 +40,8 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; +import java.util.Optional; + import static baritone.pathing.movement.Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP; /** @@ -494,7 +496,12 @@ public interface MovementHelper extends ActionCosts, Helper { static PlaceResult attemptToPlaceABlock(MovementState state, IBaritone baritone, BlockPos placeAt, boolean preferDown) { IPlayerContext ctx = baritone.getPlayerContext(); + Optional direct = RotationUtils.reachable(ctx, placeAt); // we assume that if there is a block there, it must be replacable boolean found = false; + if (direct.isPresent()) { + state.setTarget(new MovementState.MovementTarget(direct.get(), true)); + found = true; + } for (int i = 0; i < 5; i++) { BlockPos against1 = placeAt.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); if (MovementHelper.canPlaceAgainst(ctx, against1)) { From 6e7320b954bee323f41b8373bd7746ced87b04cb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 25 Feb 2019 18:07:55 -0800 Subject: [PATCH 216/682] v1.2.1 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 7d9e0958..a03a8963 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.2.0' +version '1.2.1' buildscript { repositories { From 5412fa6cfd92d6249e2c507d06b8fe3164c31ee4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 25 Feb 2019 20:35:06 -0800 Subject: [PATCH 217/682] cursed flowing --- src/main/java/baritone/cache/ChunkPacker.java | 17 ++++++++------ .../pathing/movement/MovementHelper.java | 22 +++++++++++++++---- .../movement/movements/MovementDescend.java | 2 +- 3 files changed, 29 insertions(+), 12 deletions(-) diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index e2903cea..892369d5 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -19,10 +19,7 @@ package baritone.cache; import baritone.pathing.movement.MovementHelper; import baritone.utils.pathing.PathingBlockType; -import net.minecraft.block.Block; -import net.minecraft.block.BlockDoublePlant; -import net.minecraft.block.BlockFlower; -import net.minecraft.block.BlockTallGrass; +import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; @@ -73,7 +70,7 @@ public final class ChunkPacker { for (int x = 0; x < 16; x++) { int index = CachedChunk.getPositionIndex(x, y, z); IBlockState state = bsc.get(x, y1, z); - boolean[] bits = getPathingBlockType(state).getBits(); + boolean[] bits = getPathingBlockType(state, chunk, x, y, z).getBits(); bitSet.set(index, bits[0]); bitSet.set(index + 1, bits[1]); Block block = state.getBlock(); @@ -122,11 +119,17 @@ public final class ChunkPacker { return resourceCache.computeIfAbsent(name, n -> Block.getBlockFromName(n.contains(":") ? n : "minecraft:" + n)); } - private static PathingBlockType getPathingBlockType(IBlockState state) { + private static PathingBlockType getPathingBlockType(IBlockState state, Chunk chunk, int x, int y, int z) { Block block = state.getBlock(); - if ((block == Blocks.WATER || block == Blocks.FLOWING_WATER) && !MovementHelper.isFlowing(state)) { + if (block == Blocks.WATER || block == Blocks.FLOWING_WATER) { // only water source blocks are plausibly usable, flowing water should be avoid // FLOWING_WATER is a waterfall, it doesn't really matter and caching it as AVOID just makes it look wrong + if (!MovementHelper.possiblyFlowing(state)) { + return PathingBlockType.WATER; + } + if (BlockLiquid.getSlopeAngle(chunk.getWorld(), new BlockPos(x + chunk.x << 4, y, z + chunk.z << 4), state.getMaterial(), state) != -1000.0F) { + return PathingBlockType.AVOID; + } return PathingBlockType.WATER; } diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index a3fbf041..592aecd0 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -109,7 +109,7 @@ public interface MovementHelper extends ActionCosts, Helper { } throw new IllegalStateException(); } - if (isFlowing(state)) { + if (isFlowing(x, y, z, state, bsi)) { return false; // Don't walk through flowing liquids } if (block instanceof BlockLiquid) { @@ -288,10 +288,10 @@ public interface MovementHelper extends ActionCosts, Helper { // since this is called literally millions of times per second, the benefit of not allocating millions of useless "pos.up()" // BlockPos s that we'd just garbage collect immediately is actually noticeable. I don't even think its a decrease in readability Block up = bsi.get0(x, y + 1, z).getBlock(); - if (up == Blocks.WATERLILY) { + if (up == Blocks.WATERLILY || up == Blocks.CARPET) { return true; } - if (isFlowing(state) || block == Blocks.FLOWING_WATER) { + if (isFlowing(x, y, z, state, bsi) || block == Blocks.FLOWING_WATER) { // the only scenario in which we can walk on flowing water is if it's under still water with jesus off return isWater(up) && !Baritone.settings().assumeWalkOnWater.get(); } @@ -488,12 +488,26 @@ public interface MovementHelper extends ActionCosts, Helper { return BlockStateInterface.getBlock(ctx, p) instanceof BlockLiquid; } - static boolean isFlowing(IBlockState state) { + static boolean possiblyFlowing(IBlockState state) { // Will be IFluidState in 1.13 return state.getBlock() instanceof BlockLiquid && state.getValue(BlockLiquid.LEVEL) != 0; } + static boolean isFlowing(int x, int y, int z, IBlockState state, BlockStateInterface bsi) { + if (!(state.getBlock() instanceof BlockLiquid)) { + return false; + } + if (state.getValue(BlockLiquid.LEVEL) != 0) { + return true; + } + return possiblyFlowing(bsi.get0(x + 1, y, z)) + || possiblyFlowing(bsi.get0(x - 1, y, z)) + || possiblyFlowing(bsi.get0(x, y, z + 1)) + || possiblyFlowing(bsi.get0(x, y, z - 1)); + } + + static PlaceResult attemptToPlaceABlock(MovementState state, IBaritone baritone, BlockPos placeAt, boolean preferDown) { IPlayerContext ctx = baritone.getPlayerContext(); Optional direct = RotationUtils.reachable(ctx, placeAt); // we assume that if there is a block there, it must be replacable diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 914a2993..3a8ed913 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -143,7 +143,7 @@ public class MovementDescend extends Movement { if (context.assumeWalkOnWater) { return false; // TODO fix } - if (MovementHelper.isFlowing(ontoBlock)) { + if (MovementHelper.isFlowing(destX, newY, destZ, ontoBlock, context.bsi)) { return false; // TODO flowing check required here? } if (!MovementHelper.canWalkOn(context.bsi, destX, newY - 1, destZ)) { From 9be44c0371b172fb119d0ba69b93c44b1a367414 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 26 Feb 2019 14:57:44 -0800 Subject: [PATCH 218/682] placement without unepic right click --- src/api/java/baritone/api/Settings.java | 15 ++-- .../api/utils/IInputOverrideHandler.java | 3 - .../baritone/api/utils/IPlayerController.java | 7 ++ .../launch/mixins/MixinKeyBinding.java | 79 ------------------- src/launch/resources/mixins.baritone.json | 1 - .../movement/movements/MovementPillar.java | 2 +- .../java/baritone/utils/BlockBreakHelper.java | 2 +- .../java/baritone/utils/BlockPlaceHelper.java | 53 +++++++++++++ .../baritone/utils/InputOverrideHandler.java | 36 ++------- .../utils/player/PrimaryPlayerController.java | 12 +++ 10 files changed, 86 insertions(+), 124 deletions(-) delete mode 100644 src/launch/java/baritone/launch/mixins/MixinKeyBinding.java create mode 100644 src/main/java/baritone/utils/BlockPlaceHelper.java diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 2d67dbe3..7b47a2a6 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -170,6 +170,11 @@ public final class Settings { */ public final Setting sprintAscends = new Setting<>(true); + /** + * How many ticks between right clicks are allowed. Default in game is 4 + */ + public final Setting rightClickSpeed = new Setting<>(4); + /** * This is the big A* setting. * As long as your cost heuristic is an *underestimate*, it's guaranteed to find you the best path. @@ -386,11 +391,6 @@ public final class Settings { */ public final Setting pruneRegionsFromRAM = new Setting<>(false); - /** - * Cancel baritone on left click, as a form of "panic button" - */ - public final Setting clickCancel = new Setting<>(false); - /** * Remember the contents of containers (chests, echests, furnaces) *

@@ -509,11 +509,6 @@ public final class Settings { */ public final Setting cachedChunksOpacity = new Setting<>(0.5f); - /** - * If true, Baritone will not allow you to left or right click while pathing - */ - public final Setting suppressClicks = new Setting<>(false); - /** * Whether or not to use the "#" command prefix */ diff --git a/src/api/java/baritone/api/utils/IInputOverrideHandler.java b/src/api/java/baritone/api/utils/IInputOverrideHandler.java index 03f6e4dd..3cfb7438 100644 --- a/src/api/java/baritone/api/utils/IInputOverrideHandler.java +++ b/src/api/java/baritone/api/utils/IInputOverrideHandler.java @@ -19,7 +19,6 @@ package baritone.api.utils; import baritone.api.behavior.IBehavior; import baritone.api.utils.input.Input; -import net.minecraft.client.settings.KeyBinding; /** * @author Brady @@ -27,8 +26,6 @@ import net.minecraft.client.settings.KeyBinding; */ public interface IInputOverrideHandler extends IBehavior { - Boolean isInputForcedDown(KeyBinding key); - boolean isInputForcedDown(Input input); void setInputForceState(Input input, boolean forced); diff --git a/src/api/java/baritone/api/utils/IPlayerController.java b/src/api/java/baritone/api/utils/IPlayerController.java index dd63a41b..dced5286 100644 --- a/src/api/java/baritone/api/utils/IPlayerController.java +++ b/src/api/java/baritone/api/utils/IPlayerController.java @@ -17,12 +17,17 @@ package baritone.api.utils; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ClickType; import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; import net.minecraft.world.GameType; +import net.minecraft.world.World; /** * @author Brady @@ -43,4 +48,6 @@ public interface IPlayerController { default double getBlockReachDistance() { return this.getGameType().isCreative() ? 5.0F : 4.5F; } + + EnumActionResult processRightClickBlock(EntityPlayerSP player, World world, BlockPos pos, EnumFacing direction, Vec3d vec, EnumHand hand); } diff --git a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java deleted file mode 100644 index d61537c9..00000000 --- a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.launch.mixins; - -import baritone.Baritone; -import baritone.api.BaritoneAPI; -import baritone.utils.Helper; -import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.KeyBinding; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -/** - * @author Brady - * @since 7/31/2018 - */ -@Mixin(KeyBinding.class) -public class MixinKeyBinding { - - @Shadow - private int pressTime; - - @Inject( - method = "isKeyDown", - at = @At("HEAD"), - cancellable = true - ) - private void isKeyDown(CallbackInfoReturnable cir) { - // only the primary baritone forces keys - Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this); - if (force != null) { - if (!force && !Baritone.settings().suppressClicks.get()) { - return; - } - cir.setReturnValue(force); // :sunglasses: - } - } - - @Inject( - method = "isPressed", - at = @At("HEAD"), - cancellable = true - ) - private void isPressed(CallbackInfoReturnable cir) { - // only the primary baritone forces keys - Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this); - if (pressTime > 0 && (KeyBinding) (Object) this == Minecraft.getMinecraft().gameSettings.keyBindAttack && Baritone.settings().clickCancel.get() && BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().isPathing()) { - Helper.HELPER.logDirect("Cancelling path on left click since the clickCancel setting is enabled!"); - BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().cancelEverything(); - return; - } - if (force != null && !force && Baritone.settings().suppressClicks.get()) { // <-- cursed - if (pressTime > 0) { - Helper.HELPER.logDirect("You're trying to press this mouse button but I won't let you."); - Helper.HELPER.logDirect("Turn off the suppressClicks setting to allow clicking while pathing."); - pressTime--; - } - cir.setReturnValue(force); // :sunglasses: - } - } -} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index fea9cca7..3b5fa70c 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -17,7 +17,6 @@ "MixinEntityLivingBase", "MixinEntityPlayerSP", "MixinEntityRenderer", - "MixinKeyBinding", "MixinMinecraft", "MixinNetHandlerPlayClient", "MixinNetworkManager", diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index d430f8c5..1bbfa6f9 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -226,7 +226,7 @@ public class MovementPillar extends Movement { if (!(fr instanceof BlockAir || fr.isReplaceable(ctx.world(), src))) { state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; - } else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos()))) { + } else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos())) && ctx.player().posY > dest.getY() + 0.1) { state.setInput(Input.CLICK_RIGHT, true); } } diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index b410e6b3..db56b91f 100644 --- a/src/main/java/baritone/utils/BlockBreakHelper.java +++ b/src/main/java/baritone/utils/BlockBreakHelper.java @@ -31,7 +31,7 @@ public final class BlockBreakHelper implements Helper { private boolean didBreakLastTick; - private IPlayerContext playerContext; + private final IPlayerContext playerContext; public BlockBreakHelper(IPlayerContext playerContext) { this.playerContext = playerContext; diff --git a/src/main/java/baritone/utils/BlockPlaceHelper.java b/src/main/java/baritone/utils/BlockPlaceHelper.java new file mode 100644 index 00000000..e0c782bb --- /dev/null +++ b/src/main/java/baritone/utils/BlockPlaceHelper.java @@ -0,0 +1,53 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import baritone.Baritone; +import baritone.api.utils.IPlayerContext; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; + +public class BlockPlaceHelper implements Helper { + private final IPlayerContext ctx; + private int rightClickTimer; + + public BlockPlaceHelper(IPlayerContext playerContext) { + this.ctx = playerContext; + } + + public void tick(boolean rightClickRequested) { + if (rightClickTimer > 0) { + rightClickTimer--; + return; + } + RayTraceResult mouseOver = ctx.objectMouseOver(); + BlockPos pos = mouseOver.getBlockPos(); + if (!rightClickRequested || ctx.player().isRowingBoat() || pos == null || mouseOver.typeOfHit != RayTraceResult.Type.BLOCK) { + return; + } + rightClickTimer = Baritone.settings().rightClickSpeed.get(); + for (EnumHand hand : EnumHand.values()) { + if (ctx.playerController().processRightClickBlock(ctx.player(), ctx.world(), pos, mouseOver.sideHit, mouseOver.hitVec, hand) == EnumActionResult.SUCCESS) { + ctx.player().swingArm(hand); + return; + } + } + } +} diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 6b0a96e7..47a06854 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -24,7 +24,6 @@ import baritone.api.utils.IInputOverrideHandler; import baritone.api.utils.input.Input; import baritone.behavior.Behavior; import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.KeyBinding; import net.minecraft.util.MovementInputFromOptions; import java.util.HashMap; @@ -46,38 +45,12 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri private final Map inputForceStateMap = new HashMap<>(); private final BlockBreakHelper blockBreakHelper; + private final BlockPlaceHelper blockPlaceHelper; public InputOverrideHandler(Baritone baritone) { super(baritone); this.blockBreakHelper = new BlockBreakHelper(baritone.getPlayerContext()); - } - - /** - * Returns whether or not we are forcing down the specified {@link KeyBinding}. - * - * @param key The KeyBinding object - * @return Whether or not it is being forced down - */ - @Override - public final Boolean isInputForcedDown(KeyBinding key) { - Input input = Input.getInputForBind(key); - if (input == null) { - return null; - } - if (input == Input.CLICK_LEFT && inControl()) { - // only override left click off when pathing - return false; - } - if (input == Input.CLICK_RIGHT) { - if (isInputForcedDown(Input.CLICK_RIGHT)) { - // gettoblock and builder can right click even when not pathing; allow them to do so - return true; - } else if (inControl()) { - // but when we are pathing for real, force right click off - return false; - } - } - return null; // dont force any inputs other than left and right click + this.blockPlaceHelper = new BlockPlaceHelper(baritone.getPlayerContext()); } /** @@ -115,7 +88,11 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri if (event.getType() == TickEvent.Type.OUT) { return; } + if (isInputForcedDown(Input.CLICK_LEFT)) { + setInputForceState(Input.CLICK_RIGHT, false); + } blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT)); + blockPlaceHelper.tick(isInputForcedDown(Input.CLICK_RIGHT)); if (inControl()) { if (ctx.player().movementInput.getClass() != PlayerMovementInput.class) { @@ -131,6 +108,7 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri } private boolean inControl() { + // if we are not primary (a bot) we should set the movementinput even when idle (not pathing) return baritone.getPathingBehavior().isPathing() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone(); } diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerController.java b/src/main/java/baritone/utils/player/PrimaryPlayerController.java index c0dc8798..76e389e7 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerController.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerController.java @@ -19,12 +19,18 @@ package baritone.utils.player; import baritone.api.utils.IPlayerController; import baritone.utils.Helper; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ClickType; import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; import net.minecraft.world.GameType; +import net.minecraft.world.World; /** * Implementation of {@link IPlayerController} that chains to the primary player controller's methods @@ -60,4 +66,10 @@ public enum PrimaryPlayerController implements IPlayerController, Helper { public GameType getGameType() { return mc.playerController.getCurrentGameType(); } + + @Override + public EnumActionResult processRightClickBlock(EntityPlayerSP player, World world, BlockPos pos, EnumFacing direction, Vec3d vec, EnumHand hand) { + // primaryplayercontroller is always in a WorldClient so this is ok + return mc.playerController.processRightClickBlock(player, (WorldClient) world, pos, direction, vec, hand); + } } From c947c778536e46b4ead96838142e4da41af094ab Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 26 Feb 2019 15:07:01 -0800 Subject: [PATCH 219/682] goodbye mc.objectMouseOver --- src/main/java/baritone/utils/player/PrimaryPlayerContext.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java index 1eefc91f..20fe9836 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java @@ -21,6 +21,7 @@ import baritone.api.BaritoneAPI; import baritone.api.cache.IWorldData; import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerController; +import baritone.api.utils.RayTraceUtils; import baritone.utils.Helper; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.math.RayTraceResult; @@ -58,6 +59,6 @@ public enum PrimaryPlayerContext implements IPlayerContext, Helper { @Override public RayTraceResult objectMouseOver() { - return mc.objectMouseOver; + return RayTraceUtils.rayTraceTowards(player(), playerRotations(), playerController().getBlockReachDistance()); } } From 4086c9f4b5daa157a14bb7d4d52634a6d0c7a794 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 26 Feb 2019 17:25:12 -0600 Subject: [PATCH 220/682] Implement secondary license conditioning Sorry fellas, no anime in this town. --- LICENSE-Part-2.jpg | Bin 0 -> 6834 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 LICENSE-Part-2.jpg diff --git a/LICENSE-Part-2.jpg b/LICENSE-Part-2.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d087ee7e07347d5b116d4407290fa56fba240ea5 GIT binary patch literal 6834 zcmb7IWmr_-*PUTt7|EfA4naDkyIYWMq&uVq1WBn8q@+Q*1?d!&Zlt?IB&54}hhIJa zukSwR!=Am@Id?txp1by*`!Msc0)Q&WzK{g~fk1#fVgMfI0a5@kG71<484N}NqoRT# zXizk?Cr{Auv9K|qg!n{6g!nKR2{|n#2`LR33`WI5MMFo=$izrY$;!^kz)s7+$ndxc z5ET^_4T6S;hK9#L0wZDgf7?Sl00#nC0Q>;~sR2khKoAb_p%Xv`00NLek97Yt6fg)G z6$uDIWQh@RMDo8B!T}}{fdEl@hnb%dpwq|VU z<<1)n_wS#QT1K1{#5`9;=1l&E008Bh`B?&dSHvZ@U$aYZPRj1goO#HE7H=ijYk&Q=ghz;(SV$wEn}bk`SxJG7`8WPXc@4}jVO z_qo~MUvHEtby|}>07RC}YLd3tg)laftIjQ8h~)y-8i4}Oox(E&-nb7% zmTPxxP8YI%qOrzexpzOl`Vsckslh=1omaknLWDh*k^KBpN80>4W)@;4fai+O^h>;o zY74Dk(5bR-XutgAX5K&sv-)Ea0Nm`04I-}lm^(G=RWlX(&fQCX_?6q1nm49?s*ZOH zUTT@f~ND~ZS2S>Lex=Tp75{juC5@(P+GdQ8qT7TU+H&+H@} zUfg}>KCz|{33$B1zeb5TOe|0U5E%&wLKw>5aS-A(A*0~ng7Kc>vx^f@b3my~XgImJ zB@pKef;e_S6r_7>fllY9iQyry-QYN@DvYoR!knOq6D=;y(gNRGzw-EbvM|j~>wJbO zQPy^QO(lKDIn65VVo`ct((3;-REgzQt+uV4e{P$Ai@EUYZXL zajh9wlGJhva2iOG!d`Oh1?fpfx=QpOkTl{-YI?sp$6}C{x=c4W2rhpBI7dMSKYc6= zO5{Fs)kd1_^DYDv#U{$FTL5=#$!KvHTBDJ)+_#Ezuo}9e0<2$=-IezA^ta=xv&y;} z7sC=|3f2j78%#+OxaQwxw6p-Dy#VS*({be^=p4 zh&bP4p%6aXU_bT%F+?j02#vn1Ukeql!HgJ0J7{mT(E`T(c%AZRGIrOTLn5Cre5Iiv z+@&Trp|#ML+RsjDihA>F@xkW`fUAyTd_A3wTtP`iN6UO|?S$_6Gpm5>M2h9SmVMZ- zr9H)$o`y!&A%d|ZOgd+t_ChY!ukLv3>e5H^*XbyJHi#u9F|0UTf1_Adof3IRP=$)Q zQy3ECo_5!Eq*KsUr0rjs?tn0%VnMFUq53nLtGR6&A;a?xSiDCM$u;tKh={{%l6kA0 zXN&t|YHA{#cye79fBnjkf>rCnNt3+)3N5(M9Pra>H!WWLR;%HHwX^xCLnu66!MSg9 zy+N;#xmm1HpUhI$-4@w{aSXq5u@aQ>ER0R{LU6QJ7-hQHC->Lanh?*#GMpPX>m!#7 zNW!H+-geAJmF|fg*L{H`c|Xn@(M`0W>kBTTtzRV*U0UTRnc(%!AM#(t92#G!3~vqp zGQu>8u}hKznK5+p8d1mflXb5zQ~I?gw=v60@3XBT=I=&&os`YjL=94yL0!IrV%R*< zXHc*0o04x$#qi`0g|+WXmVf#<7UhDYGT-jf+8xqy#u8+tV6 z6)f6Qwdy+Bl>5wlLF9>}MDl@%8cht_XQ9NL@I`KNZVkSc{H`RJ0kOv{Vx;^tW}Pj& z5?kIs01z)MEe-$)35bM(@?QY}A^|`+$WL+c*f}Ji_~NQAv46d(h!Ph~N$lK}^zD*zNEFz8>kc`Ru-$hc40IiPqb_%!0GY7+l2MS5g<#kn$S$*J8E zV)n=5H8lBmEoE4ZYZ{*Uy7%a1Q2@QB46_{WXurqP=#l9B%~>COm%)C>lQJyg&`#rc zrI2&YI?bOV!)uX+<97+4qO1+=+XJ&J14J5~(HoqULsl3zhCBu&^yHMs9XJAmRO}H9 z1)%`MeMD4MFftfXHW7yS1$bmg%^{%%#iQXAH+5m>l2i|j#dpmfrQ$X*t8629_UZ5+ z9R!OZ-G{OKLLvENQ-;N^v*{=Tcl(Xi=UbpVPh;-)O1{XT5mt{L0tjoz;f^wE5G4V{#eDuie6p*6X)c;g*Au zKavM*O=zsHjWefe&5mX2J~3QG-Yq3ei|3i;-{4Dj^3t~HoQZ|6fwdy9RIT0)rd(I!rd9A1gjO66EL%>u_c7P0=K7Xv`$(5%vZ?04 zB|8KC_JC95J|#|+M5oB(pLwYTW_37}G&9FaQ)00(I;XUOpsG(tS>LW|GWCKxNNL`vfo9>YMzKakcR#I!Wu!=b-!Bt{of)D!gS zMSh&DYl=9&IgQna7`DHmy*-QKT~0~^!=Tc$uuaVC z%MVjrZ`W0Un?toXQ+cT)uW}C$NxOx94rf0iJx$=c&zW*{l)s146m8L(FHPy*a<88G78k(E4kvX&jZ7 zGFsP6$+HdukKUlY%IH^0yt^xIUyaq5F&H$ML5n4_NaeCthUZX{+Mnhu=uS8v(iwDi`qYu%66j|<$X2h-)pKDn)uH7q`b=t(J&F*KYhU>yVYKi+t)HlpKo?VAJ8k- zm%VH5RQR&e`Ay6G9JGC9%I2)2#dDzlTZ)SL(+5CbDc^>j%7D@9ko!{+xNus5+)CvG zAk%JCp)t08N_L8C!O=ZTPvn<)vG5Lm_j%O>yy-nubb^8PMud$q9jlpvE8Ra_i$;6A zz}C;Betw=?JrbKjb7Y{|QMgNX-4$a(PO#rIlBpwsU1(at;QN{qWBjLra+%Qgq2H!z z;Vf+0=S8$Bk`azqk!;k8EWGbu?SbbF+Q)W^_GEc9Xd|;W@|?WOtygi4g7nU?d-;;R;x+Hbb=k@+-pJw=$2aVC;O-8S;cQx{*ox&?JF$Z(2& zVjp``-2<`1tIg&l58CpKCFn=1|rDCgp&z<^GP85t*a9n=ptvGx9Xo+IC8 z@4J=a{)hBa*fQiiUT=ydoiKy;E0DV2`)}{7kjrBSci!riHI46$oQjDi+HEfE^*AMz z+89?-1FW!CBNo0_PBo2X9wc#~rAZKooC-3e+SL-2_bd*EcAa*8rSxhi=Z*qxSP7Eg zkIvu=-D=h8TeE>!<8((tc0|?6^STn3+43>t6K$FjJ%y77=h(0+#q=A*SacQJuDs<; zv|`2!v56>zq2Zb#AE`uNJ^(1;ZOBA&HpwV@!8}9^O3eFb#{f~)X1=-4!+O;nza75C zRo-=AANhf8?>#Hr7LLq*>X`7KifK~3*doV(RSWrHPDA!ZA+&_&*mIH(fEY;ElE%vB z>XYDE%xL6@BT7&T;4A&Or7AE{NJNj@SEWe8f$s*ZmyvF*DY(xddg2TSTF4In8C|#) z?{SNF2iR2JCK^vxoV`eR0QhA;BcRDqV990kX~D}~_~v?UcK@@N@l^4Karz|x?V5jp z4;F(MymS1c;}h@P(>v8uGz=L>C-e(eU){Yfk>4X5f8Z$WayC^criy9@>^n&L%c+|^ zK5Q_78ipe`mG%b!w~FbFU+rQwNT*7|)0unjMUl81R%Wu@787kPfw%NxoDt$btXcgJ zD$&91lqzw9)-A2>BRQLtkZRZ@D#i=vPjGTCizi*WY-zHB1O)C@NCX(aBkxO|v>nSV zJL83oesma+w%&EIMAu|;z^XDEN4aVJEUQlvlLV;bpDrB;w|g#W-E(UeSN^Sypaeh) zWs+Q%5p2;>E>bLW>7;K%n%!)NTXPkRkjz&JVg*xT6|lVjbe+6Lbf>`el7?88ts*k| zZGbY_WP<2e^9HiMW{Wn8$qnvWdez|-x?*^fq}@-r#H3K+8+wMa=N8C|W~lkz1%Af1 z(PPjoQVN1!nTo_KcU=;dJj9DatCND&C9B|G#wGLPD`$M}rJ*fG8HFe6(+$|jK%)&G z@#!nmW1sZtU;f`7d;(&X_HnA7XPHnG9WxWqwBZnvbBT z%Q~Rf6)&{cnsl|d%TkN`eN}jikqPm!+qx`ngQ)A=;~})?udfh*$HotOGA#VRGfRnk z{+|ecC4}GYAD?g}{a+ZolBxV3UmZjf6#eM02Pwo1l60sbe3s)reDg8DNh7+yN;TF0T50HgI@YJ}IS;qariWhiA!wnp*^g@#<~dH+hsXSqzB{Ft80wOW3bM zulcseautQ0jqeP%cKo|i3VQk?KF5cbi%S{%5%CQnq~Yb$ucZ(ipZ&!V35;k@|FOS0 zQi(q*f8Zgs^5`#`k9{%*jsN~j=ouD z`eg7b6Pfh_+mTA>KBWeL%h3GIme+gvuPdC|7dxagZdrk+rs0D#Qb}x-c_vbOfh=Nk z#uPUD%cle2tUoP7fvwx?+J;J*K^KWKTDJShz={u+;_u(YV`=?cq>vCF6%cg)X8d1~ zLX;?|_+Ldz)nxU*A_aW_bQ|wgSOufo9m>8dx(fIrTt5?;5k=qseBm@$4=rII=(ml@ z?H;`=x;i{2WGrPph!$cplip(J=X8ba*eeoD&e@H}!^~k8DS(bN8_kKA_B04fS2#e& zA&U`XokPBgxzETUwIgGc)=7eqf>dS5{wI;QGiy@gu!pw+shIY9V8dZFWK8&(th|l- z#%mUx7q*@CbcBH+uk)4N?A)06`BO_5%oEpyjn{dq{>DDm%GB2$?wczk=*Esnq3($RB3=b1$Tw- z-gR6ML3LyuV6|;fxgYSI)UdZ(@BCfL_u03tMVMjfUnuMWWHV*xkwfe037 z$Lzg}vg%f=F(3eEjV0vS5!|8yF^SfOU?qtSpU2u#?3);&rAPF_$ftlQE+AT*#{_yd5mqv zbrEP9i-_fS0DAog>6MZ;{y(V912aP>Rmj{^)mjut znHiZy{`2%1fVpO{1RL@YP zR`evA3)X8?f^PI@Y*}^ZWi{)1XhB2de$T!rjQCzIgcqZgn#CI?OY+2E<1m6oPMWgo zFudL~s4H4c($YE|b+Kne!*}&C_nWvtN2y-WsCxS=W@cs`*D7sgdvZFqpKtn%(nJ&z z23UV;5IQQkg0?96ZUbVoD#Bv=NhdLi`gu`aZS_bKD?|L0i&jbTig~f`i}KEH5>oW| zQZZC)&xn{)Uuv{mk!^aIE>u6O`JA?jcVj*OzJfo|vS@`?4EqY#D!K;$L+`+1`E#D- z`M5^r5~!>))*xv6kEm+oL3sVzdhRT&55xWNrO@qL>9ddP3$w|5@uP37vvLpP7?^EE z;MeyW*IX2_t7Op_{c)qY1*gIpgPik1CAGCP_?JISa2G&dshdGq$e4>bGiNOEN;WFvAh7CWt$$)-I+3KYT zfzYa$QjBH&1+m11lZNTWr9z~6i06xY@ee1#O1`qH5}peFDmy|ec!~vsLr?NE3zHJ&Tj9H(29s>i zf~KfBYt0Dup(5@Co;}mY6+88rnxwF(TWGWWr!VE-zc@DBIt55nTKdfH18o3OB<3!0 zk()Jai@-kDjo{`ZJoFKa%RThhja+TXBNny4SE-o@G#3nfsDNlvjyZ-@CIlheiQOl_ z8k_>CJ&?qmwP3u1adIb5?Eyf;`f}G_%1(dLKs42yLCH|%BxNaR5K4v3PR{~?4HUcy z>i?8l!&4^bj?@Hk^3Hr+!j({aG^T07e5yZ_!(SeaCHNxQU-| zJe88gW%#3LlN?g5Bg=(kU8gnmoh|uuv093KV$J;b{}^rR%XC2zze# zeF_P>){0i%sb3B|>@1+ Date: Tue, 26 Feb 2019 17:29:50 -0600 Subject: [PATCH 221/682] Better update the badges --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8090c904..928acab8 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Baritone [![Build Status](https://travis-ci.com/cabaletta/baritone.svg?branch=master)](https://travis-ci.com/cabaletta/baritone) [![Release](https://img.shields.io/github/release/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/releases) -[![License](https://img.shields.io/badge/license-LGPL--3.0-green.svg)](LICENSE) +[![License](https://img.shields.io/badge/license-LGPL--3.0%20with%20anime%20exception-green.svg)](LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) [![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) From 3de02cbf21c98d6c7d34fe6a2e7487ed32fed58a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 26 Feb 2019 18:34:11 -0800 Subject: [PATCH 222/682] brady save me idk how to gl --- .../utils/ExampleBaritoneControl.java | 7 ++ .../java/baritone/utils/GuiClickMeme.java | 97 +++++++++++++++++++ .../java/baritone/utils/PathRenderer.java | 3 + 3 files changed, 107 insertions(+) create mode 100644 src/main/java/baritone/utils/GuiClickMeme.java diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 31ee8ff1..a5fe93e9 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -407,6 +407,13 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Started mining blocks of type " + Arrays.toString(blockTypes)); return true; } + if (msg.equals("click")) { + mc.addScheduledTask(() -> { + mc.displayGuiScreen(new GuiClickMeme()); + }); + logDirect("click owo"); + return true; + } if (msg.startsWith("thisway") || msg.startsWith("forward")) { try { Goal goal = GoalXZ.fromDirection(ctx.playerFeetAsVec(), ctx.player().rotationYaw, Double.parseDouble(msg.substring(7).trim())); diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClickMeme.java new file mode 100644 index 00000000..1e5e096e --- /dev/null +++ b/src/main/java/baritone/utils/GuiClickMeme.java @@ -0,0 +1,97 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils; + +import baritone.Baritone; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.Entity; +import net.minecraft.util.math.Vec3d; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.Display; +import org.lwjgl.util.glu.GLU; + +import java.awt.*; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; + +import static org.lwjgl.opengl.GL11.*; + +public class GuiClickMeme extends GuiScreen { + private final FloatBuffer MODELVIEW = BufferUtils.createFloatBuffer(16); + private final FloatBuffer PROJECTION = BufferUtils.createFloatBuffer(16); + private final IntBuffer VIEWPORT = BufferUtils.createIntBuffer(16); + private final FloatBuffer TO_SCREEN_BUFFER = BufferUtils.createFloatBuffer(3); + private final FloatBuffer TO_WORLD_BUFFER = BufferUtils.createFloatBuffer(3); + private Vec3d meme; + + @Override + public boolean doesGuiPauseGame() { + return false; + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + System.out.println("Screen " + mouseX + " " + mouseY); + System.out.println(toWorld(mouseX, mouseY, 0)); + System.out.println(toWorld(mouseX, mouseY, 0.1)); + System.out.println(toWorld(mouseX, mouseY, 1)); + System.out.println(VIEWPORT.get(3) + " " + Display.getHeight()); + meme = toWorld(mouseX, Display.getHeight() - mouseY, 0); + System.out.println(toScreen(mc.player.posX + 1, mc.player.posY, mc.player.posZ)); + System.out.println(toScreen(1, 0, 0)); + } + + public void onRender(float partialTicks) { + System.out.println("on render"); + GlStateManager.getFloat(GL_MODELVIEW_MATRIX, (FloatBuffer) MODELVIEW.clear()); + GlStateManager.getFloat(GL_PROJECTION_MATRIX, (FloatBuffer) PROJECTION.clear()); + GlStateManager.glGetInteger(GL_VIEWPORT, (IntBuffer) VIEWPORT.clear()); + if (meme != null) { + Entity e = mc.getRenderViewEntity(); + 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); + GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); + GlStateManager.disableTexture2D(); + GlStateManager.depthMask(false); + PathRenderer.drawLine(e, e.posX + 1, e.posY, e.posZ, e.posX + meme.x + 1, e.posY + meme.y, e.posZ + meme.z, partialTicks); + Tessellator.getInstance().draw(); + GlStateManager.depthMask(true); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } + } + + public Vec3d toWorld(double x, double y, double z) { + boolean result = GLU.gluUnProject((float) x, (float) y, (float) z, MODELVIEW, PROJECTION, VIEWPORT, (FloatBuffer) TO_WORLD_BUFFER.clear()); + if (result) { + return new Vec3d(TO_WORLD_BUFFER.get(0), TO_WORLD_BUFFER.get(1), TO_WORLD_BUFFER.get(2)); + } + return null; + } + + public Vec3d toScreen(double x, double y, double z) { + boolean result = GLU.gluProject((float) x, (float) y, (float) z, MODELVIEW, PROJECTION, VIEWPORT, (FloatBuffer) TO_SCREEN_BUFFER.clear()); + if (result) { + return new Vec3d(TO_SCREEN_BUFFER.get(0), Display.getHeight() - TO_SCREEN_BUFFER.get(1), TO_SCREEN_BUFFER.get(2)); + } + return null; + } +} diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 06e298be..a51f2e8d 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -59,6 +59,9 @@ public final class PathRenderer implements Helper { public static void render(RenderEvent event, PathingBehavior behavior) { float partialTicks = event.getPartialTicks(); Goal goal = behavior.getGoal(); + if (mc.currentScreen instanceof GuiClickMeme) { + ((GuiClickMeme) mc.currentScreen).onRender(partialTicks); + } int thisPlayerDimension = behavior.baritone.getPlayerContext().world().provider.getDimensionType().getId(); int currentRenderViewDimension = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().provider.getDimensionType().getId(); From c474cdb1f819853f8fb8c430bde713e9d74b7098 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 26 Feb 2019 21:41:08 -0600 Subject: [PATCH 223/682] Working clicking goals --- .../utils/ExampleBaritoneControl.java | 11 +++-- .../java/baritone/utils/GuiClickMeme.java | 48 ++++++++++++++----- 2 files changed, 42 insertions(+), 17 deletions(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index a5fe93e9..041a5401 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -408,10 +408,13 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("click")) { - mc.addScheduledTask(() -> { - mc.displayGuiScreen(new GuiClickMeme()); - }); - logDirect("click owo"); + new Thread(() -> { + try { + Thread.sleep(100); + mc.addScheduledTask(() -> mc.displayGuiScreen(new GuiClickMeme())); + } catch (Exception ignored) {} + }).start(); + logDirect("aight dude"); return true; } if (msg.startsWith("thisway") || msg.startsWith("forward")) { diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClickMeme.java index 1e5e096e..66a06725 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClickMeme.java @@ -18,28 +18,37 @@ package baritone.utils; import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.pathing.goals.GoalBlock; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import org.lwjgl.BufferUtils; +import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import org.lwjgl.util.glu.GLU; import java.awt.*; +import java.io.IOException; import java.nio.FloatBuffer; import java.nio.IntBuffer; +import java.util.Collections; import static org.lwjgl.opengl.GL11.*; public class GuiClickMeme extends GuiScreen { + + // My name is Brady and I grant Leijurv permission to use this pasted code private final FloatBuffer MODELVIEW = BufferUtils.createFloatBuffer(16); private final FloatBuffer PROJECTION = BufferUtils.createFloatBuffer(16); private final IntBuffer VIEWPORT = BufferUtils.createIntBuffer(16); private final FloatBuffer TO_SCREEN_BUFFER = BufferUtils.createFloatBuffer(3); private final FloatBuffer TO_WORLD_BUFFER = BufferUtils.createFloatBuffer(3); - private Vec3d meme; + + private BlockPos meme; @Override public boolean doesGuiPauseGame() { @@ -48,21 +57,32 @@ public class GuiClickMeme extends GuiScreen { @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { - System.out.println("Screen " + mouseX + " " + mouseY); - System.out.println(toWorld(mouseX, mouseY, 0)); - System.out.println(toWorld(mouseX, mouseY, 0.1)); - System.out.println(toWorld(mouseX, mouseY, 1)); - System.out.println(VIEWPORT.get(3) + " " + Display.getHeight()); - meme = toWorld(mouseX, Display.getHeight() - mouseY, 0); - System.out.println(toScreen(mc.player.posX + 1, mc.player.posY, mc.player.posZ)); - System.out.println(toScreen(1, 0, 0)); + int mx = Mouse.getX(); + int my = Mouse.getY(); + Vec3d near = toWorld(mx, my, 0); + Vec3d far = toWorld(mx, my, 1); // "Use 0.945 that's what stack overflow says" - Leijurv + if (near != null && far != null) { + Vec3d viewerPos = new Vec3d(mc.getRenderManager().viewerPosX, mc.getRenderManager().viewerPosY, mc.getRenderManager().viewerPosZ); + RayTraceResult result = mc.world.rayTraceBlocks(near.add(viewerPos), far.add(viewerPos), false, false, true); + if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { + meme = result.getBlockPos(); + } + } + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); + if (mouseButton == 0) { + BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoal(new GoalBlock(meme)); + } } public void onRender(float partialTicks) { - System.out.println("on render"); GlStateManager.getFloat(GL_MODELVIEW_MATRIX, (FloatBuffer) MODELVIEW.clear()); GlStateManager.getFloat(GL_PROJECTION_MATRIX, (FloatBuffer) PROJECTION.clear()); GlStateManager.glGetInteger(GL_VIEWPORT, (IntBuffer) VIEWPORT.clear()); + if (meme != null) { Entity e = mc.getRenderViewEntity(); GlStateManager.enableBlend(); @@ -71,8 +91,10 @@ public class GuiClickMeme extends GuiScreen { GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); - PathRenderer.drawLine(e, e.posX + 1, e.posY, e.posZ, e.posX + meme.x + 1, e.posY + meme.y, e.posZ + meme.z, partialTicks); - Tessellator.getInstance().draw(); + + // drawSingleSelectionBox WHEN? + PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(meme), partialTicks, Color.CYAN); + GlStateManager.depthMask(true); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); From 3dbbe053d7a9d90ee0b3f246abde32af6967681f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 26 Feb 2019 19:45:20 -0800 Subject: [PATCH 224/682] teensy change --- src/main/java/baritone/utils/GuiClickMeme.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClickMeme.java index 66a06725..8f485ffb 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClickMeme.java @@ -20,6 +20,7 @@ package baritone.utils; import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.GoalBlock; +import baritone.api.pathing.goals.GoalTwoBlocks; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; @@ -74,7 +75,9 @@ public class GuiClickMeme extends GuiScreen { protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { super.mouseClicked(mouseX, mouseY, mouseButton); if (mouseButton == 0) { - BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoal(new GoalBlock(meme)); + BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalTwoBlocks(meme)); + } else if (mouseButton == 1) { + BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(meme.up())); } } From 76914b78591985e190ee8b00a3405aa6793c72ae Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 26 Feb 2019 19:50:35 -0800 Subject: [PATCH 225/682] awesome --- scripts/proguard.pro | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/scripts/proguard.pro b/scripts/proguard.pro index e4189f7f..1c67e258 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -13,8 +13,7 @@ -repackageclasses 'baritone' # lwjgl is weird --dontwarn org.lwjgl.opengl.GL14 --dontwarn org.lwjgl.opengl.GL11 +-dontwarn org.lwjgl.* -keep class baritone.api.** { *; } # this is the keep api From 596849c7e68be492c662e6653602fbb23149e310 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 26 Feb 2019 19:51:20 -0800 Subject: [PATCH 226/682] i am rarted --- scripts/proguard.pro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 1c67e258..4bed6b5d 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -13,7 +13,7 @@ -repackageclasses 'baritone' # lwjgl is weird --dontwarn org.lwjgl.* +-dontwarn org.lwjgl.** -keep class baritone.api.** { *; } # this is the keep api From a47b0c0581b59436e9fdf2ef4af9c4bcae53a4a9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 27 Feb 2019 12:00:39 -0800 Subject: [PATCH 227/682] rendering cleanup, fixes #317 --- .../java/baritone/utils/GuiClickMeme.java | 22 +------------ .../java/baritone/utils/PathRenderer.java | 33 ++++++++----------- 2 files changed, 15 insertions(+), 40 deletions(-) diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClickMeme.java index 8f485ffb..1db794ba 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClickMeme.java @@ -17,7 +17,6 @@ package baritone.utils; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalTwoBlocks; @@ -88,19 +87,8 @@ public class GuiClickMeme extends GuiScreen { if (meme != null) { Entity e = mc.getRenderViewEntity(); - 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); - GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); - GlStateManager.disableTexture2D(); - GlStateManager.depthMask(false); - // drawSingleSelectionBox WHEN? - PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(meme), partialTicks, Color.CYAN); - - GlStateManager.depthMask(true); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); + PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(meme), Color.CYAN); } } @@ -111,12 +99,4 @@ public class GuiClickMeme extends GuiScreen { } return null; } - - public Vec3d toScreen(double x, double y, double z) { - boolean result = GLU.gluProject((float) x, (float) y, (float) z, MODELVIEW, PROJECTION, VIEWPORT, (FloatBuffer) TO_SCREEN_BUFFER.clear()); - if (result) { - return new Vec3d(TO_SCREEN_BUFFER.get(0), Display.getHeight() - TO_SCREEN_BUFFER.get(1), TO_SCREEN_BUFFER.get(2)); - } - return null; - } } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index a51f2e8d..c0af870e 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -105,9 +105,9 @@ public final class PathRenderer implements Helper { //long split = System.nanoTime(); if (current != null) { - drawManySelectionBoxes(renderView, current.toBreak(), partialTicks, Baritone.settings().colorBlocksToBreak.get()); - drawManySelectionBoxes(renderView, current.toPlace(), partialTicks, Baritone.settings().colorBlocksToPlace.get()); - drawManySelectionBoxes(renderView, current.toWalkInto(), partialTicks, Baritone.settings().colorBlocksToWalkInto.get()); + drawManySelectionBoxes(renderView, current.toBreak(), Baritone.settings().colorBlocksToBreak.get()); + drawManySelectionBoxes(renderView, current.toPlace(), Baritone.settings().colorBlocksToPlace.get()); + drawManySelectionBoxes(renderView, current.toWalkInto(), Baritone.settings().colorBlocksToWalkInto.get()); } // If there is a path calculation currently running, render the path calculation process @@ -118,7 +118,7 @@ public final class PathRenderer implements Helper { currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { drawPath(mr, 0, renderView, partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); - drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); + drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), Baritone.settings().colorMostRecentConsidered.get()); }); }); //long end = System.nanoTime(); @@ -175,7 +175,7 @@ public final class PathRenderer implements Helper { } GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], alpha); } - drawLine(player, x1, y1, z1, x2, y2, z2, partialTicks); + drawLine(player, x1, y1, z1, x2, y2, z2); tessellator.draw(); } if (Baritone.settings().renderPathIgnoreDepth.get()) { @@ -187,10 +187,10 @@ public final class PathRenderer implements Helper { GlStateManager.disableBlend(); } - public static void drawLine(Entity player, double bp1x, double bp1y, double bp1z, double bp2x, double bp2y, double bp2z, float partialTicks) { - double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks; - double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; - double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; + public static void drawLine(Entity player, double bp1x, double bp1y, double bp1z, double bp2x, double bp2y, double bp2z) { + double d0 = mc.getRenderManager().viewerPosX; + double d1 = mc.getRenderManager().viewerPosY; + double d2 = mc.getRenderManager().viewerPosZ; BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex(); BUFFER.pos(bp2x + 0.5D - d0, bp2y + 0.5D - d1, bp2z + 0.5D - d2).endVertex(); @@ -199,7 +199,7 @@ public final class PathRenderer implements Helper { BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex(); } - public static void drawManySelectionBoxes(Entity player, Collection positions, float partialTicks, Color color) { + public static void drawManySelectionBoxes(Entity player, Collection positions, Color color) { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F); @@ -213,10 +213,6 @@ public final class PathRenderer implements Helper { float expand = 0.002F; //BlockPos blockpos = movingObjectPositionIn.getBlockPos(); - - double renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks; - double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; - double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; BlockStateInterface bsi = new BlockStateInterface(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext()); // TODO this assumes same dimension between primary baritone and render view? is this safe? positions.forEach(pos -> { IBlockState state = bsi.get0(pos); @@ -226,7 +222,7 @@ public final class PathRenderer implements Helper { } else { toDraw = state.getSelectedBoundingBox(player.world, pos); } - toDraw = toDraw.expand(expand, expand, expand).offset(-renderPosX, -renderPosY, -renderPosZ); + toDraw = toDraw.expand(expand, expand, expand).offset(-mc.getRenderManager().viewerPosX, -mc.getRenderManager().viewerPosY, -mc.getRenderManager().viewerPosZ); BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex(); @@ -263,10 +259,9 @@ public final class PathRenderer implements Helper { } public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTicks, Color color) { - double renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks; - double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; - double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; - + double renderPosX = mc.getRenderManager().viewerPosX; + double renderPosY = mc.getRenderManager().viewerPosY; + double renderPosZ = mc.getRenderManager().viewerPosZ; double minX; double maxX; double minZ; From bf25d7328eaa18e8d5ee9c0289ae917b31b97076 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 27 Feb 2019 12:23:05 -0800 Subject: [PATCH 228/682] revalidate on goal update too --- src/main/java/baritone/process/CustomGoalProcess.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index 00d3c802..a6234227 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -55,6 +55,9 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG if (this.state == State.NONE) { this.state = State.GOAL_SET; } + if (this.state == State.EXECUTING) { + this.state = State.PATH_REQUESTED; + } } @Override From 0ed6ccab716cefe20ce2de08fafe8c6c7e592453 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 27 Feb 2019 15:46:28 -0800 Subject: [PATCH 229/682] update some documentation --- FEATURES.md | 2 +- INSTALL.md | 90 ----------------------------------------------------- README.md | 6 ++-- SETUP.md | 21 +++++++------ USAGE.md | 3 +- 5 files changed, 17 insertions(+), 105 deletions(-) delete mode 100644 INSTALL.md diff --git a/FEATURES.md b/FEATURES.md index 09c932f0..372a7741 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -4,7 +4,7 @@ - **Block breaking** Baritone considers breaking blocks as part of its path. It also takes into account your current tool set and hot bar. For example, if you have a Eff V diamond pick, it may choose to mine through a stone barrier, while if you only had a wood pick it might be faster to climb over it. - **Block placing** Baritone considers placing blocks as part of its path. This includes sneak-back-placing, pillaring, etc. It has a configurable penalty of placing a block (set to 1 second by default), to conserve its resources. The list of acceptable throwaway blocks is also configurable, and is cobble, dirt, or netherrack by default. Example - **Falling** Baritone will fall up to 3 blocks onto solid ground (configurable, if you have Feather Falling and/or don't mind taking a little damage). If you have a water bucket on your hotbar, it will fall up to 23 blocks and place the bucket beneath it. It will fall an unlimited distance into existing still water. -- **Vines and ladders** Baritone understands how to climb and descend vines and ladders. There is experimental support for more advanced maneuvers, like strafing to a different ladder / vine column in midair (off by default, setting named `allowVines`). +- **Vines and ladders** Baritone understands how to climb and descend vines and ladders. There is experimental support for more advanced maneuvers, like strafing to a different ladder / vine column in midair (off by default, setting named `allowVines`). Baritone can break its fall by grabbing ladders / vines midair, and understands when that is and isn't possible. - **Opening fence gates and doors** - **Slabs and stairs** - **Falling blocks** Baritone understands the costs of breaking blocks with falling blocks on top, and includes all of their break costs. Additionally, since it avoids breaking any blocks touching a liquid, it won't break the bottom of a gravel stack below a lava lake (anymore). diff --git a/INSTALL.md b/INSTALL.md deleted file mode 100644 index e66054b6..00000000 --- a/INSTALL.md +++ /dev/null @@ -1,90 +0,0 @@ -# Integration between Baritone and Impact -Impact 4.4 has Baritone included. - -These instructions apply to Impact 4.3. - -For Forge follow the instructions in [Setup](SETUP.md). - -To run Baritone on Vanilla, just follow the instructions in the README (it's `./gradlew runClient`). - -## An Introduction -There are some basic steps to getting Baritone setup with Impact. -- Acquiring a build of Baritone -- Placing Baritone in the libraries directory -- Modifying the Impact Profile JSON to run baritone -- How to use Baritone - -## Acquiring a build of Baritone -There are two methods of acquiring a build of Baritone - -### Official Release (Not always up to date) -https://github.com/cabaletta/baritone/releases - -For Impact 4.3, there is no Baritone integration yet, so you will want `baritone-standalone-X.Y.Z.jar`. **For the rest of this guide, replace `X.Y.Z` with the actual numeric version you are using.** - -Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. - -The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone .` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). - -### Building Baritone yourself -You can either build Baritone through a command line or through IntelliJ's UI, information on that can be found [here](SETUP.md#building). - -## Placing Baritone in the libraries directory -``/libraries`` is a neat directory in your Minecraft Installation Directory -that contains all of the dependencies that are required from the game and some mods. This is where we will be -putting baritone. -- Locate the ``libraries`` folder, it should be in the Minecraft Installation Directory -- Create 3 new subdirectories starting from ``libraries`` - - ``cabaletta`` - - ``baritone`` - - ``X.Y.Z`` - - Copy the build of Baritone that was acquired earlier, and place it into the ``X.Y.Z`` folder, renamed like so: - - The full path should look like ``/libraries/cabaletta/baritone/X.Y.Z/baritone-X.Y.Z.jar`` - -## Modifying the Impact Profile JSON to run baritone -The final step is "registering" the Baritone library with Impact, so that it loads on launch. -- Ensure your Minecraft launcher is closed -- Navigate back to the Minecraft Installation Directory -- Find the ``versions`` directory, and open in -- In here there should be a ``1.12.2-Impact_4.3`` folder. - - If you don't have any Impact folder or have a version older than 4.3, you can download Impact here. -- Open the folder and inside there should be a file called ``1.12.2-Impact_4.3.json`` -- Open the JSON file with a text editor that supports your system's line endings - - For example, Notepad on Windows likely will NOT work for this. You should instead use a Text Editor like - Notepad++ if you're on Windows. (For other systems, I'm not sure - what would work the best so you may have to do some research.) -- Find the ``libraries`` array in the JSON. It should look something like this. - ``` - "libraries": [ - { - "name": "net.minecraft:launchwrapper:1.12" - }, - { - "name": "com.github.ImpactDevelopment:Impact:4.3-1.12.2", - "url": "https://impactdevelopment.github.io/maven/" - }, - { - "name": "com.github.ImpactDeveloment:ClientAPI:3.0.2", - "url": "https://impactdevelopment.github.io/maven/" - }, - ... - ``` -- Create two new objects in the array, between the ``Impact`` and ``ClientAPI`` dependencies preferably. - ``` - { - "name": "cabaletta:baritone:X.Y.Z" - }, - { - "name": "com.github.ImpactDevelopment:SimpleTweaker:1.2", - "url": "https://impactdevelopment.github.io/maven/" - }, - ``` -- Now find the ``"minecraftArguments": "..."`` text near the top. -- At the very end of the quotes where it says ``--tweakClass clientapi.load.ClientTweaker"``, add on the following so it looks like: - - ``--tweakClass clientapi.load.ClientTweaker --tweakClass baritone.launch.BaritoneTweaker"`` -- If you didn't close your launcher for this step, restart it now. -- You can now launch Impact 4.3 as normal, and Baritone should start up - - ## How to use Baritone - -- [Baritone chat control usage](USAGE.md) diff --git a/README.md b/README.md index 928acab8..5aee5702 100644 --- a/README.md +++ b/README.md @@ -40,11 +40,9 @@ Here are some links to help to get started: - [Features](FEATURES.md) -- [Setup](SETUP.md) +- [Installation & setup](SETUP.md) -- [Installation](INSTALL.md) - -- [Javadocs](https://baritone.leijurv.com/) +- [API Javadocs](https://baritone.leijurv.com/) - [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#field.detail) diff --git a/SETUP.md b/SETUP.md index 6d50a85b..33563147 100644 --- a/SETUP.md +++ b/SETUP.md @@ -1,20 +1,23 @@ -# Setup +# Installation -## Prebuilt -(not always completely up to date with latest features) +## Prebuilt official releases +These releases are not always completely up to date with latest features, and are only released from `master`. (so if you want `builder` branch for example, you'll have to build it yourself) -Download from the [Releases](https://github.com/cabaletta/baritone/releases) +Link to the releases page: [Releases](https://github.com/cabaletta/baritone/releases) -The Forge releases can simply be added as a Forge mod. +Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. -If another one of your Forge mods has a Baritone integration, you want `baritone-api-forge-VERSION.jar`. Otherwise, you want `baritone-standalone-forge-VERSION.jar` +The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone .` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). -Previously (Baritone v1.1.2 and below), it was not fully compatible with the latest version of Forge. `freeLook` was broken in Forge 14.23.4.2744. Forge 14.23.4.2743 or **older** worked with Baritone v1.1.2 and lower. Newer versions of Forge "worked", sort of, but Baritone's movement became unreliable and `freeLook` must be off. ## Artifacts Building Baritone will result in 5 artifacts created in the ``dist`` directory. These are the same as the artifacts created in the [releases](https://github.com/cabaletta/baritone/releases). +**The Forge release can simply be added as a Forge mod.** + +If another one of your Forge mods has a Baritone integration, you want `baritone-api-forge-VERSION.jar`. Otherwise, you want `baritone-standalone-forge-VERSION.jar` + - **API**: Only the non-api packages are obfuscated. This should be used in environments where other mods would like to use Baritone's features. - **Forge API**: Same as API, but packaged for Forge. This should be used where another mod has a Baritone integration. - **Standalone**: Everything is obfuscated. This should be used in environments where there are no other mods present that would like to use Baritone's features. @@ -22,9 +25,9 @@ Building Baritone will result in 5 artifacts created in the ``dist`` directory. - **Unoptimized**: Nothing is obfuscated. This shouldn't be used ever in production. ## More Info -To replace out Impact 4.4's Baritone build with a customized one, switch to the `impact4.4-compat` branch, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`). +To replace out Impact 4.5's Baritone build with a customized one, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.2/baritone-api-1.2.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.5/1.12.2-Impact_4.5.json`, find the line `"name": "cabaletta:baritone-api:1.2"`, remove the comma from the end, and **entirely remove the next line** (starts with `"url"`). -Impact 4.4 **only** works with builds from the quite outdated `impact4.4-compat` branch. If you must have the latest Baritone features with Impact, and can't wait for 4.5, consider creating a standalone (non forge) build then adding it to Impact 4.**3** via the instructions in [Install](INSTALL.md). +You can verify whether or not it worked by running `.b version` in chat (only valid in Impact). If it says `v1.2.0` then you didn't do it properly, and it's still running the version that came with 4.5. ## Build it yourself - Clone or download Baritone diff --git a/USAGE.md b/USAGE.md index de5b836d..6a07518b 100644 --- a/USAGE.md +++ b/USAGE.md @@ -9,7 +9,7 @@ Therefore you can use a prefix before your messages. On Baritone v1.1.0 and newer: The prefix is `#` by default. Anything beginning with `#` isn't sent, and is only interpreted by Baritone. For older than v1.1.0, `#` must be enabled by toggling on the `prefix` setting. -**Only** in Impact 4.4 is `.b` also a valid prefix. In 4.4, `#` does **not** work, neither does saying the commands directly in chat. +**Only** in Impact is `.b` also a valid prefix. In 4.4, `#` does **not** work, neither does saying the commands directly in chat. `#` works by default in 4.5 (not 4.4). Other clients like Kami and Asuna have their own custom things (like `-path`), and can disable direct chat control entirely. @@ -39,6 +39,7 @@ Some common examples: - `axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120). - `invert` to invert the current goal and path. This gets as far away from it as possible, instead of as close as possible. For example, do `goal` then `invert` to run as far as possible from where you're standing at the start. - `render` to rerender the world in case `renderCachedChunks` is being glitchy +- `version` to get the version of Baritone you're running - `damn` daniel For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java). From 8ac82ebe2ae44b94c09e5c403b430d347b5b8ee9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 27 Feb 2019 17:48:57 -0800 Subject: [PATCH 230/682] v1.2.2 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index a03a8963..2044d3db 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.2.1' +version '1.2.2' buildscript { repositories { From e767e34b92de076dfdc3ecba1256154a581c9a47 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 27 Feb 2019 22:15:54 -0800 Subject: [PATCH 231/682] well that was stupid, thanks thesmarttheorist --- src/main/java/baritone/utils/BlockPlaceHelper.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/utils/BlockPlaceHelper.java b/src/main/java/baritone/utils/BlockPlaceHelper.java index e0c782bb..e93bf807 100644 --- a/src/main/java/baritone/utils/BlockPlaceHelper.java +++ b/src/main/java/baritone/utils/BlockPlaceHelper.java @@ -21,7 +21,6 @@ import baritone.Baritone; import baritone.api.utils.IPlayerContext; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; public class BlockPlaceHelper implements Helper { @@ -38,13 +37,12 @@ public class BlockPlaceHelper implements Helper { return; } RayTraceResult mouseOver = ctx.objectMouseOver(); - BlockPos pos = mouseOver.getBlockPos(); - if (!rightClickRequested || ctx.player().isRowingBoat() || pos == null || mouseOver.typeOfHit != RayTraceResult.Type.BLOCK) { + if (!rightClickRequested || ctx.player().isRowingBoat() || mouseOver == null || mouseOver.getBlockPos() == null || mouseOver.typeOfHit != RayTraceResult.Type.BLOCK) { return; } rightClickTimer = Baritone.settings().rightClickSpeed.get(); for (EnumHand hand : EnumHand.values()) { - if (ctx.playerController().processRightClickBlock(ctx.player(), ctx.world(), pos, mouseOver.sideHit, mouseOver.hitVec, hand) == EnumActionResult.SUCCESS) { + if (ctx.playerController().processRightClickBlock(ctx.player(), ctx.world(), mouseOver.getBlockPos(), mouseOver.sideHit, mouseOver.hitVec, hand) == EnumActionResult.SUCCESS) { ctx.player().swingArm(hand); return; } From a4237bf1f943bab7b08cd7a35e295421fafe2530 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 27 Feb 2019 23:04:43 -0800 Subject: [PATCH 232/682] tentative fix to descend, needs testing --- .../pathing/movement/movements/MovementDescend.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 3a8ed913..2a2679af 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -202,7 +202,8 @@ public class MovementDescend extends Movement { } BlockPos playerFeet = ctx.playerFeet(); - if (playerFeet.equals(dest) && (MovementHelper.isLiquid(ctx, dest) || ctx.player().posY - playerFeet.getY() < 0.094)) { // lilypads + BlockPos fakeDest = new BlockPos(dest.getX() * 2 - src.getX(), dest.getY(), dest.getZ() * 2 - src.getZ()); + if ((playerFeet.equals(dest) || playerFeet.equals(fakeDest)) && (MovementHelper.isLiquid(ctx, dest) || ctx.player().posY - dest.getY() < 0.5)) { // lilypads // Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately return state.setStatus(MovementStatus.SUCCESS); /* else { @@ -228,12 +229,8 @@ public class MovementDescend extends Movement { double z = ctx.player().posZ - (src.getZ() + 0.5); double fromStart = Math.sqrt(x * x + z * z); if (!playerFeet.equals(dest) || ab > 0.25) { - BlockPos fakeDest = new BlockPos(dest.getX() * 2 - src.getX(), dest.getY(), dest.getZ() * 2 - src.getZ()); - if (numTicks++ < 20) { + if (numTicks++ < 20 && fromStart < 1.25) { MovementHelper.moveTowards(ctx, state, fakeDest); - if (fromStart > 1.25) { - state.getTarget().rotation = new Rotation(state.getTarget().rotation.getYaw() + 180F, state.getTarget().rotation.getPitch()); - } } else { MovementHelper.moveTowards(ctx, state, dest); } From c72eb3e19531c7548e7b9f5972429504f1888d33 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 28 Feb 2019 09:47:47 -0800 Subject: [PATCH 233/682] v1.2.3 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 2044d3db..e52cc370 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.2.2' +version '1.2.3' buildscript { repositories { From 4c6f321cfff945b544e8dddc1d9aed99b794edd1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 28 Feb 2019 12:12:16 -0800 Subject: [PATCH 234/682] clarify --- SETUP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SETUP.md b/SETUP.md index 33563147..cd19a574 100644 --- a/SETUP.md +++ b/SETUP.md @@ -27,7 +27,7 @@ If another one of your Forge mods has a Baritone integration, you want `baritone ## More Info To replace out Impact 4.5's Baritone build with a customized one, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.2/baritone-api-1.2.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.5/1.12.2-Impact_4.5.json`, find the line `"name": "cabaletta:baritone-api:1.2"`, remove the comma from the end, and **entirely remove the next line** (starts with `"url"`). -You can verify whether or not it worked by running `.b version` in chat (only valid in Impact). If it says `v1.2.0` then you didn't do it properly, and it's still running the version that came with 4.5. +You can verify whether or not it worked by running `.b version` in chat (only valid in Impact). It should print out the version that you downloaded. Note: The version that comes with 4.5 is `v1.2.3`. ## Build it yourself - Clone or download Baritone From 3ae05b734867a15fb6b1c869dbb268948f6c6a44 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 28 Feb 2019 15:26:09 -0800 Subject: [PATCH 235/682] worldedit --- .../java/baritone/process/BuilderProcess.java | 11 +++- .../utils/ExampleBaritoneControl.java | 7 +-- .../java/baritone/utils/GuiClickMeme.java | 62 ++++++++++++++++--- .../java/baritone/utils/PathRenderer.java | 57 +++++++++-------- 4 files changed, 94 insertions(+), 43 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 9ff8102d..6c8099f9 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -33,6 +33,7 @@ import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; import baritone.utils.PathingCommandContext; +import baritone.utils.schematic.AirSchematic; import baritone.utils.schematic.Schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -94,6 +95,14 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return true; } + public void clearArea(BlockPos corner1, BlockPos corner2) { + BlockPos origin = new BlockPos(Math.min(corner1.getX(), corner2.getX()), Math.min(corner1.getY(), corner2.getY()), Math.min(corner1.getZ(), corner2.getZ())); + int widthX = Math.abs(corner1.getX() - corner2.getX()) + 1; + int heightY = Math.abs(corner1.getY() - corner2.getY()) + 1; + int lengthZ = Math.abs(corner1.getZ() - corner2.getZ()) + 1; + build("clear area", new AirSchematic(widthX, heightY, lengthZ), origin); + } + private static ISchematic parse(NBTTagCompound schematic) { return new Schematic(schematic); } @@ -273,7 +282,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro // this will work as is, but it'll be trashy // need to iterate over incorrectPositions and see which ones we can "correct" from our current standing position - + baritone.getInputOverrideHandler().clearAllKeys(); BuilderCalculationContext bcc = new BuilderCalculationContext(); if (!recalc(bcc)) { logDirect("Done building"); diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 97d58162..baa0ae7b 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -35,7 +35,6 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; import baritone.utils.pathing.SegmentedCalculator; -import baritone.utils.schematic.AirSchematic; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ChunkProviderClient; @@ -336,11 +335,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } - BlockPos origin = new BlockPos(Math.min(corner1.getX(), corner2.getX()), Math.min(corner1.getY(), corner2.getY()), Math.min(corner1.getZ(), corner2.getZ())); - int widthX = Math.abs(corner1.getX() - corner2.getX()) + 1; - int heightY = Math.abs(corner1.getY() - corner2.getY()) + 1; - int lengthZ = Math.abs(corner1.getZ() - corner2.getZ()) + 1; - baritone.getBuilderProcess().build("clear area", new AirSchematic(widthX, heightY, lengthZ), origin); + baritone.getBuilderProcess().clearArea(corner1, corner2); return true; } if (msg.equals("reset")) { diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClickMeme.java index 1db794ba..4bd878e1 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClickMeme.java @@ -17,22 +17,23 @@ package baritone.utils; +import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalTwoBlocks; +import baritone.api.utils.BetterBlockPos; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; +import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import org.lwjgl.BufferUtils; import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.Display; import org.lwjgl.util.glu.GLU; import java.awt.*; -import java.io.IOException; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.Collections; @@ -48,7 +49,8 @@ public class GuiClickMeme extends GuiScreen { private final FloatBuffer TO_SCREEN_BUFFER = BufferUtils.createFloatBuffer(3); private final FloatBuffer TO_WORLD_BUFFER = BufferUtils.createFloatBuffer(3); - private BlockPos meme; + private BlockPos clickStart; + private BlockPos currentMouseOver; @Override public boolean doesGuiPauseGame() { @@ -65,19 +67,40 @@ public class GuiClickMeme extends GuiScreen { Vec3d viewerPos = new Vec3d(mc.getRenderManager().viewerPosX, mc.getRenderManager().viewerPosY, mc.getRenderManager().viewerPosZ); RayTraceResult result = mc.world.rayTraceBlocks(near.add(viewerPos), far.add(viewerPos), false, false, true); if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { - meme = result.getBlockPos(); + currentMouseOver = result.getBlockPos(); } } + } @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { - super.mouseClicked(mouseX, mouseY, mouseButton); + protected void mouseReleased(int mouseX, int mouseY, int mouseButton) { + System.out.println("Mouse released"); if (mouseButton == 0) { - BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalTwoBlocks(meme)); + if (clickStart != null && !clickStart.equals(currentMouseOver)) { + ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getBuilderProcess().clearArea(clickStart, currentMouseOver); + clickStart = null; + } else { + + + BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalTwoBlocks(currentMouseOver)); + } } else if (mouseButton == 1) { - BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(meme.up())); + BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(currentMouseOver.up())); } + clickStart = null; + } + + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) { + System.out.println("Mouse clicked"); + clickStart = currentMouseOver; + } + + @Override + protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { + System.out.println("Click move"); } public void onRender(float partialTicks) { @@ -85,11 +108,30 @@ public class GuiClickMeme extends GuiScreen { GlStateManager.getFloat(GL_PROJECTION_MATRIX, (FloatBuffer) PROJECTION.clear()); GlStateManager.glGetInteger(GL_VIEWPORT, (IntBuffer) VIEWPORT.clear()); - if (meme != null) { + if (currentMouseOver != null) { Entity e = mc.getRenderViewEntity(); // drawSingleSelectionBox WHEN? - PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(meme), Color.CYAN); + PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(currentMouseOver), Color.CYAN); + if (clickStart != null && !clickStart.equals(currentMouseOver)) { + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); + GlStateManager.color(Color.RED.getColorComponents(null)[0], Color.RED.getColorComponents(null)[1], Color.RED.getColorComponents(null)[2], 0.4F); + GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); + GlStateManager.disableTexture2D(); + GlStateManager.depthMask(false); + GlStateManager.disableDepth(); + BetterBlockPos a = new BetterBlockPos(currentMouseOver); + BetterBlockPos b = new BetterBlockPos(clickStart); + PathRenderer.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(); + } } + + } public Vec3d toWorld(double x, double y, double z) { diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index c0af870e..807523e2 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -211,7 +211,7 @@ public final class PathRenderer implements Helper { GlStateManager.disableDepth(); } - float expand = 0.002F; + //BlockPos blockpos = movingObjectPositionIn.getBlockPos(); BlockStateInterface bsi = new BlockStateInterface(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext()); // TODO this assumes same dimension between primary baritone and render view? is this safe? positions.forEach(pos -> { @@ -222,31 +222,7 @@ public final class PathRenderer implements Helper { } else { toDraw = state.getSelectedBoundingBox(player.world, pos); } - toDraw = toDraw.expand(expand, expand, expand).offset(-mc.getRenderManager().viewerPosX, -mc.getRenderManager().viewerPosY, -mc.getRenderManager().viewerPosZ); - BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); - 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.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); - TESSELLATOR.draw(); - BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); - 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.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); - TESSELLATOR.draw(); - BUFFER.begin(GL_LINES, DefaultVertexFormats.POSITION); - 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(); - TESSELLATOR.draw(); + drawAABB(toDraw); }); if (Baritone.settings().renderSelectionBoxesIgnoreDepth.get()) { @@ -258,6 +234,35 @@ public final class PathRenderer implements Helper { GlStateManager.disableBlend(); } + public static void drawAABB(AxisAlignedBB aabb) { + float expand = 0.002F; + AxisAlignedBB toDraw = aabb.expand(expand, expand, expand).offset(-mc.getRenderManager().viewerPosX, -mc.getRenderManager().viewerPosY, -mc.getRenderManager().viewerPosZ); + BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); + 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.maxZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); + TESSELLATOR.draw(); + BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); + 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.maxZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); + TESSELLATOR.draw(); + BUFFER.begin(GL_LINES, DefaultVertexFormats.POSITION); + 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(); + TESSELLATOR.draw(); + } + public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTicks, Color color) { double renderPosX = mc.getRenderManager().viewerPosX; double renderPosY = mc.getRenderManager().viewerPosY; From 701bc772a8664cbbabddf8fea9084a7c416107bb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 1 Mar 2019 11:22:21 -0800 Subject: [PATCH 236/682] update impcat badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5aee5702..d59c7ba7 100644 --- a/README.md +++ b/README.md @@ -16,8 +16,8 @@ [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) +[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.3-brightgreen.svg)](https://impactdevelopment.github.io/) [![Asuna integration](https://img.shields.io/badge/Asuna%20integration-builder%20branch-brightgreen.svg)](https://github.com/EmotionalLove/Asuna/) -[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.0.0--hotfix--4-green.svg)](https://impactdevelopment.github.io/) [![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-orange.svg)](https://github.com/zeroeightysix/KAMI/) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-v1.0.0%3F%3F%20smh%20license%20violations-orange.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) From 3e47d485f9ba85854b52631895c069a3d7c7dc53 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 1 Mar 2019 12:11:47 -0800 Subject: [PATCH 237/682] emphasize and clarify lol --- SETUP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SETUP.md b/SETUP.md index cd19a574..49ab838f 100644 --- a/SETUP.md +++ b/SETUP.md @@ -25,7 +25,7 @@ If another one of your Forge mods has a Baritone integration, you want `baritone - **Unoptimized**: Nothing is obfuscated. This shouldn't be used ever in production. ## More Info -To replace out Impact 4.5's Baritone build with a customized one, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.2/baritone-api-1.2.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.5/1.12.2-Impact_4.5.json`, find the line `"name": "cabaletta:baritone-api:1.2"`, remove the comma from the end, and **entirely remove the next line** (starts with `"url"`). +To replace out Impact 4.5's Baritone build with a customized one, build Baritone as above then copy & **rename** `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.2/baritone-api-1.2.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.5/1.12.2-Impact_4.5.json`, find the line `"name": "cabaletta:baritone-api:1.2"`, remove the comma from the end, and **entirely remove the NEXT line** (starts with `"url"`). **Restart your launcher** then load as normal. You can verify whether or not it worked by running `.b version` in chat (only valid in Impact). It should print out the version that you downloaded. Note: The version that comes with 4.5 is `v1.2.3`. From 81b22019dd2c7d837a262a41cdf565d2863a3395 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 2 Mar 2019 21:43:11 -0800 Subject: [PATCH 238/682] Create CODE_OF_CONDUCT.md --- CODE_OF_CONDUCT.md | 76 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..3dc44d88 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at complaints@leijurv.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq From c4652285319ae47249105437065a7d9b7a90cfaf Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 2 Mar 2019 21:44:20 -0800 Subject: [PATCH 239/682] consistency with the previously existing anime policy --- CODE_OF_CONDUCT.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 3dc44d88..8811361f 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -14,6 +14,7 @@ appearance, race, religion, or sexual identity and orientation. Examples of behavior that contributes to creating a positive environment include: +* No Anime * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism @@ -22,6 +23,7 @@ include: Examples of unacceptable behavior by participants include: +* Anime * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks From 5904441a7ec88fcb0deea3187a39291549e9d091 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 2 Mar 2019 22:40:42 -0800 Subject: [PATCH 240/682] :heart: code of conduct --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d59c7ba7..f5cf2b18 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ [![License](https://img.shields.io/badge/license-LGPL--3.0%20with%20anime%20exception-green.svg)](LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) [![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) +[![Code of Conduct](https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg?style=flat)](https://github.com/cabaletta/baritone/blob/master/CODE_OF_CONDUCT.md) [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) [![Issues](https://img.shields.io/github/issues/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues/) From 66c7a3f513c86ffc89ed724d2af4e0977daed02b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 3 Mar 2019 21:29:31 -0800 Subject: [PATCH 241/682] this is really bad --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f5cf2b18..68654701 100644 --- a/README.md +++ b/README.md @@ -19,8 +19,8 @@ [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.3-brightgreen.svg)](https://impactdevelopment.github.io/) [![Asuna integration](https://img.shields.io/badge/Asuna%20integration-builder%20branch-brightgreen.svg)](https://github.com/EmotionalLove/Asuna/) -[![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-orange.svg)](https://github.com/zeroeightysix/KAMI/) -[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-v1.0.0%3F%3F%20smh%20license%20violations-orange.svg)](https://wweclient.com/) +[![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-red.svg)](https://github.com/zeroeightysix/KAMI/) +[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-v1.0.0%3F%3F%20smh%20license%20violations-red.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soonâ„¢-red.svg)](https://github.com/fr1kin/ForgeHax) From 882ac41291261d1e8219f5d821755f085d9c1e35 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 11:28:41 -0800 Subject: [PATCH 242/682] player coords --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index baa0ae7b..46f092c6 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -257,7 +257,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { try { String[] coords = msg.substring("build".length()).trim().split(" "); file = coords[0] + ".schematic"; - origin = new BlockPos(Integer.parseInt(coords[1]), Integer.parseInt(coords[2]), Integer.parseInt(coords[3])); + origin = new BlockPos(parseOrDefault(coords[1], ctx.playerFeet().x), parseOrDefault(coords[2], ctx.playerFeet().y), parseOrDefault(coords[3], ctx.playerFeet().z)); } catch (Exception ex) { file = msg.substring(5).trim() + ".schematic"; origin = ctx.playerFeet(); @@ -603,6 +603,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return false; } + private int parseOrDefault(String str, int i) { + return str.equals("~") ? i : Integer.parseInt(str); + } + private void log(List stacks) { for (ItemStack stack : stacks) { if (!stack.isEmpty()) { From 558c14a3757425d3e294956c900a463e5199b337 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 13:11:36 -0800 Subject: [PATCH 243/682] little cleanup --- src/main/java/baritone/utils/GuiClickMeme.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClickMeme.java index 1db794ba..1163b1b0 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClickMeme.java @@ -28,7 +28,6 @@ import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import org.lwjgl.BufferUtils; import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.Display; import org.lwjgl.util.glu.GLU; import java.awt.*; @@ -45,7 +44,6 @@ public class GuiClickMeme extends GuiScreen { private final FloatBuffer MODELVIEW = BufferUtils.createFloatBuffer(16); private final FloatBuffer PROJECTION = BufferUtils.createFloatBuffer(16); private final IntBuffer VIEWPORT = BufferUtils.createIntBuffer(16); - private final FloatBuffer TO_SCREEN_BUFFER = BufferUtils.createFloatBuffer(3); private final FloatBuffer TO_WORLD_BUFFER = BufferUtils.createFloatBuffer(3); private BlockPos meme; From 2133ab39b7f8749efaa93d45a5074ce0812bb7ef Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 19:44:36 -0800 Subject: [PATCH 244/682] better cache, needs more testing --- src/main/java/baritone/cache/CachedChunk.java | 35 ++++++++++++++++--- src/main/java/baritone/cache/ChunkPacker.java | 15 +++++--- 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index d2737190..05ef8f3e 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -86,6 +86,7 @@ public final class CachedChunk { temp.add(Blocks.WEB); temp.add(Blocks.NETHER_WART); temp.add(Blocks.LADDER); + temp.add(Blocks.VINE); BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(temp); } @@ -118,6 +119,8 @@ public final class CachedChunk { */ private final BitSet data; + private final BitSet special; + /** * The block names of each surface level block for generating an overview */ @@ -139,12 +142,27 @@ public final class CachedChunk { this.heightMap = new int[256]; this.specialBlockLocations = specialBlockLocations; this.cacheTimestamp = cacheTimestamp; + this.special = new BitSet(); calculateHeightMap(); + setSpecial(); + } + + private final void setSpecial() { + for (List list : specialBlockLocations.values()) { + for (BlockPos pos : list) { + System.out.println("Turning on bit"); + special.set(getPositionIndex(pos.getX(), pos.getY(), pos.getZ()) >> 1); + } + } } public final IBlockState getBlock(int x, int y, int z, int dimension) { + int index = getPositionIndex(x, y, z); + PathingBlockType type = getType(index); int internalPos = z << 4 | x; - if (heightMap[internalPos] == y) { + if (heightMap[internalPos] == y && type != PathingBlockType.AVOID) { + // if the top block in a column is water, we cache it as AVOID but we don't want to just return default state water (which is not flowing) beacuse then it would try to path through it + // we have this exact block, it's a surface block /*System.out.println("Saying that " + x + "," + y + "," + z + " is " + state); if (!Minecraft.getMinecraft().world.getBlockState(new BlockPos(x + this.x * 16, y, z + this.z * 16)).getBlock().equals(state.getBlock())) { @@ -152,15 +170,24 @@ public final class CachedChunk { }*/ return overview[internalPos]; } - PathingBlockType type = getType(x, y, z); + if (special.get(index >> 1)) { + // this block is special + for (Map.Entry> entry : specialBlockLocations.entrySet()) { + for (BlockPos pos : entry.getValue()) { + if (pos.getX() == x && pos.getY() == y && pos.getZ() == z) { + return ChunkPacker.stringToBlock(entry.getKey()).getDefaultState(); + } + } + } + } + if (type == PathingBlockType.SOLID && y == 127 && dimension == -1) { return Blocks.BEDROCK.getDefaultState(); } return ChunkPacker.pathingTypeToBlock(type, dimension); } - private PathingBlockType getType(int x, int y, int z) { - int index = getPositionIndex(x, y, z); + private PathingBlockType getType(int index) { return PathingBlockType.fromBits(data.get(index), data.get(index + 1)); } diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index 892369d5..7f447f87 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -90,7 +90,8 @@ public final class ChunkPacker { IBlockState[] blocks = new IBlockState[256]; for (int z = 0; z < 16; z++) { - https://www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html + https: +//www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html for (int x = 0; x < 16; x++) { for (int y = 255; y >= 0; y--) { int index = CachedChunk.getPositionIndex(x, y, z); @@ -124,10 +125,16 @@ public final class ChunkPacker { if (block == Blocks.WATER || block == Blocks.FLOWING_WATER) { // only water source blocks are plausibly usable, flowing water should be avoid // FLOWING_WATER is a waterfall, it doesn't really matter and caching it as AVOID just makes it look wrong - if (!MovementHelper.possiblyFlowing(state)) { - return PathingBlockType.WATER; + if (MovementHelper.possiblyFlowing(state)) { + return PathingBlockType.AVOID; } - if (BlockLiquid.getSlopeAngle(chunk.getWorld(), new BlockPos(x + chunk.x << 4, y, z + chunk.z << 4), state.getMaterial(), state) != -1000.0F) { + if (x == 0 || x == 15 || z == 0 || z == 15) { + if (BlockLiquid.getSlopeAngle(chunk.getWorld(), new BlockPos(x + chunk.x << 4, y, z + chunk.z << 4), state.getMaterial(), state) == -1000.0F) { + return PathingBlockType.WATER; + } + return PathingBlockType.AVOID; + } + if (MovementHelper.possiblyFlowing(chunk.getBlockState(x + 1, y, z)) || MovementHelper.possiblyFlowing(chunk.getBlockState(x - 1, y, z)) || MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z + 1)) || MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z - 1))) { return PathingBlockType.AVOID; } return PathingBlockType.WATER; From 826f3788d043a42d74aa2fc84f6d4e0c752bd89f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 20:39:22 -0800 Subject: [PATCH 245/682] performance improvement and no allocation promise --- src/main/java/baritone/cache/CachedChunk.java | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 05ef8f3e..390ea3f3 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -18,6 +18,7 @@ package baritone.cache; import baritone.utils.pathing.PathingBlockType; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -119,7 +120,7 @@ public final class CachedChunk { */ private final BitSet data; - private final BitSet special; + private final Int2ObjectOpenHashMap special; /** * The block names of each surface level block for generating an overview @@ -142,16 +143,15 @@ public final class CachedChunk { this.heightMap = new int[256]; this.specialBlockLocations = specialBlockLocations; this.cacheTimestamp = cacheTimestamp; - this.special = new BitSet(); + this.special = new Int2ObjectOpenHashMap<>(); calculateHeightMap(); setSpecial(); } private final void setSpecial() { - for (List list : specialBlockLocations.values()) { - for (BlockPos pos : list) { - System.out.println("Turning on bit"); - special.set(getPositionIndex(pos.getX(), pos.getY(), pos.getZ()) >> 1); + for (Map.Entry> entry : specialBlockLocations.entrySet()) { + for (BlockPos pos : entry.getValue()) { + special.put(getPositionIndex(pos.getX(), pos.getY(), pos.getZ()), entry.getKey()); } } } @@ -170,15 +170,9 @@ public final class CachedChunk { }*/ return overview[internalPos]; } - if (special.get(index >> 1)) { - // this block is special - for (Map.Entry> entry : specialBlockLocations.entrySet()) { - for (BlockPos pos : entry.getValue()) { - if (pos.getX() == x && pos.getY() == y && pos.getZ() == z) { - return ChunkPacker.stringToBlock(entry.getKey()).getDefaultState(); - } - } - } + String str = special.get(index); + if (str != null) { + return ChunkPacker.stringToBlock(str).getDefaultState(); } if (type == PathingBlockType.SOLID && y == 127 && dimension == -1) { From 0d15225b1d089dd09fdb36639e4b8d3a5057a0bf Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 21:00:30 -0800 Subject: [PATCH 246/682] dont construct one unlesss we need to --- src/main/java/baritone/cache/CachedChunk.java | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 390ea3f3..10c17898 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -143,9 +143,13 @@ public final class CachedChunk { this.heightMap = new int[256]; this.specialBlockLocations = specialBlockLocations; this.cacheTimestamp = cacheTimestamp; - this.special = new Int2ObjectOpenHashMap<>(); + if (specialBlockLocations.isEmpty()) { + this.special = null; + } else { + this.special = new Int2ObjectOpenHashMap<>(); + setSpecial(); + } calculateHeightMap(); - setSpecial(); } private final void setSpecial() { @@ -170,9 +174,11 @@ public final class CachedChunk { }*/ return overview[internalPos]; } - String str = special.get(index); - if (str != null) { - return ChunkPacker.stringToBlock(str).getDefaultState(); + if (special != null) { + String str = special.get(index); + if (str != null) { + return ChunkPacker.stringToBlock(str).getDefaultState(); + } } if (type == PathingBlockType.SOLID && y == 127 && dimension == -1) { From 71cb0f6d36387d223a55781e15beb9d1d7b7439e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 21:00:41 -0800 Subject: [PATCH 247/682] fix a weird way of getting stuck on a ladder --- .../pathing/movement/movements/MovementTraverse.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index d618cf1a..4a5687fd 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -231,6 +231,13 @@ public class MovementTraverse extends Movement { if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } + Block low = BlockStateInterface.get(ctx, src).getBlock(); + Block high = BlockStateInterface.get(ctx, src.up()).getBlock(); + if (!ctx.player().onGround && (low == Blocks.VINE || low == Blocks.LADDER || high == Blocks.VINE || high == Blocks.LADDER)) { + // hitting W could cause us to climb the ladder instead of going forward + // wait until we're on the ground + return state; + } BlockPos into = dest.subtract(src).add(dest); Block intoBelow = BlockStateInterface.get(ctx, into).getBlock(); Block intoAbove = BlockStateInterface.get(ctx, into.up()).getBlock(); From a73f5c1359c720d113a7f6ecd576b718deaeea33 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 21:20:13 -0800 Subject: [PATCH 248/682] crapton of performance improvements --- src/api/java/baritone/api/Settings.java | 5 +++++ src/api/java/baritone/api/cache/ICachedWorld.java | 4 ++-- src/main/java/baritone/cache/CachedChunk.java | 4 ++-- src/main/java/baritone/cache/CachedRegion.java | 13 +++++-------- src/main/java/baritone/cache/CachedWorld.java | 7 +++---- src/main/java/baritone/process/MineProcess.java | 5 +++-- .../java/baritone/utils/ExampleBaritoneControl.java | 2 +- 7 files changed, 21 insertions(+), 19 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 7b47a2a6..6be16dad 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -535,6 +535,11 @@ public final class Settings { */ public final Setting mineGoalUpdateInterval = new Setting<>(5); + /** + * After finding this many instances of the target block in the cache, it will stop expanding outward the chunk search. + */ + public final Setting maxCachedWorldScanCount = new Setting<>(10); + /** * When GetToBlock doesn't know any locations for the desired block, explore randomly instead of giving up. */ diff --git a/src/api/java/baritone/api/cache/ICachedWorld.java b/src/api/java/baritone/api/cache/ICachedWorld.java index a435ebe0..e681ce51 100644 --- a/src/api/java/baritone/api/cache/ICachedWorld.java +++ b/src/api/java/baritone/api/cache/ICachedWorld.java @@ -20,7 +20,7 @@ package baritone.api.cache; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.Chunk; -import java.util.LinkedList; +import java.util.ArrayList; /** * @author Brady @@ -68,7 +68,7 @@ public interface ICachedWorld { * @param maxRegionDistanceSq The maximum region distance, squared * @return The locations found that match the special block */ - LinkedList getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq); + ArrayList getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq); /** * Reloads all of the cached regions in this world from disk. Anything that is not saved diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 10c17898..08c80141 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -215,11 +215,11 @@ public final class CachedChunk { return specialBlockLocations; } - public final LinkedList getAbsoluteBlocks(String blockType) { + public final ArrayList getAbsoluteBlocks(String blockType) { if (specialBlockLocations.get(blockType) == null) { return null; } - LinkedList res = new LinkedList<>(); + ArrayList res = new ArrayList<>(); for (BlockPos pos : specialBlockLocations.get(blockType)) { res.add(new BlockPos(pos.getX() + x * 16, pos.getY(), pos.getZ() + z * 16)); } diff --git a/src/main/java/baritone/cache/CachedRegion.java b/src/main/java/baritone/cache/CachedRegion.java index d8426197..0081d941 100644 --- a/src/main/java/baritone/cache/CachedRegion.java +++ b/src/main/java/baritone/cache/CachedRegion.java @@ -87,19 +87,16 @@ public final class CachedRegion implements ICachedRegion { return chunks[x >> 4][z >> 4] != null; } - public final LinkedList getLocationsOf(String block) { - LinkedList res = new LinkedList<>(); + public final ArrayList getLocationsOf(String block) { + ArrayList res = new ArrayList<>(); for (int chunkX = 0; chunkX < 32; chunkX++) { for (int chunkZ = 0; chunkZ < 32; chunkZ++) { if (chunks[chunkX][chunkZ] == null) { continue; } - List locs = chunks[chunkX][chunkZ].getAbsoluteBlocks(block); - if (locs == null) { - continue; - } - for (BlockPos pos : locs) { - res.add(pos); + ArrayList locs = chunks[chunkX][chunkZ].getAbsoluteBlocks(block); + if (locs != null) { + res.addAll(locs); } } } diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index db85339d..025ec773 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -32,7 +32,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; -import java.util.LinkedList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; @@ -109,8 +108,8 @@ public final class CachedWorld implements ICachedWorld, Helper { } @Override - public final LinkedList getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq) { - LinkedList res = new LinkedList<>(); + public final ArrayList getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq) { + ArrayList res = new ArrayList<>(); int centerRegionX = centerX >> 9; int centerRegionZ = centerZ >> 9; @@ -127,7 +126,7 @@ public final class CachedWorld implements ICachedWorld, Helper { CachedRegion region = getOrCreateRegion(regionX, regionZ); if (region != null) { // TODO: 100% verify if this or addAll is faster. - region.getLocationsOf(block).forEach(res::add); + res.addAll(region.getLocationsOf(block)); } } } diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index a299bf31..699cf998 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -210,7 +210,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro //long b = System.currentTimeMillis(); for (Block m : mining) { if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(m)) { - locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2)); + // maxRegionDistanceSq 2 means adjacent directly or adjacent diagonally; nothing further than that + locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), Baritone.settings().maxCachedWorldScanCount.get(), ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2)); } else { uninteresting.add(m); } @@ -221,7 +222,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } if (!uninteresting.isEmpty()) { //long before = System.currentTimeMillis(); - locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), uninteresting, max, 10, 26)); + locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), uninteresting, max, 10, 5)); // maxSearchRadius is NOT sq //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); } locs.addAll(alreadyKnown); diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 041a5401..61b9ebf1 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -376,7 +376,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } if (msg.startsWith("find")) { String blockType = msg.substring(4).trim(); - LinkedList locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4); + ArrayList locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4); logDirect("Have " + locs.size() + " locations"); for (BlockPos pos : locs) { Block actually = BlockStateInterface.get(ctx, pos).getBlock(); From 459720c348055a945cb7a89c86f345a56855d45b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 21:21:02 -0800 Subject: [PATCH 249/682] eh actually lets do the whole render distance! --- 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 699cf998..ac341cb8 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -222,7 +222,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } if (!uninteresting.isEmpty()) { //long before = System.currentTimeMillis(); - locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), uninteresting, max, 10, 5)); // maxSearchRadius is NOT sq + locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), uninteresting, max, 10, 32)); // maxSearchRadius is NOT sq //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); } locs.addAll(alreadyKnown); From 8050b69f2fd13791b029d840b1c8fe8d11d71dfd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 21:30:04 -0800 Subject: [PATCH 250/682] no more .get :sunglasses: --- src/api/java/baritone/api/Settings.java | 6 +-- .../baritone/api/pathing/goals/GoalAxis.java | 4 +- .../baritone/api/pathing/goals/GoalXZ.java | 2 +- .../java/baritone/api/utils/SettingsUtil.java | 4 +- .../mixins/MixinChunkRenderContainer.java | 4 +- .../launch/mixins/MixinChunkRenderWorker.java | 2 +- .../launch/mixins/MixinRenderChunk.java | 4 +- .../launch/mixins/MixinRenderList.java | 2 +- .../launch/mixins/MixinVboRenderList.java | 2 +- .../baritone/behavior/InventoryBehavior.java | 4 +- .../java/baritone/behavior/LookBehavior.java | 6 +-- .../baritone/behavior/MemoryBehavior.java | 8 ++-- .../baritone/behavior/PathingBehavior.java | 12 ++--- .../java/baritone/cache/CachedRegion.java | 2 +- src/main/java/baritone/cache/CachedWorld.java | 4 +- .../java/baritone/cache/ContainerMemory.java | 2 +- .../pathing/calc/AStarPathFinder.java | 14 +++--- .../pathing/calc/AbstractNodeCostSearch.java | 2 +- .../pathing/movement/CalculationContext.java | 30 ++++++------- .../pathing/movement/MovementHelper.java | 14 +++--- .../movement/movements/MovementAscend.java | 2 +- .../movement/movements/MovementDiagonal.java | 2 +- .../movement/movements/MovementTraverse.java | 10 ++--- .../baritone/pathing/path/PathExecutor.java | 14 +++--- .../java/baritone/process/FollowProcess.java | 6 +-- .../baritone/process/GetToBlockProcess.java | 10 ++--- .../java/baritone/process/MineProcess.java | 22 +++++----- .../java/baritone/utils/BlockPlaceHelper.java | 2 +- .../baritone/utils/BlockStateInterface.java | 2 +- .../utils/ExampleBaritoneControl.java | 4 +- src/main/java/baritone/utils/Helper.java | 4 +- .../java/baritone/utils/PathRenderer.java | 44 +++++++++---------- .../baritone/utils/PathingControlManager.java | 2 +- src/main/java/baritone/utils/ToolSet.java | 2 +- .../baritone/utils/pathing/Avoidance.java | 10 ++--- .../java/baritone/utils/pathing/Favoring.java | 2 +- .../java/baritone/utils/pathing/PathBase.java | 6 +-- .../utils/pathing/SegmentedCalculator.java | 2 +- 38 files changed, 137 insertions(+), 137 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 6be16dad..bdebd117 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -721,9 +721,9 @@ public final class Settings { this.klass = (Class) value.getClass(); } - @SuppressWarnings("unchecked") - public final K get() { - return (K) value; + @Deprecated + public final T get() { + return value; } public final String getName() { diff --git a/src/api/java/baritone/api/pathing/goals/GoalAxis.java b/src/api/java/baritone/api/pathing/goals/GoalAxis.java index d8811cf9..7c9b2670 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalAxis.java +++ b/src/api/java/baritone/api/pathing/goals/GoalAxis.java @@ -25,7 +25,7 @@ public class GoalAxis implements Goal { @Override public boolean isInGoal(int x, int y, int z) { - return y == BaritoneAPI.getSettings().axisHeight.get() && (x == 0 || z == 0 || Math.abs(x) == Math.abs(z)); + return y == BaritoneAPI.getSettings().axisHeight.value && (x == 0 || z == 0 || Math.abs(x) == Math.abs(z)); } @Override @@ -39,7 +39,7 @@ public class GoalAxis implements Goal { double flatAxisDistance = Math.min(x, Math.min(z, diff * SQRT_2_OVER_2)); - return flatAxisDistance * BaritoneAPI.getSettings().costHeuristic.get() + GoalYLevel.calculate(BaritoneAPI.getSettings().axisHeight.get(), y); + return flatAxisDistance * BaritoneAPI.getSettings().costHeuristic.value + GoalYLevel.calculate(BaritoneAPI.getSettings().axisHeight.value, y); } @Override diff --git a/src/api/java/baritone/api/pathing/goals/GoalXZ.java b/src/api/java/baritone/api/pathing/goals/GoalXZ.java index 636c649f..7f8d16ab 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalXZ.java +++ b/src/api/java/baritone/api/pathing/goals/GoalXZ.java @@ -80,7 +80,7 @@ public class GoalXZ implements Goal { diagonal = z; } diagonal *= SQRT_2; - return (diagonal + straight) * BaritoneAPI.getSettings().costHeuristic.get(); // big TODO tune + return (diagonal + straight) * BaritoneAPI.getSettings().costHeuristic.value; // big TODO tune } public static GoalXZ fromDirection(Vec3d origin, float yaw, double distance) { diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 84e9af68..051e8793 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -99,7 +99,7 @@ public class SettingsUtil { public static List modifiedSettings(Settings settings) { List modified = new ArrayList<>(); for (Settings.Setting setting : settings.allSettings) { - if (setting.get() == null) { + if (setting.value == null) { System.out.println("NULL SETTING?" + setting.getName()); continue; } @@ -122,7 +122,7 @@ public class SettingsUtil { if (io == null) { throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName()); } - return setting.getName() + " " + io.toString.apply(setting.get()); + return setting.getName() + " " + io.toString.apply(setting.value); } public static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException { diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index 0fc81487..78bd1607 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -41,10 +41,10 @@ public class MixinChunkRenderContainer { ) ) private BlockPos getPosition(RenderChunk renderChunkIn) { - if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { + if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { GlStateManager.enableAlpha(); GlStateManager.enableBlend(); - GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.get()); + GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.value); GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); } return renderChunkIn.getPosition(); diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java index 2bd1521c..81e39382 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java @@ -43,7 +43,7 @@ public abstract class MixinChunkRenderWorker { ) ) private boolean isChunkExisting(ChunkRenderWorker worker, BlockPos pos, World world) { - if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) { + if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { diff --git a/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java b/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java index 754f523f..22ab0bdd 100644 --- a/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java +++ b/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java @@ -47,7 +47,7 @@ public class MixinRenderChunk { if (!chunkCache.isEmpty()) { return false; } - if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) { + if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { @@ -76,7 +76,7 @@ public class MixinRenderChunk { ) ) private IBlockState getBlockState(ChunkCache chunkCache, BlockPos pos) { - if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) { + if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { diff --git a/src/launch/java/baritone/launch/mixins/MixinRenderList.java b/src/launch/java/baritone/launch/mixins/MixinRenderList.java index e2f0ae90..98ae5bf5 100644 --- a/src/launch/java/baritone/launch/mixins/MixinRenderList.java +++ b/src/launch/java/baritone/launch/mixins/MixinRenderList.java @@ -38,7 +38,7 @@ public class MixinRenderList { ) ) private void popMatrix() { - if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) { + if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) { // reset the blend func to normal (not dependent on constant alpha) GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } diff --git a/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java b/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java index f51d2234..bab98b3c 100644 --- a/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java +++ b/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java @@ -38,7 +38,7 @@ public class MixinVboRenderList { ) ) private void popMatrix() { - if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) { + if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) { // reset the blend func to normal (not dependent on constant alpha) GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 8a1ea943..cb5eb612 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -35,7 +35,7 @@ public class InventoryBehavior extends Behavior { @Override public void onTick(TickEvent event) { - if (!Baritone.settings().allowInventory.get()) { + if (!Baritone.settings().allowInventory.value) { return; } if (event.getType() == TickEvent.Type.OUT) { @@ -61,7 +61,7 @@ public class InventoryBehavior extends Behavior { private int firstValidThrowaway() { // TODO offhand idk NonNullList invy = ctx.player().inventory.mainInventory; for (int i = 0; i < invy.size(); i++) { - if (Baritone.settings().acceptableThrowawayItems.get().contains(invy.get(i).getItem())) { + if (Baritone.settings().acceptableThrowawayItems.value.contains(invy.get(i).getItem())) { return i; } } diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index df0921cf..323d81fc 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -53,7 +53,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior { @Override public void updateTarget(Rotation target, boolean force) { this.target = target; - this.force = force || !Baritone.settings().freeLook.get(); + this.force = force || !Baritone.settings().freeLook.value; } @Override @@ -63,7 +63,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior { } // Whether or not we're going to silently set our angles - boolean silent = Baritone.settings().antiCheatCompatibility.get() && !this.force; + boolean silent = Baritone.settings().antiCheatCompatibility.value && !this.force; switch (event.getState()) { case PRE: { @@ -109,7 +109,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior { // If we have antiCheatCompatibility on, we're going to use the target value later in onPlayerUpdate() // Also the type has to be MOTION_UPDATE because that is called after JUMP - if (!Baritone.settings().antiCheatCompatibility.get() && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE && !this.force) { + if (!Baritone.settings().antiCheatCompatibility.value && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE && !this.force) { this.target = null; } } diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 390ac859..8d3a0a8c 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -65,7 +65,7 @@ public final class MemoryBehavior extends Behavior { @Override public synchronized void onTick(TickEvent event) { - if (!Baritone.settings().containerMemory.get()) { + if (!Baritone.settings().containerMemory.value) { return; } if (event.getType() == TickEvent.Type.OUT) { @@ -83,7 +83,7 @@ public final class MemoryBehavior extends Behavior { @Override public synchronized void onSendPacket(PacketEvent event) { - if (!Baritone.settings().containerMemory.get()) { + if (!Baritone.settings().containerMemory.value) { return; } Packet p = event.getPacket(); @@ -122,7 +122,7 @@ public final class MemoryBehavior extends Behavior { @Override public synchronized void onReceivePacket(PacketEvent event) { - if (!Baritone.settings().containerMemory.get()) { + if (!Baritone.settings().containerMemory.value) { return; } Packet p = event.getPacket(); @@ -171,7 +171,7 @@ public final class MemoryBehavior extends Behavior { private void updateInventory() { - if (!Baritone.settings().containerMemory.get()) { + if (!Baritone.settings().containerMemory.value) { return; } int windowId = ctx.player().openContainer.windowId; diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index e9e4d480..a7c5c34b 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -201,7 +201,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // and this path doesn't get us all the way there return; } - if (ticksRemainingInSegment(false).get() < Baritone.settings().planningTickLookahead.get()) { + if (ticksRemainingInSegment(false).get() < Baritone.settings().planningTickLookahead.value) { // and this path has 7.5 seconds or less left // don't include the current movement so a very long last movement (e.g. descend) doesn't trip it up // if we actually included current, it wouldn't start planning ahead until the last movement was done, if the last movement took more than 7.5 seconds on its own @@ -426,11 +426,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, long primaryTimeout; long failureTimeout; if (current == null) { - primaryTimeout = Baritone.settings().primaryTimeoutMS.get(); - failureTimeout = Baritone.settings().failureTimeoutMS.get(); + primaryTimeout = Baritone.settings().primaryTimeoutMS.value; + failureTimeout = Baritone.settings().failureTimeoutMS.value; } else { - primaryTimeout = Baritone.settings().planAheadPrimaryTimeoutMS.get(); - failureTimeout = Baritone.settings().planAheadFailureTimeoutMS.get(); + primaryTimeout = Baritone.settings().planAheadPrimaryTimeoutMS.value; + failureTimeout = Baritone.settings().planAheadFailureTimeoutMS.value; } CalculationContext context = new CalculationContext(baritone, true); // not safe to create on the other thread, it looks up a lot of stuff in minecraft AbstractNodeCostSearch pathfinder = createPathfinder(start, goal, current == null ? null : current.getPath(), context); @@ -494,7 +494,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, public static AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, IPath previous, CalculationContext context) { Goal transformed = goal; - if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) { + if (Baritone.settings().simplifyUnloadedYCoord.value && goal instanceof IGoalRenderPos) { BlockPos pos = ((IGoalRenderPos) goal).getGoalPos(); if (!context.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ())) { transformed = new GoalXZ(pos.getX(), pos.getZ()); diff --git a/src/main/java/baritone/cache/CachedRegion.java b/src/main/java/baritone/cache/CachedRegion.java index 0081d941..e3a85dfc 100644 --- a/src/main/java/baritone/cache/CachedRegion.java +++ b/src/main/java/baritone/cache/CachedRegion.java @@ -303,7 +303,7 @@ public final class CachedRegion implements ICachedRegion { } public synchronized final void removeExpired() { - long expiry = Baritone.settings().cachedChunksExpirySeconds.get(); + long expiry = Baritone.settings().cachedChunksExpirySeconds.value; if (expiry < 0) { return; } diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 025ec773..e8ea5cae 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -145,7 +145,7 @@ public final class CachedWorld implements ICachedWorld, Helper { @Override public final void save() { - if (!Baritone.settings().chunkCaching.get()) { + if (!Baritone.settings().chunkCaching.value) { System.out.println("Not saving to disk; chunk caching is disabled."); allRegions().forEach(region -> { if (region != null) { @@ -170,7 +170,7 @@ public final class CachedWorld implements ICachedWorld, Helper { * Delete regions that are too far from the player */ private synchronized void prune() { - if (!Baritone.settings().pruneRegionsFromRAM.get()) { + if (!Baritone.settings().pruneRegionsFromRAM.value) { return; } BlockPos pruneCenter = guessPosition(); diff --git a/src/main/java/baritone/cache/ContainerMemory.java b/src/main/java/baritone/cache/ContainerMemory.java index 466bf710..c1cb7b34 100644 --- a/src/main/java/baritone/cache/ContainerMemory.java +++ b/src/main/java/baritone/cache/ContainerMemory.java @@ -70,7 +70,7 @@ public class ContainerMemory implements IContainerMemory { } public synchronized void save() throws IOException { - if (!Baritone.settings().containerMemory.get()) { + if (!Baritone.settings().containerMemory.value) { return; } ByteBuf buf = Unpooled.buffer(0, Integer.MAX_VALUE); diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index fda41cfd..57e9200d 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -62,20 +62,20 @@ public final class AStarPathFinder extends AbstractNodeCostSearch { MutableMoveResult res = new MutableMoveResult(); BetterWorldBorder worldBorder = new BetterWorldBorder(calcContext.world.getWorldBorder()); long startTime = System.currentTimeMillis(); - boolean slowPath = Baritone.settings().slowPath.get(); + boolean slowPath = Baritone.settings().slowPath.value; if (slowPath) { - logDebug("slowPath is on, path timeout will be " + Baritone.settings().slowPathTimeoutMS.get() + "ms instead of " + primaryTimeout + "ms"); + logDebug("slowPath is on, path timeout will be " + Baritone.settings().slowPathTimeoutMS.value + "ms instead of " + primaryTimeout + "ms"); } - long primaryTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.get() : primaryTimeout); - long failureTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.get() : failureTimeout); + long primaryTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.value : primaryTimeout); + long failureTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.value : failureTimeout); boolean failing = true; int numNodes = 0; int numMovementsConsidered = 0; int numEmptyChunk = 0; boolean isFavoring = !favoring.isEmpty(); int timeCheckInterval = 1 << 6; - int pathingMaxChunkBorderFetch = Baritone.settings().pathingMaxChunkBorderFetch.get(); // grab all settings beforehand so that changing settings during pathing doesn't cause a crash or unpredictable behavior - double minimumImprovement = Baritone.settings().minimumImprovementRepropagation.get() ? MIN_IMPROVEMENT : 0; + int pathingMaxChunkBorderFetch = Baritone.settings().pathingMaxChunkBorderFetch.value; // grab all settings beforehand so that changing settings during pathing doesn't cause a crash or unpredictable behavior + double minimumImprovement = Baritone.settings().minimumImprovementRepropagation.value ? MIN_IMPROVEMENT : 0; while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && !cancelRequested) { if ((numNodes & (timeCheckInterval - 1)) == 0) { // only call this once every 64 nodes (about half a millisecond) long now = System.currentTimeMillis(); // since nanoTime is slow on windows (takes many microseconds) @@ -85,7 +85,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch { } if (slowPath) { try { - Thread.sleep(Baritone.settings().slowPathTimeDelayMS.get()); + Thread.sleep(Baritone.settings().slowPathTimeDelayMS.value); } catch (InterruptedException ex) { } } diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index a9974e8d..a7d104cf 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -87,7 +87,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder, Helper { this.startZ = startZ; this.goal = goal; this.context = context; - this.map = new Long2ObjectOpenHashMap<>(Baritone.settings().pathingMapDefaultSize.value, Baritone.settings().pathingMapLoadFactor.get()); + this.map = new Long2ObjectOpenHashMap<>(Baritone.settings().pathingMapDefaultSize.value, Baritone.settings().pathingMapLoadFactor.value); } public void cancel() { diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 4c3b299d..6c4c326b 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -76,27 +76,27 @@ public class CalculationContext { this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld(); this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); // TODO TODO TODO this.toolSet = new ToolSet(player); - this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(baritone.getPlayerContext(), false); - this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether(); - this.canSprint = Baritone.settings().allowSprint.get() && player.getFoodStats().getFoodLevel() > 6; - this.placeBlockCost = Baritone.settings().blockPlacementPenalty.get(); - this.allowBreak = Baritone.settings().allowBreak.get(); - this.allowParkour = Baritone.settings().allowParkour.get(); - this.allowParkourPlace = Baritone.settings().allowParkourPlace.get(); - this.allowJumpAt256 = Baritone.settings().allowJumpAt256.get(); - this.assumeWalkOnWater = Baritone.settings().assumeWalkOnWater.get(); - this.allowDiagonalDescend = Baritone.settings().allowDiagonalDescend.get(); - this.maxFallHeightNoWater = Baritone.settings().maxFallHeightNoWater.get(); - this.maxFallHeightBucket = Baritone.settings().maxFallHeightBucket.get(); + this.hasThrowaway = Baritone.settings().allowPlace.value && MovementHelper.throwaway(baritone.getPlayerContext(), false); + this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.value && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether(); + this.canSprint = Baritone.settings().allowSprint.value && player.getFoodStats().getFoodLevel() > 6; + this.placeBlockCost = Baritone.settings().blockPlacementPenalty.value; + this.allowBreak = Baritone.settings().allowBreak.value; + this.allowParkour = Baritone.settings().allowParkour.value; + this.allowParkourPlace = Baritone.settings().allowParkourPlace.value; + this.allowJumpAt256 = Baritone.settings().allowJumpAt256.value; + this.assumeWalkOnWater = Baritone.settings().assumeWalkOnWater.value; + this.allowDiagonalDescend = Baritone.settings().allowDiagonalDescend.value; + this.maxFallHeightNoWater = Baritone.settings().maxFallHeightNoWater.value; + this.maxFallHeightBucket = Baritone.settings().maxFallHeightBucket.value; int depth = EnchantmentHelper.getDepthStriderModifier(player); if (depth > 3) { depth = 3; } float mult = depth / 3.0F; this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - mult) + ActionCosts.WALK_ONE_BLOCK_COST * mult; - this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.get(); - this.jumpPenalty = Baritone.settings().jumpPenalty.get(); - this.walkOnWaterOnePenalty = Baritone.settings().walkOnWaterOnePenalty.get(); + this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.value; + this.jumpPenalty = Baritone.settings().jumpPenalty.value; + this.walkOnWaterOnePenalty = Baritone.settings().walkOnWaterOnePenalty.value; // why cache these things here, why not let the movements just get directly from settings? // because if some movements are calculated one way and others are calculated another way, // then you get a wildly inconsistent path that isn't optimal for either scenario. diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 592aecd0..7d2552b5 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -113,7 +113,7 @@ public interface MovementHelper extends ActionCosts, Helper { return false; // Don't walk through flowing liquids } if (block instanceof BlockLiquid) { - if (Baritone.settings().assumeWalkOnWater.get()) { + if (Baritone.settings().assumeWalkOnWater.value) { return false; } IBlockState up = bsi.get0(x, y + 1, z); @@ -275,7 +275,7 @@ public interface MovementHelper extends ActionCosts, Helper { if (state.isBlockNormalCube()) { return true; } - if (block == Blocks.LADDER || (block == Blocks.VINE && Baritone.settings().allowVines.get())) { // TODO reconsider this + if (block == Blocks.LADDER || (block == Blocks.VINE && Baritone.settings().allowVines.value)) { // TODO reconsider this return true; } if (block == Blocks.FARMLAND || block == Blocks.GRASS_PATH) { @@ -293,17 +293,17 @@ public interface MovementHelper extends ActionCosts, Helper { } if (isFlowing(x, y, z, state, bsi) || block == Blocks.FLOWING_WATER) { // the only scenario in which we can walk on flowing water is if it's under still water with jesus off - return isWater(up) && !Baritone.settings().assumeWalkOnWater.get(); + return isWater(up) && !Baritone.settings().assumeWalkOnWater.value; } // if assumeWalkOnWater is on, we can only walk on water if there isn't water above it // if assumeWalkOnWater is off, we can only walk on water if there is water above it - return isWater(up) ^ Baritone.settings().assumeWalkOnWater.get(); + return isWater(up) ^ Baritone.settings().assumeWalkOnWater.value; } if (block == Blocks.GLASS || block == Blocks.STAINED_GLASS) { return true; } if (block instanceof BlockSlab) { - if (!Baritone.settings().allowWalkOnBottomSlab.get()) { + if (!Baritone.settings().allowWalkOnBottomSlab.value) { if (((BlockSlab) block).isDouble()) { return true; } @@ -415,14 +415,14 @@ public interface MovementHelper extends ActionCosts, Helper { // and then it's called during execution // since this function is never called during cost calculation, we don't need to migrate // acceptableThrowawayItems to the CalculationContext - if (Baritone.settings().acceptableThrowawayItems.get().contains(item.getItem())) { + if (Baritone.settings().acceptableThrowawayItems.value.contains(item.getItem())) { if (select) { p.inventory.currentItem = i; } return true; } } - if (Baritone.settings().acceptableThrowawayItems.get().contains(p.inventory.offHandInventory.get(0).getItem())) { + if (Baritone.settings().acceptableThrowawayItems.value.contains(p.inventory.offHandInventory.get(0).getItem())) { // main hand takes precedence over off hand // that means that if we have block A selected in main hand and block B in off hand, right clicking places block B // we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 5bb6281f..3dc65990 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -176,7 +176,7 @@ public class MovementAscend extends Movement { return state; // don't jump while walking from a non double slab into a bottom slab } - if (Baritone.settings().assumeStep.get() || ctx.playerFeet().equals(src.up())) { + if (Baritone.settings().assumeStep.value || ctx.playerFeet().equals(src.up())) { // no need to hit space if we're already jumping return state; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index f156ff1b..9761f617 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -182,7 +182,7 @@ public class MovementDiagonal extends Movement { } public boolean sprint() { - if (MovementHelper.isLiquid(ctx, ctx.playerFeet()) && !Baritone.settings().sprintInWater.get()) { + if (MovementHelper.isLiquid(ctx, ctx.playerFeet()) && !Baritone.settings().sprintInWater.value) { return false; } for (int i = 0; i < 4; i++) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 4a5687fd..21783605 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -152,7 +152,7 @@ public class MovementTraverse extends Movement { super.updateState(state); if (state.getStatus() != MovementStatus.RUNNING) { // if the setting is enabled - if (!Baritone.settings().walkWhileBreaking.get()) { + if (!Baritone.settings().walkWhileBreaking.value) { return state; } // and if we're prepping (aka mining the block in front) @@ -241,7 +241,7 @@ public class MovementTraverse extends Movement { BlockPos into = dest.subtract(src).add(dest); Block intoBelow = BlockStateInterface.get(ctx, into).getBlock(); Block intoAbove = BlockStateInterface.get(ctx, into.up()).getBlock(); - if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, ctx.playerFeet()) || Baritone.settings().sprintInWater.get()) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) { + if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, ctx.playerFeet()) || Baritone.settings().sprintInWater.value) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) { state.setInput(Input.SPRINT, true); } Block destDown = BlockStateInterface.get(ctx, dest.down()).getBlock(); @@ -264,12 +264,12 @@ public class MovementTraverse extends Movement { } double dist1 = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); PlaceResult p = MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false); - if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.get()) { + if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.value) { state.setInput(Input.SNEAK, true); } switch (p) { case READY_TO_PLACE: { - if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) { + if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.value) { state.setInput(Input.CLICK_RIGHT, true); } return state; @@ -343,4 +343,4 @@ public class MovementTraverse extends Movement { } return super.prepared(state); } -} \ No newline at end of file +} diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index b025f689..2c2f7ad9 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -229,7 +229,7 @@ public class PathExecutor implements IPathExecutor, Helper { costEstimateIndex = pathPosition; // do this only once, when the movement starts, and deliberately get the cost as cached when this path was calculated, not the cost as it is right now currentMovementOriginalCostEstimate = movement.getCost(); - for (int i = 1; i < Baritone.settings().costVerificationLookahead.get() && pathPosition + i < path.length() - 1; i++) { + for (int i = 1; i < Baritone.settings().costVerificationLookahead.value && pathPosition + i < path.length() - 1; i++) { if (path.movements().get(pathPosition + i).calculateCostWithoutCaching() >= ActionCosts.COST_INF && canCancel) { logDebug("Something has changed in the world and a future movement has become impossible. Cancelling."); cancel(); @@ -243,7 +243,7 @@ public class PathExecutor implements IPathExecutor, Helper { cancel(); return true; } - if (!movement.calculatedWhileLoaded() && currentCost - currentMovementOriginalCostEstimate > Baritone.settings().maxCostIncrease.get() && canCancel) { + if (!movement.calculatedWhileLoaded() && currentCost - currentMovementOriginalCostEstimate > Baritone.settings().maxCostIncrease.value && canCancel) { // don't do this if the movement was calculated while loaded // that means that this isn't a cache error, it's just part of the path interfering with a later part logDebug("Original cost " + currentMovementOriginalCostEstimate + " current cost " + currentCost + ". Cancelling."); @@ -273,7 +273,7 @@ public class PathExecutor implements IPathExecutor, Helper { ctx.player().setSprinting(false); // letting go of control doesn't make you stop sprinting actually } ticksOnCurrent++; - if (ticksOnCurrent > currentMovementOriginalCostEstimate + Baritone.settings().movementTimeoutTicks.get()) { + if (ticksOnCurrent > currentMovementOriginalCostEstimate + Baritone.settings().movementTimeoutTicks.value) { // only cancel if the total time has exceeded the initial estimate // as you break the blocks required, the remaining cost goes down, to the point where // ticksOnCurrent is greater than recalculateCost + 100 @@ -527,7 +527,7 @@ public class PathExecutor implements IPathExecutor, Helper { } private static boolean sprintableAscend(IPlayerContext ctx, MovementTraverse current, MovementAscend next, IMovement nextnext) { - if (!Baritone.settings().sprintAscends.get()) { + if (!Baritone.settings().sprintAscends.value) { return false; } if (!current.getDirection().equals(next.getDirection().down())) { @@ -569,7 +569,7 @@ public class PathExecutor implements IPathExecutor, Helper { if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(ctx, next.getDest().down())) { return true; } - return next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.get(); + return next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.value; } private void onChangeInPathPosition() { @@ -612,8 +612,8 @@ public class PathExecutor implements IPathExecutor, Helper { } private PathExecutor cutIfTooLong() { - if (pathPosition > Baritone.settings().maxPathHistoryLength.get()) { - int cutoffAmt = Baritone.settings().pathHistoryCutoffAmount.get(); + if (pathPosition > Baritone.settings().maxPathHistoryLength.value) { + int cutoffAmt = Baritone.settings().pathHistoryCutoffAmount.value; CutoffPath newPath = new CutoffPath(path, cutoffAmt, path.length() - 1); if (!newPath.getDest().equals(path.getDest())) { throw new IllegalStateException(); diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 3d25c076..6e377dec 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -58,13 +58,13 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo private Goal towards(Entity following) { BlockPos pos; - if (Baritone.settings().followOffsetDistance.get() == 0) { + if (Baritone.settings().followOffsetDistance.value == 0) { pos = new BlockPos(following); } else { - GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.get(), Baritone.settings().followOffsetDistance.get()); + GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.value, Baritone.settings().followOffsetDistance.value); pos = new BlockPos(g.getX(), following.posY, g.getZ()); } - return new GoalNear(pos, Baritone.settings().followRadius.get()); + return new GoalNear(pos, Baritone.settings().followRadius.value); } diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index cb80926b..7f63c6e2 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -67,7 +67,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl rescan(new ArrayList<>(), new CalculationContext(baritone)); } if (knownLocations.isEmpty()) { - if (Baritone.settings().exploreForBlocks.get() && !calcFailed) { + if (Baritone.settings().exploreForBlocks.value && !calcFailed) { return new PathingCommand(new GoalRunAway(1, start) { @Override public boolean isInGoal(int x, int y, int z) { @@ -83,7 +83,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } Goal goal = new GoalComposite(knownLocations.stream().map(this::createGoal).toArray(Goal[]::new)); if (calcFailed) { - if (Baritone.settings().blacklistOnGetToBlockFailure.get()) { + if (Baritone.settings().blacklistOnGetToBlockFailure.value) { logDirect("Unable to find any path to " + gettingTo + ", blacklisting presumably unreachable closest instances"); blacklistClosest(); return onTick(false, isSafeToCancel); // gamer moment @@ -95,7 +95,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl return new PathingCommand(goal, PathingCommandType.CANCEL_AND_SET_GOAL); } } - int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); + int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.value; if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain List current = new ArrayList<>(knownLocations); CalculationContext context = new CalculationContext(baritone, true); @@ -200,14 +200,14 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } private boolean walkIntoInsteadOfAdjacent(Block block) { - if (!Baritone.settings().enterPortal.get()) { + if (!Baritone.settings().enterPortal.value) { return false; } return block == Blocks.PORTAL; } private boolean rightClickOnArrival(Block block) { - if (!Baritone.settings().rightClickContainerOnArrival.get()) { + if (!Baritone.settings().rightClickContainerOnArrival.value) { return false; } return block == Blocks.CRAFTING_TABLE || block == Blocks.FURNACE || block == Blocks.ENDER_CHEST || block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST; diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index ac341cb8..121ddb8f 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -85,13 +85,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro cancel(); return null; } - int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); + int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.value; if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain List curr = new ArrayList<>(knownOreLocations); CalculationContext context = new CalculationContext(baritone, true); Baritone.getExecutor().execute(() -> rescan(curr, context)); } - if (Baritone.settings().legitMine.get()) { + if (Baritone.settings().legitMine.value) { addNearby(); } PathingCommand command = updateGoal(); @@ -115,7 +115,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } private PathingCommand updateGoal() { - boolean legit = Baritone.settings().legitMine.get(); + boolean legit = Baritone.settings().legitMine.value; List locs = knownOreLocations; if (!locs.isEmpty()) { List locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT); @@ -129,7 +129,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return null; } // only in non-Xray mode (aka legit mode) do we do this - int y = Baritone.settings().legitMineYLevel.get(); + int y = Baritone.settings().legitMineYLevel.value; if (branchPoint == null) { /*if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) { // cool, path is over and we are at desired y @@ -157,7 +157,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (mining == null) { return; } - if (Baritone.settings().legitMine.get()) { + if (Baritone.settings().legitMine.value) { return; } List locs = searchWorld(context, mining, ORE_LOCATIONS_COUNT, already); @@ -171,18 +171,18 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } private static Goal coalesce(IPlayerContext ctx, BlockPos loc, List locs) { - if (!Baritone.settings().forceInternalMining.get()) { + if (!Baritone.settings().forceInternalMining.value) { return new GoalTwoBlocks(loc); } // Here, BlockStateInterface is used because the position may be in a cached chunk (the targeted block is one that is kept track of) - boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(ctx, loc.up()) == Blocks.AIR); - boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(ctx, loc.down()) == Blocks.AIR); + boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.value && BlockStateInterface.getBlock(ctx, loc.up()) == Blocks.AIR); + boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.value && BlockStateInterface.getBlock(ctx, loc.down()) == Blocks.AIR); return upwardGoal == downwardGoal ? new GoalTwoBlocks(loc) : upwardGoal ? new GoalBlock(loc) : new GoalBlock(loc.down()); } public static List droppedItemsScan(List mining, World world) { - if (!Baritone.settings().mineScanDroppedItems.get()) { + if (!Baritone.settings().mineScanDroppedItems.value) { return new ArrayList<>(); } Set searchingFor = new HashSet<>(); @@ -211,7 +211,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro for (Block m : mining) { if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(m)) { // maxRegionDistanceSq 2 means adjacent directly or adjacent diagonally; nothing further than that - locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), Baritone.settings().maxCachedWorldScanCount.get(), ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2)); + locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), Baritone.settings().maxCachedWorldScanCount.value, ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2)); } else { uninteresting.add(m); } @@ -242,7 +242,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro // is an x-ray and it'll get caught if (mining.contains(bsi.get0(x, y, z).getBlock())) { BlockPos pos = new BlockPos(x, y, z); - if ((Baritone.settings().legitMineIncludeDiagonals.get() && 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.player(), pos, fakedBlockReachDistance).isPresent()) { knownOreLocations.add(pos); } } diff --git a/src/main/java/baritone/utils/BlockPlaceHelper.java b/src/main/java/baritone/utils/BlockPlaceHelper.java index e93bf807..8e7ef44a 100644 --- a/src/main/java/baritone/utils/BlockPlaceHelper.java +++ b/src/main/java/baritone/utils/BlockPlaceHelper.java @@ -40,7 +40,7 @@ public class BlockPlaceHelper implements Helper { if (!rightClickRequested || ctx.player().isRowingBoat() || mouseOver == null || mouseOver.getBlockPos() == null || mouseOver.typeOfHit != RayTraceResult.Type.BLOCK) { return; } - rightClickTimer = Baritone.settings().rightClickSpeed.get(); + rightClickTimer = Baritone.settings().rightClickSpeed.value; for (EnumHand hand : EnumHand.values()) { if (ctx.playerController().processRightClickBlock(ctx.player(), ctx.world(), mouseOver.getBlockPos(), mouseOver.sideHit, mouseOver.hitVec, hand) == EnumActionResult.SUCCESS) { ctx.player().swingArm(hand); diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 5f8cac6a..84bdce5f 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -66,7 +66,7 @@ public class BlockStateInterface { } else { this.loadedChunks = worldLoaded; // this will only be used on the main thread } - this.useTheRealWorld = !Baritone.settings().pathThroughCachedOnly.get(); + this.useTheRealWorld = !Baritone.settings().pathThroughCachedOnly.value; if (!Minecraft.getMinecraft().isCallingFromMinecraftThread()) { throw new IllegalStateException(); } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 61b9ebf1..7988d796 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -89,14 +89,14 @@ public class ExampleBaritoneControl extends Behavior implements Helper { @Override public void onSendChatMessage(ChatEvent event) { String msg = event.getMessage(); - if (Baritone.settings().prefixControl.get() && msg.startsWith(COMMAND_PREFIX)) { + if (Baritone.settings().prefixControl.value && msg.startsWith(COMMAND_PREFIX)) { if (!runCommand(msg.substring(COMMAND_PREFIX.length()))) { logDirect("Invalid command"); } event.cancel(); // always cancel if using prefixControl return; } - if (!Baritone.settings().chatControl.get() && !Baritone.settings().removePrefix.get()) { + if (!Baritone.settings().chatControl.value && !Baritone.settings().removePrefix.value) { return; } if (runCommand(msg)) { diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index f85f240c..7bcc605c 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -50,7 +50,7 @@ public interface Helper { * @param message The message to display in chat */ default void logDebug(String message) { - if (!Baritone.settings().chatDebug.get()) { + if (!Baritone.settings().chatDebug.value) { //System.out.println("Suppressed debug message:"); //System.out.println(message); return; @@ -67,6 +67,6 @@ public interface Helper { ITextComponent component = MESSAGE_PREFIX.createCopy(); component.getStyle().setColor(TextFormatting.GRAY); component.appendSibling(new TextComponentString(" " + message)); - Minecraft.getMinecraft().addScheduledTask(() -> Baritone.settings().logger.get().accept(component)); + Minecraft.getMinecraft().addScheduledTask(() -> Baritone.settings().logger.value.accept(component)); } } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index c0af870e..e3da0e3e 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -81,9 +81,9 @@ public final class PathRenderer implements Helper { } if (goal != null && Baritone.settings().renderGoal.value) { - drawDankLitGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.get()); + drawDankLitGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.value); } - if (!Baritone.settings().renderPath.get()) { + if (!Baritone.settings().renderPath.value) { return; } @@ -97,28 +97,28 @@ public final class PathRenderer implements Helper { // Render the current path, if there is one if (current != null && current.getPath() != null) { int renderBegin = Math.max(current.getPosition() - 3, 0); - drawPath(current.getPath(), renderBegin, renderView, partialTicks, Baritone.settings().colorCurrentPath.get(), Baritone.settings().fadePath.get(), 10, 20); + drawPath(current.getPath(), renderBegin, renderView, partialTicks, Baritone.settings().colorCurrentPath.value, Baritone.settings().fadePath.value, 10, 20); } if (next != null && next.getPath() != null) { - drawPath(next.getPath(), 0, renderView, partialTicks, Baritone.settings().colorNextPath.get(), Baritone.settings().fadePath.get(), 10, 20); + drawPath(next.getPath(), 0, renderView, partialTicks, Baritone.settings().colorNextPath.value, Baritone.settings().fadePath.value, 10, 20); } //long split = System.nanoTime(); if (current != null) { - drawManySelectionBoxes(renderView, current.toBreak(), Baritone.settings().colorBlocksToBreak.get()); - drawManySelectionBoxes(renderView, current.toPlace(), Baritone.settings().colorBlocksToPlace.get()); - drawManySelectionBoxes(renderView, current.toWalkInto(), Baritone.settings().colorBlocksToWalkInto.get()); + drawManySelectionBoxes(renderView, current.toBreak(), Baritone.settings().colorBlocksToBreak.value); + drawManySelectionBoxes(renderView, current.toPlace(), Baritone.settings().colorBlocksToPlace.value); + drawManySelectionBoxes(renderView, current.toWalkInto(), Baritone.settings().colorBlocksToWalkInto.value); } // If there is a path calculation currently running, render the path calculation process behavior.getInProgress().ifPresent(currentlyRunning -> { currentlyRunning.bestPathSoFar().ifPresent(p -> { - drawPath(p, 0, renderView, partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20); + drawPath(p, 0, renderView, partialTicks, Baritone.settings().colorBestPathSoFar.value, Baritone.settings().fadePath.value, 10, 20); }); currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { - drawPath(mr, 0, renderView, partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); - drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), Baritone.settings().colorMostRecentConsidered.get()); + drawPath(mr, 0, renderView, partialTicks, Baritone.settings().colorMostRecentConsidered.value, Baritone.settings().fadePath.value, 10, 20); + drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), Baritone.settings().colorMostRecentConsidered.value); }); }); //long end = System.nanoTime(); @@ -132,10 +132,10 @@ public final class PathRenderer implements Helper { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F); - GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); + GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); - if (Baritone.settings().renderPathIgnoreDepth.get()) { + if (Baritone.settings().renderPathIgnoreDepth.value) { GlStateManager.disableDepth(); } List positions = path.positions(); @@ -178,7 +178,7 @@ public final class PathRenderer implements Helper { drawLine(player, x1, y1, z1, x2, y2, z2); tessellator.draw(); } - if (Baritone.settings().renderPathIgnoreDepth.get()) { + if (Baritone.settings().renderPathIgnoreDepth.value) { GlStateManager.enableDepth(); } //GlStateManager.color(0.0f, 0.0f, 0.0f, 0.4f); @@ -203,11 +203,11 @@ public final class PathRenderer implements Helper { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F); - GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); + GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); - if (Baritone.settings().renderSelectionBoxesIgnoreDepth.get()) { + if (Baritone.settings().renderSelectionBoxesIgnoreDepth.value) { GlStateManager.disableDepth(); } @@ -249,7 +249,7 @@ public final class PathRenderer implements Helper { TESSELLATOR.draw(); }); - if (Baritone.settings().renderSelectionBoxesIgnoreDepth.get()) { + if (Baritone.settings().renderSelectionBoxesIgnoreDepth.value) { GlStateManager.enableDepth(); } @@ -292,12 +292,12 @@ public final class PathRenderer implements Helper { } else if (goal instanceof GoalXZ) { GoalXZ goalPos = (GoalXZ) goal; - if (Baritone.settings().renderGoalXZBeacon.get()) { + if (Baritone.settings().renderGoalXZBeacon.value) { glPushAttrib(GL_LIGHTING_BIT); mc.getTextureManager().bindTexture(TileEntityBeaconRenderer.TEXTURE_BEACON_BEAM); - if (Baritone.settings().renderGoalIgnoreDepth.get()) { + if (Baritone.settings().renderGoalIgnoreDepth.value) { GlStateManager.disableDepth(); } @@ -313,7 +313,7 @@ public final class PathRenderer implements Helper { color.getColorComponents(null) ); - if (Baritone.settings().renderGoalIgnoreDepth.get()) { + if (Baritone.settings().renderGoalIgnoreDepth.value) { GlStateManager.enableDepth(); } @@ -342,10 +342,10 @@ public final class PathRenderer implements Helper { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.6F); - GlStateManager.glLineWidth(Baritone.settings().goalRenderLineWidthPixels.get()); + GlStateManager.glLineWidth(Baritone.settings().goalRenderLineWidthPixels.value); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); - if (Baritone.settings().renderGoalIgnoreDepth.get()) { + if (Baritone.settings().renderGoalIgnoreDepth.value) { GlStateManager.disableDepth(); } @@ -363,7 +363,7 @@ public final class PathRenderer implements Helper { BUFFER.pos(minX, maxY, maxZ).endVertex(); TESSELLATOR.draw(); - if (Baritone.settings().renderGoalIgnoreDepth.get()) { + if (Baritone.settings().renderGoalIgnoreDepth.value) { GlStateManager.enableDepth(); } GlStateManager.depthMask(true); diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 54ed848a..8d1616c4 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -136,7 +136,7 @@ public class PathingControlManager implements IPathingControlManager { p.secretInternalSetGoalAndPath(command.goal); break; case REVALIDATE_GOAL_AND_PATH: - if (Baritone.settings().cancelOnGoalInvalidation.get() && (command.goal == null || revalidateGoal(command.goal))) { + if (Baritone.settings().cancelOnGoalInvalidation.value && (command.goal == null || revalidateGoal(command.goal))) { p.softCancelIfSafe(); } p.secretInternalSetGoalAndPath(command.goal); diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index bfa4e251..31f23f20 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -55,7 +55,7 @@ public class ToolSet { breakStrengthCache = new HashMap<>(); this.player = player; - if (Baritone.settings().considerPotionEffects.get()) { + if (Baritone.settings().considerPotionEffects.value) { double amplifier = potionAmplifier(); Function amplify = x -> amplifier * x; backendCalculation = amplify.compose(this::getBestDestructionTime); diff --git a/src/main/java/baritone/utils/pathing/Avoidance.java b/src/main/java/baritone/utils/pathing/Avoidance.java index 1f61dc57..9b32b1df 100644 --- a/src/main/java/baritone/utils/pathing/Avoidance.java +++ b/src/main/java/baritone/utils/pathing/Avoidance.java @@ -57,17 +57,17 @@ public class Avoidance { } public static List create(IPlayerContext ctx) { - if (!Baritone.settings().avoidance.get()) { + if (!Baritone.settings().avoidance.value) { return Collections.emptyList(); } List res = new ArrayList<>(); - double mobSpawnerCoeff = Baritone.settings().mobSpawnerAvoidanceCoefficient.get(); - double mobCoeff = Baritone.settings().mobAvoidanceCoefficient.get(); + double mobSpawnerCoeff = Baritone.settings().mobSpawnerAvoidanceCoefficient.value; + double mobCoeff = Baritone.settings().mobAvoidanceCoefficient.value; if (mobSpawnerCoeff != 1.0D) { - ctx.worldData().getCachedWorld().getLocationsOf("mob_spawner", 1, ctx.playerFeet().x, ctx.playerFeet().z, 2).forEach(mobspawner -> res.add(new Avoidance(mobspawner, mobSpawnerCoeff, Baritone.settings().mobSpawnerAvoidanceRadius.get()))); + ctx.worldData().getCachedWorld().getLocationsOf("mob_spawner", 1, ctx.playerFeet().x, ctx.playerFeet().z, 2).forEach(mobspawner -> res.add(new Avoidance(mobspawner, mobSpawnerCoeff, Baritone.settings().mobSpawnerAvoidanceRadius.value))); } if (mobCoeff != 1.0D) { - ctx.world().loadedEntityList.stream().filter(entity -> entity instanceof EntityMob).forEach(entity -> res.add(new Avoidance(new BlockPos(entity), mobCoeff, Baritone.settings().mobAvoidanceRadius.get()))); + ctx.world().loadedEntityList.stream().filter(entity -> entity instanceof EntityMob).forEach(entity -> res.add(new Avoidance(new BlockPos(entity), mobCoeff, Baritone.settings().mobAvoidanceRadius.value))); } return res; } diff --git a/src/main/java/baritone/utils/pathing/Favoring.java b/src/main/java/baritone/utils/pathing/Favoring.java index 7ffe49ff..45bb8a09 100644 --- a/src/main/java/baritone/utils/pathing/Favoring.java +++ b/src/main/java/baritone/utils/pathing/Favoring.java @@ -37,7 +37,7 @@ public final class Favoring { public Favoring(IPath previous) { // create one just from previous path, no mob avoidances favorings = new Long2DoubleOpenHashMap(); favorings.defaultReturnValue(1.0D); - double coeff = Baritone.settings().backtrackCostFavoringCoefficient.get(); + double coeff = Baritone.settings().backtrackCostFavoringCoefficient.value; if (coeff != 1D && previous != null) { previous.positions().forEach(pos -> favorings.put(BetterBlockPos.longHash(pos), coeff)); } diff --git a/src/main/java/baritone/utils/pathing/PathBase.java b/src/main/java/baritone/utils/pathing/PathBase.java index 3acf80b4..8bac2dc7 100644 --- a/src/main/java/baritone/utils/pathing/PathBase.java +++ b/src/main/java/baritone/utils/pathing/PathBase.java @@ -28,7 +28,7 @@ import net.minecraft.util.math.BlockPos; public abstract class PathBase implements IPath { @Override public PathBase cutoffAtLoadedChunks(Object bsi0) { // <-- cursed cursed cursed - if (!Baritone.settings().cutoffAtLoadBoundary.get()) { + if (!Baritone.settings().cutoffAtLoadBoundary.value) { return this; } BlockStateInterface bsi = (BlockStateInterface) bsi0; @@ -43,14 +43,14 @@ public abstract class PathBase implements IPath { @Override public PathBase staticCutoff(Goal destination) { - int min = BaritoneAPI.getSettings().pathCutoffMinimumLength.get(); + int min = BaritoneAPI.getSettings().pathCutoffMinimumLength.value; if (length() < min) { return this; } if (destination == null || destination.isInGoal(getDest())) { return this; } - double factor = BaritoneAPI.getSettings().pathCutoffFactor.get(); + double factor = BaritoneAPI.getSettings().pathCutoffFactor.value; int newLength = (int) ((length() - min) * factor) + min - 1; return new CutoffPath(this, newLength); } diff --git a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java index e1d6dd10..489d560d 100644 --- a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java +++ b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java @@ -88,7 +88,7 @@ public class SegmentedCalculator { private PathCalculationResult segment(Optional previous) { BetterBlockPos segmentStart = previous.map(IPath::getDest).orElse(start); // <-- e p i c AbstractNodeCostSearch search = new AStarPathFinder(segmentStart.x, segmentStart.y, segmentStart.z, goal, new Favoring(previous.orElse(null)), context); // this is on another thread, so cannot include mob avoidances. - return search.calculate(Baritone.settings().primaryTimeoutMS.get(), Baritone.settings().failureTimeoutMS.get()); // use normal time settings, not the plan ahead settings, so as to not overwhelm the computer + return search.calculate(Baritone.settings().primaryTimeoutMS.value, Baritone.settings().failureTimeoutMS.value); // use normal time settings, not the plan ahead settings, so as to not overwhelm the computer } public static void calculateSegmentsThreaded(BetterBlockPos start, Goal goal, CalculationContext context, Consumer onCompletion, Runnable onFailure) { From b3c580e657218a18d2fdeb920ab7608a39256e92 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 21:49:21 -0800 Subject: [PATCH 251/682] teensy javadoc --- src/api/java/baritone/api/Settings.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index bdebd117..0e31d942 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -721,6 +721,11 @@ public final class Settings { this.klass = (Class) value.getClass(); } + /** + * Deprecated! Please use .value directly instead + * + * @return the current setting value + */ @Deprecated public final T get() { return value; @@ -739,6 +744,9 @@ public final class Settings { return SettingsUtil.settingToString(this); } + /** + * Reset this setting to its default value + */ public void reset() { value = defaultValue; } From 74d7483b3c228ab464c16ff4b4005df2a568ffee Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 5 Mar 2019 12:26:52 -0800 Subject: [PATCH 252/682] explore --- src/api/java/baritone/api/Settings.java | 7 ++ src/main/java/baritone/Baritone.java | 11 +- src/main/java/baritone/cache/CachedWorld.java | 4 + .../java/baritone/process/ExploreProcess.java | 100 ++++++++++++++++++ .../utils/ExampleBaritoneControl.java | 15 +++ 5 files changed, 133 insertions(+), 4 deletions(-) create mode 100644 src/main/java/baritone/process/ExploreProcess.java diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 0e31d942..b9a45960 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -625,6 +625,13 @@ public final class Settings { */ public final Setting followRadius = new Setting<>(3); + /** + * true = exploration uses pythagorean distance to choose closest uncached chunk + *

+ * false = exploration uses manhattan / taxicab distance to choose + */ + public final Setting exploreUsePythagorean = new Setting<>(false); + /** * Cached chunks (regardless of if they're in RAM or saved to disk) expire and are deleted after this number of seconds * -1 to disable diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 51a6ff69..ea8d40f2 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -25,10 +25,7 @@ import baritone.api.utils.IPlayerContext; import baritone.behavior.*; import baritone.cache.WorldProvider; import baritone.event.GameEventHandler; -import baritone.process.CustomGoalProcess; -import baritone.process.FollowProcess; -import baritone.process.GetToBlockProcess; -import baritone.process.MineProcess; +import baritone.process.*; import baritone.utils.*; import baritone.utils.player.PrimaryPlayerContext; import net.minecraft.client.Minecraft; @@ -80,6 +77,7 @@ public class Baritone implements IBaritone { private MineProcess mineProcess; private GetToBlockProcess getToBlockProcess; private CustomGoalProcess customGoalProcess; + private ExploreProcess exploreProcess; private PathingControlManager pathingControlManager; @@ -118,6 +116,7 @@ public class Baritone implements IBaritone { mineProcess = new MineProcess(this); customGoalProcess = new CustomGoalProcess(this); // very high iq getToBlockProcess = new GetToBlockProcess(this); + exploreProcess = new ExploreProcess(this); } this.worldProvider = new WorldProvider(); @@ -177,6 +176,10 @@ public class Baritone implements IBaritone { return this.lookBehavior; } + public ExploreProcess getExploreProcess() { + return this.exploreProcess; + } + @Override public MineProcess getMineProcess() { return this.mineProcess; diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index e8ea5cae..7e34fa08 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -107,6 +107,10 @@ public final class CachedWorld implements ICachedWorld, Helper { return region.isCached(blockX & 511, blockZ & 511); } + public final boolean regionLoaded(int blockX, int blockZ) { + return getRegion(blockX >> 9, blockZ >> 9) != null; + } + @Override public final ArrayList getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq) { ArrayList res = new ArrayList<>(); diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java new file mode 100644 index 00000000..3f8d0f82 --- /dev/null +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -0,0 +1,100 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.cache.ICachedWorld; +import baritone.api.pathing.goals.GoalXZ; +import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.cache.CachedWorld; +import baritone.utils.BaritoneProcessHelper; +import net.minecraft.util.math.BlockPos; + +public class ExploreProcess extends BaritoneProcessHelper { + + private BlockPos explorationOrigin; + + public ExploreProcess(Baritone baritone) { + super(baritone, 0); + } + + @Override + public boolean isActive() { + return explorationOrigin != null; + } + + public void explore(int centerX, int centerZ) { + explorationOrigin = new BlockPos(centerX, 0, centerZ); + } + + @Override + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + if (calcFailed) { + logDirect("Failed"); + onLostControl(); + return null; + } + BlockPos closestUncached = closestUncachedChunk(explorationOrigin); + if (closestUncached == null) { + logDebug("awaiting region load from disk"); + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + System.out.println("Closest uncached: " + closestUncached); + return new PathingCommand(new GoalXZ(closestUncached.getX(), closestUncached.getZ()), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); + } + + private BlockPos closestUncachedChunk(BlockPos pos) { + int chunkX = pos.getX() >> 4; + int chunkZ = pos.getZ() >> 4; + ICachedWorld cache = baritone.getWorldProvider().getCurrentWorld().getCachedWorld(); + for (int dist = 0; ; dist++) { + for (int dx = -dist; dx <= dist; dx++) { + for (int dz = -dist; dz <= dist; dz++) { + int trueDist = Baritone.settings().exploreUsePythagorean.value ? dx * dx + dz + dz : Math.abs(dx) + Math.abs(dz); + if (trueDist != dist) { + continue; // not considering this one just yet in our expanding search + } + int centerX = (chunkX + dx) * 16 + 8; + int centerZ = (chunkZ + dz) * 18 + 8; + + if (cache.isCached(centerX, centerZ)) { + continue; + } + if (!((CachedWorld) cache).regionLoaded(centerX, centerZ)) { + Baritone.getExecutor().execute(() -> { + ((CachedWorld) cache).tryLoadFromDisk(centerX >> 9, centerZ >> 9); + }); + return null; // we still need to load regions from disk in order to decide properly + } + return new BlockPos(centerX, 0, centerZ); + } + } + } + } + + @Override + public void onLostControl() { + explorationOrigin = null; + } + + @Override + public String displayName() { + return "Exploring around " + explorationOrigin + ", currently going to " + closestUncachedChunk(explorationOrigin); + } +} diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 7988d796..89aa0fb5 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -374,6 +374,21 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("ok"); return true; } + if (msg.startsWith("explore")) { + String rest = msg.substring("explore".length()).trim(); + int centerX; + int centerZ; + try { + centerX = Integer.parseInt(rest.split(" ")[0]); + centerZ = Integer.parseInt(rest.split(" ")[1]); + } catch (Exception ex) { + centerX = ctx.playerFeet().x; + centerZ = ctx.playerFeet().z; + } + baritone.getExploreProcess().explore(centerX, centerZ); + logDirect("Exploring from " + centerX + "," + centerZ); + return true; + } if (msg.startsWith("find")) { String blockType = msg.substring(4).trim(); ArrayList locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4); From d80ae57964f0175fa8c8b1c83482f73b4e71c3f4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 6 Mar 2019 22:44:57 -0800 Subject: [PATCH 253/682] disconnect on arrival --- src/api/java/baritone/api/Settings.java | 5 +++++ src/main/java/baritone/behavior/PathingBehavior.java | 3 +++ 2 files changed, 8 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index b9a45960..99fe5241 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -570,6 +570,11 @@ public final class Settings { */ public final Setting axisHeight = new Setting<>(120); + /** + * Disconnect from the server upon arriving at your goal + */ + public final Setting disconnectOnArrival = new Setting<>(false); + /** * Disallow MineBehavior from using X-Ray to see where the ores are. Turn this option on to force it to mine "legit" * where it will only mine an ore once it can actually see it, so it won't do or know anything that a normal player diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index a7c5c34b..915e5066 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -141,6 +141,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, logDebug("All done. At " + goal); queuePathEvent(PathEvent.AT_GOAL); next = null; + if (Baritone.settings().disconnectOnArrival.value) { + ctx.world().sendQuittingDisconnectingPacket(); + } return; } if (next != null && !next.getPath().positions().contains(ctx.playerFeet()) && !next.getPath().positions().contains(expectedSegmentStart)) { // can contain either one From d90f391b5e9dae3fc99ef371fcc70fb442f0678e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Mar 2019 18:18:31 -0800 Subject: [PATCH 254/682] 7 lmao --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 68654701..9216add1 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Baritone is the pathfinding system used in [Impact](https://impactdevelopment.gi This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). -Have committed at least once a day for the last 6 months =D 🦀 +Have committed at least once a day for the last 7 months =D 🦀 1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2 From 76297e817669c4757cf9f8a2304cf953c506fb5f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 8 Mar 2019 08:43:28 -0800 Subject: [PATCH 255/682] add click to usage --- USAGE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/USAGE.md b/USAGE.md index 6a07518b..2750ac78 100644 --- a/USAGE.md +++ b/USAGE.md @@ -34,6 +34,7 @@ Some common examples: - `cancel` or `stop` to stop everything - `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part) - `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) +- `click` to click your destination on the screen. left click to path into it, right click to path on top of it. - `follow playerName` to follow a player. `follow` to follow the entity you're looking at (only works if it hitting range). `followplayers` to follow any players in range (combine with Kill Aura for a fun time). - `save waypointName` to save a waypoint. `goto waypointName` to go to it. - `axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120). From ecac546c6d7ebc3191681c82c9ae70d501f4d176 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 9 Mar 2019 23:15:03 -0800 Subject: [PATCH 256/682] actually trolling is fine --- CODE_OF_CONDUCT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 8811361f..ae74fc3e 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -26,7 +26,7 @@ Examples of unacceptable behavior by participants include: * Anime * The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks +* ~~Trolling, insulting/derogatory comments, and personal or political attacks~~ * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission From d144d308908ec356aae4a77c0a329652b13d5567 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 10 Mar 2019 23:43:00 -0700 Subject: [PATCH 257/682] crucial clarification --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9216add1..02ed2bc5 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ A Minecraft pathfinder bot. Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), -the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). +the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2. 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). Have committed at least once a day for the last 7 months =D 🦀 From 580af2ab065605cfc42e49bd7666050980215c74 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Mar 2019 18:24:31 -0700 Subject: [PATCH 258/682] processes tied in priority --- .../api/process/IBaritoneProcess.java | 14 +++++++++- .../baritone/api/process/PathingCommand.java | 5 ++++ .../movement/movements/MovementAscend.java | 4 +++ .../movement/movements/MovementPillar.java | 4 +++ .../baritone/process/CustomGoalProcess.java | 10 +++---- .../java/baritone/process/ExploreProcess.java | 2 +- .../java/baritone/process/FollowProcess.java | 2 +- .../baritone/process/GetToBlockProcess.java | 7 +++-- .../java/baritone/process/MineProcess.java | 2 +- .../baritone/utils/BaritoneProcessHelper.java | 9 +----- .../utils/ExampleBaritoneControl.java | 15 ++++++++++ .../baritone/utils/PathingControlManager.java | 28 +++++++++++++------ 12 files changed, 73 insertions(+), 29 deletions(-) diff --git a/src/api/java/baritone/api/process/IBaritoneProcess.java b/src/api/java/baritone/api/process/IBaritoneProcess.java index 01e833c0..0339179c 100644 --- a/src/api/java/baritone/api/process/IBaritoneProcess.java +++ b/src/api/java/baritone/api/process/IBaritoneProcess.java @@ -35,6 +35,16 @@ import baritone.api.event.events.PathEvent; */ public interface IBaritoneProcess { + /** + * Default priority. Most normal processes should have this value. + *

+ * Some examples of processes that should have different values might include some kind of automated mob avoidance + * that would be temporary and would forcefully take control. Same for something that pauses pathing for auto eat, etc. + *

+ * The value is -1 beacuse that's what Impact 4.5's beta auto walk returns and I want to tie with it. + */ + double DEFAULT_PRIORITY = -1; + /** * Would this process like to be in control? * @@ -82,7 +92,9 @@ public interface IBaritoneProcess { * * @return A double representing the priority */ - double priority(); + default double priority() { + return DEFAULT_PRIORITY; + } /** * Returns a user-friendly name for this process. Suitable for a HUD. diff --git a/src/api/java/baritone/api/process/PathingCommand.java b/src/api/java/baritone/api/process/PathingCommand.java index 2caef158..61445f8a 100644 --- a/src/api/java/baritone/api/process/PathingCommand.java +++ b/src/api/java/baritone/api/process/PathingCommand.java @@ -53,4 +53,9 @@ public class PathingCommand { this.goal = goal; this.commandType = commandType; } + + @Override + public String toString() { + return commandType + " " + goal; + } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 3dc65990..d3ef9def 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -155,6 +155,10 @@ public class MovementAscend extends Movement { return state.setStatus(MovementStatus.SUCCESS); } + if (ctx.playerFeet().y < src.y) { + return state.setStatus(MovementStatus.UNREACHABLE); + } + IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace); if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) { ticksWithoutPlacement++; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 1bbfa6f9..e899ce63 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -148,6 +148,10 @@ public class MovementPillar extends Movement { return state; } + if (ctx.playerFeet().y < src.y) { + return state.setStatus(MovementStatus.UNREACHABLE); + } + IBlockState fromDown = BlockStateInterface.get(ctx, src); if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(ctx, dest)) { // stay centered while swimming up a water column diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index a6234227..2c8a3c33 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -24,8 +24,6 @@ import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; import baritone.utils.BaritoneProcessHelper; -import java.util.Objects; - /** * As set by ExampleBaritoneControl or something idk * @@ -46,7 +44,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG private State state; public CustomGoalProcess(Baritone baritone) { - super(baritone, 3); + super(baritone); } @Override @@ -79,20 +77,20 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { switch (this.state) { case GOAL_SET: - if (!baritone.getPathingBehavior().isPathing() && Objects.equals(baritone.getPathingBehavior().getGoal() + "", this.goal + "")) { - this.state = State.NONE; - } return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL); case PATH_REQUESTED: + // return FORCE_REVALIDATE_GOAL_AND_PATH just once PathingCommand ret = new PathingCommand(this.goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); this.state = State.EXECUTING; return ret; case EXECUTING: if (calcFailed) { onLostControl(); + return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL); } if (this.goal == null || this.goal.isInGoal(ctx.playerFeet())) { onLostControl(); // we're there xd + return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL); } return new PathingCommand(this.goal, PathingCommandType.SET_GOAL_AND_PATH); default: diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 3f8d0f82..3343d882 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -31,7 +31,7 @@ public class ExploreProcess extends BaritoneProcessHelper { private BlockPos explorationOrigin; public ExploreProcess(Baritone baritone) { - super(baritone, 0); + super(baritone); } @Override diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 6e377dec..04e80e03 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -46,7 +46,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo private List cache; public FollowProcess(Baritone baritone) { - super(baritone, 1); + super(baritone); } @Override diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 7f63c6e2..4a2aa3e2 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -44,7 +44,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl private int tickCount = 0; public GetToBlockProcess(Baritone baritone) { - super(baritone, 2); + super(baritone); } @Override @@ -161,7 +161,10 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl @Override public String displayName() { - return "Get To Block " + gettingTo; + if (knownLocations.isEmpty()) { + return "Exploring randomly to find " + gettingTo + ", no known locations"; + } + return "Get To Block " + gettingTo + ", " + knownLocations.size() + " known locations"; } private synchronized void rescan(List known, CalculationContext context) { diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 121ddb8f..495fb0ee 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -60,7 +60,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro private int tickCount; public MineProcess(Baritone baritone) { - super(baritone, 0); + super(baritone); } @Override diff --git a/src/main/java/baritone/utils/BaritoneProcessHelper.java b/src/main/java/baritone/utils/BaritoneProcessHelper.java index 1a66eaa5..61c2fd44 100644 --- a/src/main/java/baritone/utils/BaritoneProcessHelper.java +++ b/src/main/java/baritone/utils/BaritoneProcessHelper.java @@ -25,12 +25,10 @@ public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper protected final Baritone baritone; protected final IPlayerContext ctx; - private final double priority; - public BaritoneProcessHelper(Baritone baritone, double priority) { + public BaritoneProcessHelper(Baritone baritone) { this.baritone = baritone; this.ctx = baritone.getPlayerContext(); - this.priority = priority; baritone.getPathingControlManager().registerProcess(this); } @@ -38,9 +36,4 @@ public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper public boolean isTemporary() { return false; } - - @Override - public double priority() { - return priority; - } } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 89aa0fb5..ca88a828 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -24,6 +24,7 @@ import baritone.api.cache.IWaypoint; import baritone.api.event.events.ChatEvent; import baritone.api.pathing.goals.*; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.process.IBaritoneProcess; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.SettingsUtil; import baritone.behavior.Behavior; @@ -225,6 +226,20 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } return true; } + if (msg.equals("proc")) { + Optional proc = baritone.getPathingControlManager().mostRecentInControl(); + if (!proc.isPresent()) { + logDirect("No process is in control"); + return true; + } + IBaritoneProcess p = proc.get(); + logDirect("Class: " + p.getClass()); + logDirect("Priority: " + p.priority()); + logDirect("Temporary: " + p.isTemporary()); + logDirect("Display name: " + p.displayName()); + logDirect("Command: " + baritone.getPathingControlManager().mostRecentCommand()); + return true; + } if (msg.equals("version")) { String version = ExampleBaritoneControl.class.getPackage().getImplementationVersion(); if (version == null) { diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 8d1616c4..a01a1036 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -29,11 +29,11 @@ import baritone.pathing.path.PathExecutor; import net.minecraft.util.math.BlockPos; import java.util.*; -import java.util.stream.Stream; public class PathingControlManager implements IPathingControlManager { private final Baritone baritone; private final HashSet processes; // unGh + private final List active; private IBaritoneProcess inControlLastTick; private IBaritoneProcess inControlThisTick; private PathingCommand command; @@ -41,13 +41,13 @@ public class PathingControlManager implements IPathingControlManager { public PathingControlManager(Baritone baritone) { this.baritone = baritone; this.processes = new HashSet<>(); + this.active = new ArrayList<>(); baritone.getGameEventHandler().registerEventListener(new AbstractGameEventListener() { // needs to be after all behavior ticks @Override public void onTick(TickEvent event) { - if (event.getType() == TickEvent.Type.OUT) { - return; + if (event.getType() == TickEvent.Type.IN) { + postTick(); } - postTick(); } }); } @@ -62,6 +62,7 @@ public class PathingControlManager implements IPathingControlManager { inControlLastTick = null; inControlThisTick = null; command = null; + active.clear(); for (IBaritoneProcess proc : processes) { proc.onLostControl(); if (proc.isActive() && !proc.isTemporary()) { // it's okay only for a temporary thing (like combat pause) to maintain control even if you say to cancel @@ -87,6 +88,7 @@ public class PathingControlManager implements IPathingControlManager { command = executeProcesses(); if (command == null) { p.cancelSegmentIfSafe(); + p.secretInternalSetGoal(null); return; } switch (command.commandType) { @@ -172,12 +174,20 @@ public class PathingControlManager implements IPathingControlManager { public PathingCommand executeProcesses() { - Stream inContention = processes.stream() - .filter(IBaritoneProcess::isActive) - .sorted(Comparator.comparingDouble(IBaritoneProcess::priority).reversed()); + for (IBaritoneProcess process : processes) { + if (process.isActive()) { + if (!active.contains(process)) { + // put a newly active process at the very front of the queue + active.add(0, process); + } + } else { + active.remove(process); + } + } + // ties are broken by which was added to the beginning of the list first + active.sort(Comparator.comparingDouble(IBaritoneProcess::priority).reversed()); - - Iterator iterator = inContention.iterator(); + Iterator iterator = active.iterator(); while (iterator.hasNext()) { IBaritoneProcess proc = iterator.next(); From 6b7aca308191f33925c05ebea196b9c1fb863161 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Mar 2019 19:23:41 -0700 Subject: [PATCH 259/682] force revalidate on control change --- src/main/java/baritone/utils/PathingControlManager.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index a01a1036..addcc791 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -24,6 +24,7 @@ import baritone.api.pathing.calc.IPathingControlManager; import baritone.api.pathing.goals.Goal; import baritone.api.process.IBaritoneProcess; import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; import baritone.behavior.PathingBehavior; import baritone.pathing.path.PathExecutor; import net.minecraft.util.math.BlockPos; @@ -91,6 +92,11 @@ public class PathingControlManager implements IPathingControlManager { p.secretInternalSetGoal(null); return; } + if (inControlThisTick != inControlLastTick && command.commandType != PathingCommandType.REQUEST_PAUSE) { + // if control has changed, and the new process wants to do something + p.cancelSegmentIfSafe(); + // get rid of the in progress stuff from the last process + } switch (command.commandType) { case REQUEST_PAUSE: p.requestPause(); From 7cfa8376042e85c4f7e95e81cf51d39076ab0186 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Mar 2019 20:06:19 -0700 Subject: [PATCH 260/682] blacklistClosestOnFailure --- src/api/java/baritone/api/Settings.java | 8 ++++--- .../baritone/process/GetToBlockProcess.java | 4 ++-- .../java/baritone/process/MineProcess.java | 24 +++++++++++++------ 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 99fe5241..c70d60de 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -485,10 +485,12 @@ public final class Settings { public final Setting sprintInWater = new Setting<>(true); /** - * When GetToBlockProcess fails to calculate a path, instead of just giving up, mark the closest instances - * of that block as "unreachable" and go towards the next closest + * When GetToBlockProcess or MineProcess fails to calculate a path, instead of just giving up, mark the closest instance + * of that block as "unreachable" and go towards the next closest. GetToBlock expands this seaarch to the whole "vein"; MineProcess does not. + * This is because MineProcess finds individual impossible blocks (like one block in a vein that has gravel on top then lava, so it can't break) + * Whereas GetToBlock should blacklist the whole "vein" if it can't get to any of them. */ - public final Setting blacklistOnGetToBlockFailure = new Setting<>(true); + public final Setting blacklistClosestOnFailure = new Setting<>(true); /** * 😎 Render cached chunks as semitransparent. Doesn't work with OptiFine 😭 Rarely randomly crashes, see this issue. diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 4a2aa3e2..caebc865 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -83,7 +83,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } Goal goal = new GoalComposite(knownLocations.stream().map(this::createGoal).toArray(Goal[]::new)); if (calcFailed) { - if (Baritone.settings().blacklistOnGetToBlockFailure.value) { + if (Baritone.settings().blacklistClosestOnFailure.value) { logDirect("Unable to find any path to " + gettingTo + ", blacklisting presumably unreachable closest instances"); blacklistClosest(); return onTick(false, isSafeToCancel); // gamer moment @@ -168,7 +168,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } private synchronized void rescan(List known, CalculationContext context) { - List positions = MineProcess.searchWorld(context, Collections.singletonList(gettingTo), 64, known); + List positions = MineProcess.searchWorld(context, Collections.singletonList(gettingTo), 64, known, blacklist); positions.removeIf(blacklist::contains); knownLocations = positions; } diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 495fb0ee..1c2760de 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -54,6 +54,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro private List mining; private List knownOreLocations; + private List blacklist; // inaccessible private BlockPos branchPoint; private GoalRunAway branchPointRunaway; private int desiredQuantity; @@ -80,6 +81,11 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return null; } } + if (calcFailed && !knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) { + knownOreLocations.stream().sorted(Comparator.comparingDouble(ctx.player()::getDistanceSq)).findFirst().ifPresent(blacklist::add); + knownOreLocations.removeIf(blacklist::contains); + calcFailed = false; // 😎 + } if (calcFailed) { logDirect("Unable to find any path to " + mining + ", canceling Mine"); cancel(); @@ -118,7 +124,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro boolean legit = Baritone.settings().legitMine.value; List locs = knownOreLocations; if (!locs.isEmpty()) { - List locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT); + List locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT, blacklist); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(ctx, loc, locs2)).toArray(Goal[]::new)); knownOreLocations = locs2; @@ -160,10 +166,10 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (Baritone.settings().legitMine.value) { return; } - List locs = searchWorld(context, mining, ORE_LOCATIONS_COUNT, already); + List locs = searchWorld(context, mining, ORE_LOCATIONS_COUNT, already, blacklist); locs.addAll(droppedItemsScan(mining, ctx.world())); if (locs.isEmpty()) { - logDebug("No locations for " + mining + " known, cancelling"); + logDirect("No locations for " + mining + " known, cancelling"); cancel(); return; } @@ -204,7 +210,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return ret; } - public static List searchWorld(CalculationContext ctx, List mining, int max, List alreadyKnown) { + public static List searchWorld(CalculationContext ctx, List mining, int max, List alreadyKnown, List blacklist) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); //long b = System.currentTimeMillis(); @@ -216,6 +222,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro uninteresting.add(m); } } + locs = prune(ctx, locs, mining, max, blacklist); //System.out.println("Scan of cached chunks took " + (System.currentTimeMillis() - b) + "ms"); if (locs.isEmpty()) { uninteresting = mining; @@ -226,7 +233,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); } locs.addAll(alreadyKnown); - return prune(ctx, locs, mining, max); + return prune(ctx, locs, mining, max, blacklist); } private void addNearby() { @@ -249,10 +256,10 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } } - knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, mining, ORE_LOCATIONS_COUNT); + knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, mining, ORE_LOCATIONS_COUNT, blacklist); } - public static List prune(CalculationContext ctx, List locs2, List mining, int max) { + private static List prune(CalculationContext ctx, List locs2, List mining, int max, List blacklist) { List dropped = droppedItemsScan(mining, ctx.world); dropped.removeIf(drop -> { for (BlockPos pos : locs2) { @@ -272,6 +279,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro // remove any that are implausible to mine (encased in bedrock, or touching lava) .filter(pos -> MineProcess.plausibleToBreak(ctx.bsi, pos)) + .filter(pos -> !blacklist.contains(pos)) + .sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().playerFeet()::distanceSq)) .collect(Collectors.toList()); @@ -300,6 +309,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro this.mining = blocks == null || blocks.length == 0 ? null : Arrays.asList(blocks); this.desiredQuantity = quantity; this.knownOreLocations = new ArrayList<>(); + this.blacklist = new ArrayList<>(); this.branchPoint = null; this.branchPointRunaway = null; if (mining != null) { From 88e41f37b1e4537b7481dbca35177297a6d48dde Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Mar 2019 20:08:52 -0700 Subject: [PATCH 261/682] explain whats happening --- src/main/java/baritone/process/GetToBlockProcess.java | 2 +- src/main/java/baritone/process/MineProcess.java | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index caebc865..a7a28db0 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -84,7 +84,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl Goal goal = new GoalComposite(knownLocations.stream().map(this::createGoal).toArray(Goal[]::new)); if (calcFailed) { if (Baritone.settings().blacklistClosestOnFailure.value) { - logDirect("Unable to find any path to " + gettingTo + ", blacklisting presumably unreachable closest instances"); + logDirect("Unable to find any path to " + gettingTo + ", blacklisting presumably unreachable closest instances..."); blacklistClosest(); return onTick(false, isSafeToCancel); // gamer moment } else { diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 1c2760de..322a966e 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -82,6 +82,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } if (calcFailed && !knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) { + logDirect("Unable to find any path to " + mining + ", blacklisting presumably unreachable closest instance..."); knownOreLocations.stream().sorted(Comparator.comparingDouble(ctx.player()::getDistanceSq)).findFirst().ifPresent(blacklist::add); knownOreLocations.removeIf(blacklist::contains); calcFailed = false; // 😎 From 416b5b66d2d2e666492a930fa867c661fc1e00d2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Mar 2019 20:57:46 -0700 Subject: [PATCH 262/682] break fewer beds --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index ca88a828..719ddf00 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -533,7 +533,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } - Goal goal = new GoalBlock(waypoint.getLocation()); + Goal goal = waypoint.getTag() == Waypoint.Tag.BED ? new GoalGetToBlock(waypoint.getLocation()) : new GoalBlock(waypoint.getLocation()); customGoalProcess.setGoalAndPath(goal); return true; } From a5a795a22c65860488f72198d9e4c619c1786f67 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Mar 2019 22:21:35 -0700 Subject: [PATCH 263/682] lower case ok --- README.md | 2 +- src/main/java/baritone/utils/GuiClickMeme.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 02ed2bc5..a971cad0 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ That's what it's for, sure! (As long as usage is in compliance with the LGPL 3 L ## How is it so fast? -Magic. (Hours of [Leijurv](https://github.com/leijurv) enduring excruciating pain) +Magic. (Hours of [leijurv](https://github.com/leijurv) enduring excruciating pain) ## Why is it called Baritone? diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClickMeme.java index 1163b1b0..9d9ce9b2 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClickMeme.java @@ -40,7 +40,7 @@ import static org.lwjgl.opengl.GL11.*; public class GuiClickMeme extends GuiScreen { - // My name is Brady and I grant Leijurv permission to use this pasted code + // My name is Brady and I grant leijurv permission to use this pasted code private final FloatBuffer MODELVIEW = BufferUtils.createFloatBuffer(16); private final FloatBuffer PROJECTION = BufferUtils.createFloatBuffer(16); private final IntBuffer VIEWPORT = BufferUtils.createIntBuffer(16); @@ -58,7 +58,7 @@ public class GuiClickMeme extends GuiScreen { int mx = Mouse.getX(); int my = Mouse.getY(); Vec3d near = toWorld(mx, my, 0); - Vec3d far = toWorld(mx, my, 1); // "Use 0.945 that's what stack overflow says" - Leijurv + Vec3d far = toWorld(mx, my, 1); // "Use 0.945 that's what stack overflow says" - leijurv if (near != null && far != null) { Vec3d viewerPos = new Vec3d(mc.getRenderManager().viewerPosX, mc.getRenderManager().viewerPosY, mc.getRenderManager().viewerPosZ); RayTraceResult result = mc.world.rayTraceBlocks(near.add(viewerPos), far.add(viewerPos), false, false, true); From ba31d209c94e59222e9f13d5f0717bfbc3a3bda7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Mar 2019 23:29:39 -0700 Subject: [PATCH 264/682] except what if it compiled --- src/main/java/baritone/behavior/InventoryBehavior.java | 4 ++-- src/main/java/baritone/process/BuilderProcess.java | 4 ++-- src/main/java/baritone/utils/GuiClickMeme.java | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 70e5997a..120bc748 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -122,7 +122,7 @@ public class InventoryBehavior extends Behavior { } public boolean hasGenericThrowaway() { - for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { + for (Item item : Baritone.settings().acceptableThrowawayItems.value) { if (throwaway(false, item::equals)) { return true; } @@ -135,7 +135,7 @@ public class InventoryBehavior extends Behavior { if (maybe != null && throwaway(true, item -> item instanceof ItemBlock && ((ItemBlock) item).getBlock().equals(maybe.getBlock()))) { return true; // gotem } - for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { + for (Item item : Baritone.settings().acceptableThrowawayItems.value) { if (throwaway(true, item::equals)) { return true; } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 6c8099f9..09ca3460 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -57,7 +57,7 @@ import static baritone.api.pathing.movement.ActionCosts.COST_INF; public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { public BuilderProcess(Baritone baritone) { - super(baritone, 0); + super(baritone); } private HashSet incorrectPositions; @@ -329,7 +329,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } List approxPlacable = placable(36); - if (Baritone.settings().allowInventory.get()) { + if (Baritone.settings().allowInventory.value) { ArrayList usefulSlots = new ArrayList<>(); List noValidHotbarOption = new ArrayList<>(); outer: diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClickMeme.java index 13847154..50a2d245 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClickMeme.java @@ -115,7 +115,7 @@ public class GuiClickMeme extends GuiScreen { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.color(Color.RED.getColorComponents(null)[0], Color.RED.getColorComponents(null)[1], Color.RED.getColorComponents(null)[2], 0.4F); - GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); + GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); GlStateManager.disableDepth(); From 25024b58deee165c4250c820fc6b62576fd9ee9b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 15:41:58 -0700 Subject: [PATCH 265/682] fix a bunch of scuff --- .../pathing/movement/movements/MovementPillar.java | 13 +++++++++++-- .../java/baritone/process/CustomGoalProcess.java | 2 +- .../java/baritone/process/GetToBlockProcess.java | 2 +- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index e899ce63..6ccd449b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -36,6 +36,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import java.util.Objects; +import java.util.Optional; public class MovementPillar extends Movement { @@ -161,6 +162,7 @@ public class MovementPillar extends Movement { state.setInput(Input.MOVE_FORWARD, true); } if (ctx.playerFeet().equals(dest)) { + logDebug("wtf2"); return state.setStatus(MovementStatus.SUCCESS); } return state; @@ -183,6 +185,7 @@ public class MovementPillar extends Movement { } if (ctx.playerFeet().equals(against.up()) || ctx.playerFeet().equals(dest)) { + logDebug("wtf3"); return state.setStatus(MovementStatus.SUCCESS); } if (MovementHelper.isBottomSlab(BlockStateInterface.get(ctx, src.down()))) { @@ -226,8 +229,14 @@ public class MovementPillar extends Movement { if (!blockIsThere) { - Block fr = BlockStateInterface.get(ctx, src).getBlock(); - if (!(fr instanceof BlockAir || fr.isReplaceable(ctx.world(), src))) { + IBlockState frState = BlockStateInterface.get(ctx, src); + Block fr = frState.getBlock(); + // TODO: Evaluate usage of getMaterial().isReplaceable() + if (!(fr instanceof BlockAir || frState.getMaterial().isReplaceable())) { + Optional reachable = RotationUtils.reachable(ctx.player(), src, ctx.playerController().getBlockReachDistance()); + if (reachable.isPresent()) { + state.setTarget(new MovementState.MovementTarget(reachable.get(), true)); + } state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; } else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos())) && ctx.player().posY > dest.getY() + 0.1) { diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index 2c8a3c33..0ec2ba78 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -88,7 +88,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG onLostControl(); return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL); } - if (this.goal == null || this.goal.isInGoal(ctx.playerFeet())) { + if (this.goal == null || (this.goal.isInGoal(ctx.playerFeet()) && ctx.player().onGround)) { onLostControl(); // we're there xd return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL); } diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index a7a28db0..e2c34dfd 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -101,7 +101,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl CalculationContext context = new CalculationContext(baritone, true); Baritone.getExecutor().execute(() -> rescan(current, context)); } - if (goal.isInGoal(ctx.playerFeet()) && isSafeToCancel) { + if (goal.isInGoal(ctx.playerFeet()) && ctx.player().onGround && isSafeToCancel) { // we're there if (rightClickOnArrival(gettingTo)) { if (rightClick()) { From b240e8420ac50c4b00c9198306a98976e12d2a1f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 15:53:00 -0700 Subject: [PATCH 266/682] whoops --- .../baritone/pathing/movement/movements/MovementPillar.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 6ccd449b..d725d95f 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -162,7 +162,6 @@ public class MovementPillar extends Movement { state.setInput(Input.MOVE_FORWARD, true); } if (ctx.playerFeet().equals(dest)) { - logDebug("wtf2"); return state.setStatus(MovementStatus.SUCCESS); } return state; @@ -185,7 +184,6 @@ public class MovementPillar extends Movement { } if (ctx.playerFeet().equals(against.up()) || ctx.playerFeet().equals(dest)) { - logDebug("wtf3"); return state.setStatus(MovementStatus.SUCCESS); } if (MovementHelper.isBottomSlab(BlockStateInterface.get(ctx, src.down()))) { From 52d8d271f126bfc514c0f58fb1317aed3df6cfec Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 16:18:48 -0700 Subject: [PATCH 267/682] fix a meme with a path ending in water --- src/main/java/baritone/process/CustomGoalProcess.java | 2 +- src/main/java/baritone/process/GetToBlockProcess.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index 0ec2ba78..fe1de028 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -88,7 +88,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG onLostControl(); return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL); } - if (this.goal == null || (this.goal.isInGoal(ctx.playerFeet()) && ctx.player().onGround)) { + if (this.goal == null || (this.goal.isInGoal(ctx.playerFeet()) && this.goal.isInGoal(baritone.getPathingBehavior().pathStart()))) { onLostControl(); // we're there xd return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL); } diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index e2c34dfd..092e9ce4 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -101,7 +101,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl CalculationContext context = new CalculationContext(baritone, true); Baritone.getExecutor().execute(() -> rescan(current, context)); } - if (goal.isInGoal(ctx.playerFeet()) && ctx.player().onGround && isSafeToCancel) { + if (goal.isInGoal(ctx.playerFeet()) && goal.isInGoal(baritone.getPathingBehavior().pathStart()) && isSafeToCancel) { // we're there if (rightClickOnArrival(gettingTo)) { if (rightClick()) { From fa8f2632f546d48be6d172c7aec9ae3aed3e3116 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 18:58:35 -0700 Subject: [PATCH 268/682] dont jump while breaking --- .../java/baritone/pathing/movement/movements/MovementPillar.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index d725d95f..d8ab5fef 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -235,6 +235,7 @@ public class MovementPillar extends Movement { if (reachable.isPresent()) { state.setTarget(new MovementState.MovementTarget(reachable.get(), true)); } + state.setInput(Input.JUMP, false); // breaking is like 5x slower when you're jumping state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; } else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos())) && ctx.player().posY > dest.getY() + 0.1) { From a5601fd89ac5e089083c4abe9b29a5eb73f72b5f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 18:59:20 -0700 Subject: [PATCH 269/682] nutty --- .../java/baritone/api/utils/input/Input.java | 66 +++---------------- 1 file changed, 9 insertions(+), 57 deletions(-) diff --git a/src/api/java/baritone/api/utils/input/Input.java b/src/api/java/baritone/api/utils/input/Input.java index 1e8d44b5..c44f3352 100644 --- a/src/api/java/baritone/api/utils/input/Input.java +++ b/src/api/java/baritone/api/utils/input/Input.java @@ -17,15 +17,6 @@ package baritone.api.utils.input; -import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.GameSettings; -import net.minecraft.client.settings.KeyBinding; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - /** * An {@link Enum} representing the inputs that control the player's * behavior. This includes moving, interacting with blocks, jumping, @@ -36,84 +27,45 @@ public enum Input { /** * The move forward input */ - MOVE_FORWARD(s -> s.keyBindForward), + MOVE_FORWARD, /** * The move back input */ - MOVE_BACK(s -> s.keyBindBack), + MOVE_BACK, /** * The move left input */ - MOVE_LEFT(s -> s.keyBindLeft), + MOVE_LEFT, /** * The move right input */ - MOVE_RIGHT(s -> s.keyBindRight), + MOVE_RIGHT, /** * The attack input */ - CLICK_LEFT(s -> s.keyBindAttack), + CLICK_LEFT, /** * The use item input */ - CLICK_RIGHT(s -> s.keyBindUseItem), + CLICK_RIGHT, /** * The jump input */ - JUMP(s -> s.keyBindJump), + JUMP, /** * The sneak input */ - SNEAK(s -> s.keyBindSneak), + SNEAK, /** * The sprint input */ - SPRINT(s -> s.keyBindSprint); - - /** - * Map of {@link KeyBinding} to {@link Input}. Values should be queried through {@link #getInputForBind(KeyBinding)} - */ - private static final Map bindToInputMap = new HashMap<>(); - - /** - * The actual game {@link KeyBinding} being forced. - */ - private final KeyBinding keyBinding; - - Input(Function keyBindingMapper) { - /* - - Here, a Function is used because referring to a static field in this enum for the game instance, - as it was before, wouldn't be possible in an Enum constructor unless the static field was in an - interface that this class implemented. (Helper acted as this interface) I didn't feel like making - an interface with a game instance field just to not have to do this. - - */ - this.keyBinding = keyBindingMapper.apply(Minecraft.getMinecraft().gameSettings); - } - - /** - * @return The actual game {@link KeyBinding} being forced. - */ - public final KeyBinding getKeyBinding() { - return this.keyBinding; - } - - /** - * Finds the {@link Input} constant that is associated with the specified {@link KeyBinding}. - * - * @param binding The {@link KeyBinding} to find the associated {@link Input} for - * @return The {@link Input} associated with the specified {@link KeyBinding} - */ - public static Input getInputForBind(KeyBinding binding) { - return bindToInputMap.computeIfAbsent(binding, b -> Arrays.stream(values()).filter(input -> input.keyBinding == b).findFirst().orElse(null)); - } + SPRINT } From 866408aece4d663061bfcc00ba2b6547cc4042ec Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 19:17:50 -0700 Subject: [PATCH 270/682] rename --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- .../java/baritone/utils/{GuiClickMeme.java => GuiClick.java} | 2 +- src/main/java/baritone/utils/PathRenderer.java | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) rename src/main/java/baritone/utils/{GuiClickMeme.java => GuiClick.java} (99%) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 8777a3a9..fcd07101 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -483,7 +483,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { new Thread(() -> { try { Thread.sleep(100); - mc.addScheduledTask(() -> mc.displayGuiScreen(new GuiClickMeme())); + mc.addScheduledTask(() -> mc.displayGuiScreen(new GuiClick())); } catch (Exception ignored) {} }).start(); logDirect("aight dude"); diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClick.java similarity index 99% rename from src/main/java/baritone/utils/GuiClickMeme.java rename to src/main/java/baritone/utils/GuiClick.java index 50a2d245..cd10ee17 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -40,7 +40,7 @@ import java.util.Collections; import static org.lwjgl.opengl.GL11.*; -public class GuiClickMeme extends GuiScreen { +public class GuiClick extends GuiScreen { // My name is Brady and I grant leijurv permission to use this pasted code private final FloatBuffer MODELVIEW = BufferUtils.createFloatBuffer(16); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index a9cb4ce2..7ea20122 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -59,8 +59,8 @@ public final class PathRenderer implements Helper { public static void render(RenderEvent event, PathingBehavior behavior) { float partialTicks = event.getPartialTicks(); Goal goal = behavior.getGoal(); - if (mc.currentScreen instanceof GuiClickMeme) { - ((GuiClickMeme) mc.currentScreen).onRender(partialTicks); + if (mc.currentScreen instanceof GuiClick) { + ((GuiClick) mc.currentScreen).onRender(partialTicks); } int thisPlayerDimension = behavior.baritone.getPlayerContext().world().provider.getDimensionType().getId(); From 909ab553eb19d6a034e3080eda33235479ff7d95 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 22:08:17 -0700 Subject: [PATCH 271/682] small cleanup --- src/main/java/baritone/utils/GuiClick.java | 11 +---------- src/main/java/baritone/utils/PathRenderer.java | 2 +- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index cd10ee17..c928d1f1 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -74,14 +74,11 @@ public class GuiClick extends GuiScreen { @Override protected void mouseReleased(int mouseX, int mouseY, int mouseButton) { - System.out.println("Mouse released"); if (mouseButton == 0) { if (clickStart != null && !clickStart.equals(currentMouseOver)) { ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getBuilderProcess().clearArea(clickStart, currentMouseOver); clickStart = null; } else { - - BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalTwoBlocks(currentMouseOver)); } } else if (mouseButton == 1) { @@ -93,16 +90,10 @@ public class GuiClick extends GuiScreen { @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) { - System.out.println("Mouse clicked"); clickStart = currentMouseOver; } - @Override - protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { - System.out.println("Click move"); - } - - public void onRender(float partialTicks) { + public void onRender() { GlStateManager.getFloat(GL_MODELVIEW_MATRIX, (FloatBuffer) MODELVIEW.clear()); GlStateManager.getFloat(GL_PROJECTION_MATRIX, (FloatBuffer) PROJECTION.clear()); GlStateManager.glGetInteger(GL_VIEWPORT, (IntBuffer) VIEWPORT.clear()); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 7ea20122..9840e76e 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -60,7 +60,7 @@ public final class PathRenderer implements Helper { float partialTicks = event.getPartialTicks(); Goal goal = behavior.getGoal(); if (mc.currentScreen instanceof GuiClick) { - ((GuiClick) mc.currentScreen).onRender(partialTicks); + ((GuiClick) mc.currentScreen).onRender(); } int thisPlayerDimension = behavior.baritone.getPlayerContext().world().provider.getDimensionType().getId(); From 74e0552be09428b7b9e6f4f35cad27739678d303 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 23:08:06 -0700 Subject: [PATCH 272/682] unscuff water, thanks wwe --- .../pathing/movement/movements/MovementDescend.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index a0f701e6..a73ed4fb 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -122,7 +122,7 @@ public class MovementDescend extends Movement { // and potentially replace the water we're going to fall into return false; } - if (!MovementHelper.canWalkThrough(context.bsi, destX, y - 2, destZ, below) && below.getBlock() != Blocks.WATER) { + if (!MovementHelper.canWalkThrough(context.bsi, destX, y - 2, destZ, below)) { return false; } double costSoFar = 0; @@ -137,9 +137,10 @@ public class MovementDescend extends Movement { IBlockState ontoBlock = context.get(destX, newY, destZ); int unprotectedFallHeight = fallHeight - (y - effectiveStartHeight); // equal to fallHeight - y + effectiveFallHeight, which is equal to -newY + effectiveFallHeight, which is equal to effectiveFallHeight - newY double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[unprotectedFallHeight] + frontBreak + costSoFar; - if ((ontoBlock.getBlock() == Blocks.WATER || ontoBlock.getBlock() == Blocks.FLOWING_WATER) && context.getBlock(destX, newY + 1, destZ) != Blocks.WATERLILY) { - // lilypads are canWalkThrough, but we can't end a fall that should be broken by water if it's covered by a lilypad - // however, don't return impossible in the lilypad scenario, because we could still jump right on it (water that's below a lilypad is canWalkOn so it works) + if (MovementHelper.isWater(ontoBlock.getBlock())) { + if (!MovementHelper.canWalkThrough(context.bsi, destX, newY, destZ, ontoBlock)) { + return false; + } if (context.assumeWalkOnWater) { return false; // TODO fix } From e09541151f9c9a4913af3992b144c5f2bd800a12 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 23:29:08 -0700 Subject: [PATCH 273/682] update clients --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index a971cad0..f292bc64 100644 --- a/README.md +++ b/README.md @@ -18,9 +18,8 @@ [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.3-brightgreen.svg)](https://impactdevelopment.github.io/) -[![Asuna integration](https://img.shields.io/badge/Asuna%20integration-builder%20branch-brightgreen.svg)](https://github.com/EmotionalLove/Asuna/) +[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-red.svg)](https://github.com/zeroeightysix/KAMI/) -[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-v1.0.0%3F%3F%20smh%20license%20violations-red.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soon™-red.svg)](https://github.com/fr1kin/ForgeHax) From ee6df270ce97653232d7b72021fd80cc472048b5 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Mar 2019 08:50:04 -0700 Subject: [PATCH 274/682] relative coordinates --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index fcd07101..04d1606b 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -634,7 +634,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } private int parseOrDefault(String str, int i) { - return str.equals("~") ? i : Integer.parseInt(str); + return str.equals("~") ? i : str.startsWith("~") ? Integer.parseInt(str.substring(1)) + i : Integer.parseInt(str); } private void log(List stacks) { From a75317cc2c853ce26c4aa491d5d6527b6c024f3e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Mar 2019 09:17:25 -0700 Subject: [PATCH 275/682] workaround some scuff --- .../java/baritone/api/process/IBaritoneProcess.java | 11 ++++++++++- src/main/java/baritone/process/BuilderProcess.java | 2 +- src/main/java/baritone/process/CustomGoalProcess.java | 2 +- src/main/java/baritone/process/ExploreProcess.java | 2 +- src/main/java/baritone/process/FollowProcess.java | 2 +- src/main/java/baritone/process/GetToBlockProcess.java | 4 ++-- src/main/java/baritone/process/MineProcess.java | 2 +- 7 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/process/IBaritoneProcess.java b/src/api/java/baritone/api/process/IBaritoneProcess.java index 0339179c..726260d8 100644 --- a/src/api/java/baritone/api/process/IBaritoneProcess.java +++ b/src/api/java/baritone/api/process/IBaritoneProcess.java @@ -101,5 +101,14 @@ public interface IBaritoneProcess { * * @return A display name that's suitable for a HUD */ - String displayName(); + default String displayName() { + if (!isActive()) { + // i love it when impcat's scuffed HUD calls displayName for inactive processes for 1 tick too long + // causing NPEs when the displayname relies on fields that become null when inactive + return "INACTIVE"; + } + return displayName0(); + } + + String displayName0(); } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 09ca3460..9dd6fc92 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -543,7 +543,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } @Override - public String displayName() { + public String displayName0() { return "Building " + name; } diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index fe1de028..fe361ad6 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -105,7 +105,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG } @Override - public String displayName() { + public String displayName0() { return "Custom Goal " + this.goal; } diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 3343d882..eb98cbde 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -94,7 +94,7 @@ public class ExploreProcess extends BaritoneProcessHelper { } @Override - public String displayName() { + public String displayName0() { return "Exploring around " + explorationOrigin + ", currently going to " + closestUncachedChunk(explorationOrigin); } } diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 04e80e03..6004ac2f 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -101,7 +101,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo } @Override - public String displayName() { + public String displayName0() { return "Follow " + cache; } diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 092e9ce4..2dbefd50 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -160,11 +160,11 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } @Override - public String displayName() { + public String displayName0() { if (knownLocations.isEmpty()) { return "Exploring randomly to find " + gettingTo + ", no known locations"; } - return "Get To Block " + gettingTo + ", " + knownLocations.size() + " known locations"; + return "Get To " + gettingTo + ", " + knownLocations.size() + " known locations"; } private synchronized void rescan(List known, CalculationContext context) { diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 322a966e..af06556b 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -117,7 +117,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } @Override - public String displayName() { + public String displayName0() { return "Mine " + mining; } From 89fb5cecd5a3200ed81f75e1bd2721b5824c3f89 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Mar 2019 18:15:21 -0700 Subject: [PATCH 276/682] v1.2.4 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index e52cc370..a49bfd76 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.2.3' +version '1.2.4' buildscript { repositories { From 226ede7ba2c2db2c6ee6fbd494c7aa982377de01 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Mar 2019 19:23:28 -0700 Subject: [PATCH 277/682] crucial --- src/main/java/baritone/cache/ChunkPacker.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index 7f447f87..66a11fe7 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -90,8 +90,7 @@ public final class ChunkPacker { IBlockState[] blocks = new IBlockState[256]; for (int z = 0; z < 16; z++) { - https: -//www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html + https://www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html for (int x = 0; x < 16; x++) { for (int y = 255; y >= 0; y--) { int index = CachedChunk.getPositionIndex(x, y, z); From bd1dcff385737e683e932de0294cbbc9a9f0cdeb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 14 Mar 2019 14:52:51 -0700 Subject: [PATCH 278/682] allow ties for closest to explore to --- .../java/baritone/process/ExploreProcess.java | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index eb98cbde..eff4d2de 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -19,6 +19,8 @@ package baritone.process; import baritone.Baritone; import baritone.api.cache.ICachedWorld; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalXZ; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; @@ -26,6 +28,9 @@ import baritone.cache.CachedWorld; import baritone.utils.BaritoneProcessHelper; import net.minecraft.util.math.BlockPos; +import java.util.ArrayList; +import java.util.List; + public class ExploreProcess extends BaritoneProcessHelper { private BlockPos explorationOrigin; @@ -50,23 +55,24 @@ public class ExploreProcess extends BaritoneProcessHelper { onLostControl(); return null; } - BlockPos closestUncached = closestUncachedChunk(explorationOrigin); + Goal[] closestUncached = closestUncachedChunks(explorationOrigin); if (closestUncached == null) { logDebug("awaiting region load from disk"); return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } System.out.println("Closest uncached: " + closestUncached); - return new PathingCommand(new GoalXZ(closestUncached.getX(), closestUncached.getZ()), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); + return new PathingCommand(new GoalComposite(closestUncached), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); } - private BlockPos closestUncachedChunk(BlockPos pos) { - int chunkX = pos.getX() >> 4; - int chunkZ = pos.getZ() >> 4; + private Goal[] closestUncachedChunks(BlockPos center) { + int chunkX = center.getX() >> 4; + int chunkZ = center.getZ() >> 4; ICachedWorld cache = baritone.getWorldProvider().getCurrentWorld().getCachedWorld(); for (int dist = 0; ; dist++) { + List centers = new ArrayList<>(); for (int dx = -dist; dx <= dist; dx++) { for (int dz = -dist; dz <= dist; dz++) { - int trueDist = Baritone.settings().exploreUsePythagorean.value ? dx * dx + dz + dz : Math.abs(dx) + Math.abs(dz); + int trueDist = Baritone.settings().exploreUsePythagorean.value ? dx * dx + dz * dz : Math.abs(dx) + Math.abs(dz); if (trueDist != dist) { continue; // not considering this one just yet in our expanding search } @@ -82,9 +88,12 @@ public class ExploreProcess extends BaritoneProcessHelper { }); return null; // we still need to load regions from disk in order to decide properly } - return new BlockPos(centerX, 0, centerZ); + centers.add(new BlockPos(centerX, 0, centerZ)); } } + if (!centers.isEmpty()) { + return centers.stream().map(pos -> new GoalXZ(pos.getX(), pos.getZ())).toArray(Goal[]::new); + } } } @@ -95,6 +104,6 @@ public class ExploreProcess extends BaritoneProcessHelper { @Override public String displayName0() { - return "Exploring around " + explorationOrigin + ", currently going to " + closestUncachedChunk(explorationOrigin); + return "Exploring around " + explorationOrigin + ", currently going to " + new GoalComposite(closestUncachedChunks(explorationOrigin)); } } From 610fe6439f283a5c3ba4116bbae8afbb78c738bc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 15 Mar 2019 14:25:43 -0700 Subject: [PATCH 279/682] fix getting permanently stuck on vines --- .../baritone/pathing/movement/movements/MovementTraverse.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 8b43bc5c..966dae95 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -234,7 +234,7 @@ public class MovementTraverse extends Movement { } Block low = BlockStateInterface.get(ctx, src).getBlock(); Block high = BlockStateInterface.get(ctx, src.up()).getBlock(); - if (!ctx.player().onGround && (low == Blocks.VINE || low == Blocks.LADDER || high == Blocks.VINE || high == Blocks.LADDER)) { + if (ctx.player().posY > src.y + 0.1D && !ctx.player().onGround && (low == Blocks.VINE || low == Blocks.LADDER || high == Blocks.VINE || high == Blocks.LADDER)) { // hitting W could cause us to climb the ladder instead of going forward // wait until we're on the ground return state; From ee83471bf6a2cc8e8e7f5ff1f8dabf7e21d22cb1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 15 Mar 2019 14:25:59 -0700 Subject: [PATCH 280/682] fix being unable to place or pick up water buckets --- src/api/java/baritone/api/utils/IPlayerController.java | 2 ++ src/main/java/baritone/utils/BlockPlaceHelper.java | 3 +++ .../java/baritone/utils/player/PrimaryPlayerController.java | 5 +++++ 3 files changed, 10 insertions(+) diff --git a/src/api/java/baritone/api/utils/IPlayerController.java b/src/api/java/baritone/api/utils/IPlayerController.java index dced5286..14334d5e 100644 --- a/src/api/java/baritone/api/utils/IPlayerController.java +++ b/src/api/java/baritone/api/utils/IPlayerController.java @@ -50,4 +50,6 @@ public interface IPlayerController { } EnumActionResult processRightClickBlock(EntityPlayerSP player, World world, BlockPos pos, EnumFacing direction, Vec3d vec, EnumHand hand); + + EnumActionResult processRightClick(EntityPlayerSP player, World world, EnumHand hand); } diff --git a/src/main/java/baritone/utils/BlockPlaceHelper.java b/src/main/java/baritone/utils/BlockPlaceHelper.java index 8e7ef44a..ed472d57 100644 --- a/src/main/java/baritone/utils/BlockPlaceHelper.java +++ b/src/main/java/baritone/utils/BlockPlaceHelper.java @@ -46,6 +46,9 @@ public class BlockPlaceHelper implements Helper { ctx.player().swingArm(hand); return; } + if (!ctx.player().getHeldItem(hand).isEmpty() && ctx.playerController().processRightClick(ctx.player(), ctx.world(), hand) == EnumActionResult.SUCCESS) { + return; + } } } } diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerController.java b/src/main/java/baritone/utils/player/PrimaryPlayerController.java index 76e389e7..b9828c80 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerController.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerController.java @@ -72,4 +72,9 @@ public enum PrimaryPlayerController implements IPlayerController, Helper { // primaryplayercontroller is always in a WorldClient so this is ok return mc.playerController.processRightClickBlock(player, (WorldClient) world, pos, direction, vec, hand); } + + @Override + public EnumActionResult processRightClick(EntityPlayerSP player, World world, EnumHand hand) { + return mc.playerController.processRightClick(player, world, hand); + } } From aaaf0f883943f66f58f84cf3992b583d1d4befb3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 15 Mar 2019 16:39:59 -0700 Subject: [PATCH 281/682] hey so what if we didnt do that --- src/main/java/baritone/cache/CachedWorld.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 7e34fa08..c025d489 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -70,8 +70,6 @@ public final class CachedWorld implements ICachedWorld, Helper { this.directory = directory.toString(); this.dimension = dimension; System.out.println("Cached world directory: " + directory); - // Insert an invalid region element - cachedRegions.put(0, null); Baritone.getExecutor().execute(new PackerThread()); Baritone.getExecutor().execute(() -> { try { From cfec67f1f9977943083101ce7025f771d628cd60 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 16 Mar 2019 23:23:20 -0700 Subject: [PATCH 282/682] wording --- src/main/java/baritone/process/FollowProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 6004ac2f..12188729 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -102,7 +102,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo @Override public String displayName0() { - return "Follow " + cache; + return "Following " + cache; } @Override From bcd097c6cbdaa227d6a7ea85a79ad6a8e7c3955a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 17 Mar 2019 22:40:11 -0800 Subject: [PATCH 283/682] we can cancel calc even if not safe to cancel pathing --- src/main/java/baritone/behavior/PathingBehavior.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index cca7bdfc..00ac5a4c 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -325,6 +325,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, public void softCancelIfSafe() { synchronized (pathPlanLock) { + getInProgress().ifPresent(AbstractNodeCostSearch::cancel); // only cancel ours if (!isSafeToCancel()) { return; } @@ -332,7 +333,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, next = null; } cancelRequested = true; - getInProgress().ifPresent(AbstractNodeCostSearch::cancel); // only cancel ours // do everything BUT clear keys } @@ -340,11 +340,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, public void secretInternalSegmentCancel() { queuePathEvent(PathEvent.CANCELED); synchronized (pathPlanLock) { + getInProgress().ifPresent(AbstractNodeCostSearch::cancel); if (current != null) { current = null; next = null; baritone.getInputOverrideHandler().clearAllKeys(); - getInProgress().ifPresent(AbstractNodeCostSearch::cancel); baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); } } From 49658078b9cdd932d597bfc83c078ce444f3b1f9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 18 Mar 2019 22:38:06 -0700 Subject: [PATCH 284/682] trapdoors cant be passed vertically in either state, thanks plutie --- .../pathing/movement/MovementHelper.java | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 47677a65..12ab8e72 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -72,7 +72,7 @@ public interface MovementHelper extends ActionCosts, Helper { if (block == Blocks.AIR) { // early return for most common case return true; } - if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.WEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof BlockSkull) { + if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.WEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof BlockSkull || block instanceof BlockTrapDoor) { return false; } if (block instanceof BlockDoor || block instanceof BlockFenceGate) { @@ -84,9 +84,7 @@ public interface MovementHelper extends ActionCosts, Helper { if (block == Blocks.CARPET) { return canWalkOn(bsi, x, y - 1, z); } - boolean snow = block instanceof BlockSnow; - boolean trapdoor = block instanceof BlockTrapDoor; - if (snow || trapdoor) { + if (block instanceof BlockSnow) { // we've already checked doors and fence gates // so the only remaining dynamic isPassables are snow and trapdoor // if they're cached as a top block, we don't know their metadata @@ -94,19 +92,13 @@ public interface MovementHelper extends ActionCosts, Helper { if (!bsi.worldContainsLoadedChunk(x, z)) { return true; } - if (snow) { - // the check in BlockSnow.isPassable is layers < 5 - // while actually, we want < 3 because 3 or greater makes it impassable in a 2 high ceiling - if (state.getValue(BlockSnow.LAYERS) >= 3) { - return false; - } - // ok, it's low enough we could walk through it, but is it supported? - return canWalkOn(bsi, x, y - 1, z); + // the check in BlockSnow.isPassable is layers < 5 + // while actually, we want < 3 because 3 or greater makes it impassable in a 2 high ceiling + if (state.getValue(BlockSnow.LAYERS) >= 3) { + return false; } - if (trapdoor) { - return !state.getValue(BlockTrapDoor.OPEN); // see BlockTrapDoor.isPassable - } - throw new IllegalStateException(); + // ok, it's low enough we could walk through it, but is it supported? + return canWalkOn(bsi, x, y - 1, z); } if (isFlowing(x, y, z, state, bsi)) { return false; // Don't walk through flowing liquids From aada9731a63e604637e39386ef653715d97af6a1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Mar 2019 18:10:53 -0700 Subject: [PATCH 285/682] more resiliency to invalid cache files --- src/main/java/baritone/cache/CachedChunk.java | 2 +- src/main/java/baritone/cache/CachedRegion.java | 3 ++- src/main/java/baritone/cache/ChunkPacker.java | 8 +++++++- src/main/java/baritone/process/MineProcess.java | 2 +- src/main/java/baritone/utils/ExampleBaritoneControl.java | 7 +++---- 5 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 08c80141..bc5e2ac9 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -177,7 +177,7 @@ public final class CachedChunk { if (special != null) { String str = special.get(index); if (str != null) { - return ChunkPacker.stringToBlock(str).getDefaultState(); + return ChunkPacker.stringToBlockRequired(str).getDefaultState(); } } diff --git a/src/main/java/baritone/cache/CachedRegion.java b/src/main/java/baritone/cache/CachedRegion.java index e3a85dfc..d395f168 100644 --- a/src/main/java/baritone/cache/CachedRegion.java +++ b/src/main/java/baritone/cache/CachedRegion.java @@ -240,7 +240,7 @@ public final class CachedRegion implements ICachedRegion { for (int z = 0; z < 32; z++) { if (present[x][z]) { for (int i = 0; i < 256; i++) { - overview[x][z][i] = ChunkPacker.stringToBlock(in.readUTF()).getDefaultState(); + overview[x][z][i] = ChunkPacker.stringToBlockRequired(in.readUTF()).getDefaultState(); } } } @@ -255,6 +255,7 @@ public final class CachedRegion implements ICachedRegion { int numSpecialBlockTypes = in.readShort() & 0xffff; for (int i = 0; i < numSpecialBlockTypes; i++) { String blockName = in.readUTF(); + ChunkPacker.stringToBlockRequired(blockName); List locs = new ArrayList<>(); location[x][z].put(blockName, locs); int numLocations = in.readShort() & 0xffff; diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index 66a11fe7..6834549b 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -115,7 +115,13 @@ public final class ChunkPacker { return name; } - public static Block stringToBlock(String name) { + public static Block stringToBlockRequired(String name) { + Block block = stringToBlockNullable(name); + Objects.requireNonNull(block); + return block; + } + + public static Block stringToBlockNullable(String name) { return resourceCache.computeIfAbsent(name, n -> Block.getBlockFromName(n.contains(":") ? n : "minecraft:" + n)); } diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index af06556b..f2ebcd55 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -302,7 +302,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro @Override public void mineByName(int quantity, String... blocks) { - mine(quantity, blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlock).toArray(Block[]::new)); + mine(quantity, blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlockRequired).toArray(Block[]::new)); } @Override diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 04d1606b..6dbdf388 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -462,14 +462,13 @@ public class ExampleBaritoneControl extends Behavior implements Helper { String[] blockTypes = msg.substring(4).trim().split(" "); try { int quantity = Integer.parseInt(blockTypes[1]); - Block block = ChunkPacker.stringToBlock(blockTypes[0]); - Objects.requireNonNull(block); + Block block = ChunkPacker.stringToBlockRequired(blockTypes[0]); baritone.getMineProcess().mine(quantity, block); logDirect("Will mine " + quantity + " " + blockTypes[0]); return true; } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {} for (String s : blockTypes) { - if (ChunkPacker.stringToBlock(s) == null) { + if (ChunkPacker.stringToBlockNullable(s) == null) { logDirect(s + " isn't a valid block name"); return true; } @@ -552,7 +551,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { IWaypoint waypoint; if (tag == null) { String mining = waypointType; - Block block = ChunkPacker.stringToBlock(mining); + Block block = ChunkPacker.stringToBlockNullable(mining); //logDirect("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase()); if (block == null) { waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null); From 65902d556e5b2ea30ccfd584366854767ccb4cce Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Mar 2019 18:22:22 -0700 Subject: [PATCH 286/682] v1.2.5 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index a49bfd76..739e3d35 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.2.4' +version '1.2.5' buildscript { repositories { From 8c4e778506f82a8e10740032907d5acf28e16026 Mon Sep 17 00:00:00 2001 From: babbaj Date: Tue, 19 Mar 2019 01:48:16 -0400 Subject: [PATCH 287/682] Create ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/ISSUE_TEMPLATE.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..d0e034d0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1 @@ + From 3f6af517139f81c4b74b4d5e80098bfb7eb5b6f9 Mon Sep 17 00:00:00 2001 From: babbaj Date: Tue, 19 Mar 2019 01:53:09 -0400 Subject: [PATCH 288/682] Create PULL_REQUEST_TEMPLATE.md --- .github/PULL_REQUEST_TEMPLATE.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..d0e034d0 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1 @@ + From a07fae6cdd530e7e925a874ddac401c248a199a4 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 19 Mar 2019 21:25:58 -0500 Subject: [PATCH 289/682] Update Code of Conduct to include templates --- CODE_OF_CONDUCT.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index ae74fc3e..37c1b703 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -45,6 +45,11 @@ that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. +Project maintainers have the right and responsibility to immediately remove +without any sort of dispute any issues or pull requests that do not align +with their corresponding templates. Absolutely no leniancy shall be accepted +with these terms. + ## Scope This Code of Conduct applies both within project spaces and in public spaces From 7ab2cd2a4587c3df705e4d804f5d4c17a1cdc2ca Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 19 Mar 2019 21:26:47 -0500 Subject: [PATCH 290/682] Update ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index d0e034d0..e9a3c7cc 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1 +1 @@ - + From 32ac46c8a9d371504fd21939b898250db7cc870d Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 19 Mar 2019 21:26:58 -0500 Subject: [PATCH 291/682] Update PULL_REQUEST_TEMPLATE.md --- .github/PULL_REQUEST_TEMPLATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index d0e034d0..e9a3c7cc 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1 +1 @@ - + From 54ed6ce5a5b58f72bdcb69796664a0505b6431b1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 20 Mar 2019 22:55:40 -0700 Subject: [PATCH 292/682] crucial code formatting --- src/main/java/baritone/utils/GuiClick.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index c928d1f1..ab65667d 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -87,7 +87,6 @@ public class GuiClick extends GuiScreen { clickStart = null; } - @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) { clickStart = currentMouseOver; From 04ff365890692a82d7653a80289bea02ea5a1f7d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 20 Mar 2019 23:03:06 -0700 Subject: [PATCH 293/682] what about if i delete two (2) empty lines --- src/main/java/baritone/utils/GuiClick.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index ab65667d..0b412b92 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -119,8 +119,6 @@ public class GuiClick extends GuiScreen { GlStateManager.disableBlend(); } } - - } public Vec3d toWorld(double x, double y, double z) { From cac653ddd9430c03e17462c4725bb36f30d3bf44 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 20 Mar 2019 23:06:14 -0700 Subject: [PATCH 294/682] little cleanup --- src/main/java/baritone/behavior/LookBehavior.java | 4 ++-- src/main/java/baritone/utils/PathRenderer.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index fc3a6370..4d226617 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -72,8 +72,8 @@ public final class LookBehavior extends Behavior implements ILookBehavior { float oldPitch = ctx.player().rotationPitch; float desiredPitch = this.target.getPitch(); ctx.player().rotationPitch = desiredPitch; - if (desiredPitch == oldPitch) { - //nudgeToLevel(); + if (desiredPitch == oldPitch && Baritone.settings().freeLook.value) { + nudgeToLevel(); } this.target = null; } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 9840e76e..0c9a45f3 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -175,7 +175,7 @@ public final class PathRenderer implements Helper { } GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], alpha); } - drawLine(player, x1, y1, z1, x2, y2, z2); + drawLine(x1, y1, z1, x2, y2, z2); tessellator.draw(); } if (Baritone.settings().renderPathIgnoreDepth.value) { @@ -187,7 +187,7 @@ public final class PathRenderer implements Helper { GlStateManager.disableBlend(); } - public static void drawLine(Entity player, double bp1x, double bp1y, double bp1z, double bp2x, double bp2y, double bp2z) { + public static void drawLine(double bp1x, double bp1y, double bp1z, double bp2x, double bp2y, double bp2z) { double d0 = mc.getRenderManager().viewerPosX; double d1 = mc.getRenderManager().viewerPosY; double d2 = mc.getRenderManager().viewerPosZ; From bd64f73842a84ffb9877a91ee3529be2a3ea4609 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 21 Mar 2019 15:44:20 -0700 Subject: [PATCH 295/682] fix disconnect on arrival not firing for custom goal process --- src/main/java/baritone/process/CustomGoalProcess.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index fe361ad6..4003b7a7 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -90,6 +90,9 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG } if (this.goal == null || (this.goal.isInGoal(ctx.playerFeet()) && this.goal.isInGoal(baritone.getPathingBehavior().pathStart()))) { onLostControl(); // we're there xd + if (Baritone.settings().disconnectOnArrival.value) { + ctx.world().sendQuittingDisconnectingPacket(); + } return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL); } return new PathingCommand(this.goal, PathingCommandType.SET_GOAL_AND_PATH); From d4103a924dc72839812e8d53763ee6e5f340db0d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 21 Mar 2019 16:58:31 -0700 Subject: [PATCH 296/682] add two new awesome badges --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f292bc64..f498951c 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ [![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-red.svg)](https://github.com/zeroeightysix/KAMI/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soon™-red.svg)](https://github.com/fr1kin/ForgeHax) +[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com) +[![forthebadge](https://forthebadge.com/images/badges/mom-made-pizza-rolls.svg)](http://forthebadge.com) A Minecraft pathfinder bot. From ac1ac50158e1b463e93e59ba8d39881cf080da58 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 22 Mar 2019 14:36:21 -0700 Subject: [PATCH 297/682] add some builder commands to usage --- USAGE.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/USAGE.md b/USAGE.md index 2750ac78..22460378 100644 --- a/USAGE.md +++ b/USAGE.md @@ -34,7 +34,7 @@ Some common examples: - `cancel` or `stop` to stop everything - `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part) - `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) -- `click` to click your destination on the screen. left click to path into it, right click to path on top of it. +- `click` to click your destination on the screen. left click to path into it, right click to path on top of it. left click and drag to clear an area. - `follow playerName` to follow a player. `follow` to follow the entity you're looking at (only works if it hitting range). `followplayers` to follow any players in range (combine with Kill Aura for a fun time). - `save waypointName` to save a waypoint. `goto waypointName` to go to it. - `axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120). @@ -42,6 +42,7 @@ Some common examples: - `render` to rerender the world in case `renderCachedChunks` is being glitchy - `version` to get the version of Baritone you're running - `damn` daniel +- `build` to build a schematic. `build blah` will load `schematics/blah.schematic` and build it with the origin being your player feet. `build blah x y z` to set the origin. Any of those can be relative to your player (`~ 69 ~-420` would build at x=player x, y=69, z=player z-420). For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java). From f58b6b41cb72ce6589d6f59b775a3da8dc7be6db Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 22 Mar 2019 15:45:34 -0700 Subject: [PATCH 298/682] second attempt at backfill --- src/api/java/baritone/api/Settings.java | 5 + src/main/java/baritone/Baritone.java | 2 + .../baritone/behavior/InventoryBehavior.java | 6 +- .../baritone/pathing/movement/Movement.java | 4 + .../pathing/movement/MovementHelper.java | 11 +- .../movement/movements/MovementPillar.java | 2 +- .../baritone/process/BackfillProcess.java | 136 ++++++++++++++++++ .../baritone/utils/PathingControlManager.java | 8 +- 8 files changed, 163 insertions(+), 11 deletions(-) create mode 100644 src/main/java/baritone/process/BackfillProcess.java diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index c70d60de..2a14e8df 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -398,6 +398,11 @@ public final class Settings { */ public final Setting containerMemory = new Setting<>(false); + /** + * Fill in blocks behind you + */ + public final Setting backfill = new Setting<>(false); + /** * Print all the debug messages to chat */ diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index f7a20b0f..9d93f68f 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 CustomGoalProcess customGoalProcess; private BuilderProcess builderProcess; private ExploreProcess exploreProcess; + private BackfillProcess backfillProcess; private PathingControlManager pathingControlManager; @@ -120,6 +121,7 @@ public class Baritone implements IBaritone { getToBlockProcess = new GetToBlockProcess(this); builderProcess = new BuilderProcess(this); exploreProcess = new ExploreProcess(this); + backfillProcess = new BackfillProcess(this); } this.worldProvider = new WorldProvider(); diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 120bc748..ae8e5bfa 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -130,13 +130,13 @@ public class InventoryBehavior extends Behavior { return false; } - public boolean selectThrowawayForLocation(int x, int y, int z) { + public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) { IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z); - if (maybe != null && throwaway(true, item -> item instanceof ItemBlock && ((ItemBlock) item).getBlock().equals(maybe.getBlock()))) { + if (maybe != null && throwaway(select, item -> item instanceof ItemBlock && ((ItemBlock) item).getBlock().equals(maybe.getBlock()))) { return true; // gotem } for (Item item : Baritone.settings().acceptableThrowawayItems.value) { - if (throwaway(true, item::equals)) { + if (throwaway(select, item::equals)) { return true; } } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 96b650e7..8c0ba2f8 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -270,4 +270,8 @@ public abstract class Movement implements IMovement, MovementHelper { } return toWalkIntoCached; } + + public BlockPos[] toBreakAll() { + return positionsToBreak; + } } diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 12ab8e72..a7247df3 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -478,8 +478,8 @@ public interface MovementHelper extends ActionCosts, Helper { for (int i = 0; i < 5; i++) { BlockPos against1 = placeAt.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); if (MovementHelper.canPlaceAgainst(ctx, against1)) { - if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(placeAt.getX(), placeAt.getY(), placeAt.getZ())) { // get ready to place a throwaway block - Helper.HELPER.logDebug("bb pls get me some blocks. dirt or cobble"); + if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(false, placeAt.getX(), placeAt.getY(), placeAt.getZ())) { // get ready to place a throwaway block + Helper.HELPER.logDebug("bb pls get me some blocks. dirt, netherrack, cobble"); state.setStatus(MovementStatus.UNREACHABLE); return PlaceResult.NO_OPTION; } @@ -505,10 +505,15 @@ public interface MovementHelper extends ActionCosts, Helper { EnumFacing side = ctx.objectMouseOver().sideHit; // only way for selectedBlock.equals(placeAt) to be true is if it's replacable if (selectedBlock.equals(placeAt) || (MovementHelper.canPlaceAgainst(ctx, selectedBlock) && selectedBlock.offset(side).equals(placeAt))) { + ((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(true, placeAt.getX(), placeAt.getY(), placeAt.getZ()); return PlaceResult.READY_TO_PLACE; } } - return found ? PlaceResult.ATTEMPTING : PlaceResult.NO_OPTION; + if (found) { + ((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(true, placeAt.getX(), placeAt.getY(), placeAt.getZ()); + return PlaceResult.ATTEMPTING; + } + return PlaceResult.NO_OPTION; } enum PlaceResult { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index cbe375de..1d849353 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -208,7 +208,7 @@ public class MovementPillar extends Movement { return state; } else { // Get ready to place a throwaway block - if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(src.x, src.y, src.z)) { + if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(true, src.x, src.y, src.z)) { return state.setStatus(MovementStatus.UNREACHABLE); } diff --git a/src/main/java/baritone/process/BackfillProcess.java b/src/main/java/baritone/process/BackfillProcess.java new file mode 100644 index 00000000..193204ae --- /dev/null +++ b/src/main/java/baritone/process/BackfillProcess.java @@ -0,0 +1,136 @@ +/* + * 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.api.utils.input.Input; +import baritone.pathing.movement.Movement; +import baritone.pathing.movement.MovementHelper; +import baritone.pathing.movement.MovementState; +import baritone.pathing.path.PathExecutor; +import baritone.utils.BaritoneProcessHelper; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.chunk.EmptyChunk; + +import java.util.*; +import java.util.stream.Collectors; + +public class BackfillProcess extends BaritoneProcessHelper { + + public HashMap blocksToReplace = new HashMap<>(); + + public BackfillProcess(Baritone baritone) { + super(baritone); + } + + @Override + public boolean isActive() { + if (!Baritone.settings().backfill.value) { + return false; + } + if (Baritone.settings().allowParkour.value) { + logDirect("Backfill cannot be used with allowParkour true"); + Baritone.settings().backfill.value = false; + return false; + } + amIBreakingABlockHMMMMMMM(); + for (BlockPos pos : new ArrayList<>(blocksToReplace.keySet())) { + if (ctx.world().getChunk(pos) instanceof EmptyChunk) { + blocksToReplace.remove(pos); + } + } + baritone.getInputOverrideHandler().clearAllKeys(); + + return !toFillIn().isEmpty(); + } + + @Override + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + if (!isSafeToCancel) { + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + baritone.getInputOverrideHandler().clearAllKeys(); + for (BlockPos toPlace : toFillIn()) { + MovementState fake = new MovementState(); + switch (MovementHelper.attemptToPlaceABlock(fake, baritone, toPlace, false)) { + case NO_OPTION: + continue; + case READY_TO_PLACE: + baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + case ATTEMPTING: + // patience + baritone.getLookBehavior().updateTarget(fake.getTarget().getRotation().get(), true); + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + } + return null; // cede to other process + } + + public void amIBreakingABlockHMMMMMMM() { + if (!ctx.getSelectedBlock().isPresent()) { + return; + } + blocksToReplace.put(ctx.getSelectedBlock().get(), ctx.world().getBlockState(ctx.getSelectedBlock().get())); + } + + public List toFillIn() { + return blocksToReplace + .keySet() + .stream() + .filter(pos -> ctx.world().getBlockState(pos).getBlock() == Blocks.AIR) + .filter(pos -> ctx.world().mayPlace(Blocks.DIRT, pos, false, EnumFacing.UP, null)) + .filter(pos -> !partOfCurrentMovement(pos)) + .sorted(Comparator.comparingDouble(ctx.player()::getDistanceSq).reversed()) + .collect(Collectors.toList()); + } + + private boolean partOfCurrentMovement(BlockPos pos) { + PathExecutor exec = baritone.getPathingBehavior().getCurrent(); + if (exec == null || exec.finished() || exec.failed()) { + return false; + } + Movement movement = (Movement) exec.getPath().movements().get(exec.getPosition()); + return Arrays.asList(movement.toBreakAll()).contains(pos); + } + + @Override + public void onLostControl() { + blocksToReplace = new HashMap<>(); + } + + @Override + public String displayName0() { + return "Backfill"; + } + + @Override + public boolean isTemporary() { + return true; + } + + @Override + public double priority() { + return 5; + } +} diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index f6a6954d..46b69ec2 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -92,8 +92,8 @@ public class PathingControlManager implements IPathingControlManager { p.secretInternalSetGoal(null); return; } - if (inControlThisTick != inControlLastTick && command.commandType != PathingCommandType.REQUEST_PAUSE) { - // if control has changed, and the new process wants to do something + if (inControlThisTick != inControlLastTick && command.commandType != PathingCommandType.REQUEST_PAUSE && inControlLastTick != null && !inControlLastTick.isTemporary()) { + // if control has changed from a real process to another real process, and the new process wants to do something p.cancelSegmentIfSafe(); // get rid of the in progress stuff from the last process } @@ -199,10 +199,10 @@ public class PathingControlManager implements IPathingControlManager { PathingCommand exec = proc.onTick(Objects.equals(proc, inControlLastTick) && baritone.getPathingBehavior().calcFailedLastTick(), baritone.getPathingBehavior().isSafeToCancel()); if (exec == null) { - if (proc.isActive()) { + /*if (proc.isActive()) { throw new IllegalStateException(proc.displayName() + " returned null PathingCommand"); } - proc.onLostControl(); + proc.onLostControl();*/ } else { inControlThisTick = proc; if (!proc.isTemporary()) { From bc49b2d5ba9bb8871f2f08a919629f1f1ec5275a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 22 Mar 2019 15:50:23 -0700 Subject: [PATCH 299/682] add allowDownward, fixes #369 --- src/api/java/baritone/api/Settings.java | 7 +++++++ .../java/baritone/pathing/movement/CalculationContext.java | 2 ++ .../pathing/movement/movements/MovementDownward.java | 3 +++ 3 files changed, 12 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index c70d60de..b2d89fd8 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -121,6 +121,13 @@ public final class Settings { */ public final Setting allowDiagonalDescend = new Setting<>(false); + /** + * Allow mining the block directly beneath its feet + *

+ * Turn this off to force it to make more staircases and less shafts + */ + public final Setting allowDownward = new Setting<>(true); + /** * Blocks that Baritone is allowed to place (as throwaway, for sneak bridging, pillaring, etc.) */ diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 6edb8953..4dda3283 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -60,6 +60,7 @@ public class CalculationContext { public final boolean allowJumpAt256; public final boolean assumeWalkOnWater; public final boolean allowDiagonalDescend; + public final boolean allowDownward; public final int maxFallHeightNoWater; public final int maxFallHeightBucket; public final double waterWalkSpeed; @@ -91,6 +92,7 @@ public class CalculationContext { this.allowJumpAt256 = Baritone.settings().allowJumpAt256.value; this.assumeWalkOnWater = Baritone.settings().assumeWalkOnWater.value; this.allowDiagonalDescend = Baritone.settings().allowDiagonalDescend.value; + this.allowDownward = Baritone.settings().allowDownward.value; this.maxFallHeightNoWater = Baritone.settings().maxFallHeightNoWater.value; this.maxFallHeightBucket = Baritone.settings().maxFallHeightBucket.value; int depth = EnchantmentHelper.getDepthStriderModifier(player); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java index 2bec8fcf..47ed9580 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java @@ -48,6 +48,9 @@ public class MovementDownward extends Movement { } public static double cost(CalculationContext context, int x, int y, int z) { + if (!context.allowDownward) { + return COST_INF; + } if (!MovementHelper.canWalkOn(context.bsi, x, y - 2, z)) { return COST_INF; } From 170c2d35c2d380a9347bddc8e2bcdd8dce587624 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 22 Mar 2019 21:17:20 -0700 Subject: [PATCH 300/682] perhaps updating debian will help --- Dockerfile | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Dockerfile b/Dockerfile index bec43d69..020bea0c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,17 +1,16 @@ -FROM debian:jessie +FROM debian:stretch -RUN echo 'deb http://deb.debian.org/debian jessie-backports main' > /etc/apt/sources.list.d/jessie-backports.list +RUN echo 'deb http://deb.debian.org/debian stretch-backports main' > /etc/apt/sources.list.d/stretch-backports.list ENV DEBIAN_FRONTEND noninteractive RUN apt update -y -RUN apt install --target-release jessie-backports \ +RUN apt install \ openjdk-8-jdk \ - ca-certificates-java \ --assume-yes -RUN apt install -qq --force-yes mesa-utils libgl1-mesa-glx libxcursor1 libxrandr2 libxxf86vm1 x11-xserver-utils xfonts-base xserver-common +RUN apt install -qq --assume-yes mesa-utils libgl1-mesa-glx libxcursor1 libxrandr2 libxxf86vm1 x11-xserver-utils xfonts-base xserver-common COPY . /code @@ -21,4 +20,4 @@ WORKDIR /code # source: https://github.com/tectonicus/tectonicus/issues/60#issuecomment-154239173 RUN dpkg -i scripts/xvfb_1.16.4-1_amd64.deb -RUN ./gradlew build \ No newline at end of file +RUN ./gradlew build From 71491a792285070a5a606ba6669b5030494f9549 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 23 Mar 2019 22:17:40 -0800 Subject: [PATCH 301/682] blank space --- .../baritone/pathing/movement/movements/MovementAscend.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index b7b7eb5f..2ba10f70 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -197,9 +197,7 @@ public class MovementAscend extends Movement { if (headBonkClear()) { return state.setInput(Input.JUMP, true); } - - - // System.out.println(flatDistToNext + " " + sideDist); + if (flatDistToNext > 1.2 || sideDist > 0.2) { return state; } From a8f373d56851addbafe9d31fa4a7fc50166ccacd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 24 Mar 2019 13:07:08 -0700 Subject: [PATCH 302/682] fine; assumewalkonlava --- src/api/java/baritone/api/Settings.java | 5 +++++ src/main/java/baritone/pathing/movement/MovementHelper.java | 3 +++ 2 files changed, 8 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index b2d89fd8..1e34371e 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -91,6 +91,11 @@ public final class Settings { */ public final Setting assumeWalkOnWater = new Setting<>(false); + /** + * If you have Fire Resistance and Jesus then I guess you could turn this on lol + */ + public final Setting assumeWalkOnLava = new Setting<>(false); + /** * Assume step functionality; don't jump on an Ascend. */ diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 12ab8e72..aeac6bcb 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -290,6 +290,9 @@ public interface MovementHelper extends ActionCosts, Helper { // if assumeWalkOnWater is off, we can only walk on water if there is water above it return isWater(up) ^ Baritone.settings().assumeWalkOnWater.value; } + if (Baritone.settings().assumeWalkOnLava.value && isLava(block)) { + return true; + } if (block == Blocks.GLASS || block == Blocks.STAINED_GLASS) { return true; } From 27e39c80831ec037595e73a961cb50a59aa94f0d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 24 Mar 2019 13:50:50 -0700 Subject: [PATCH 303/682] update badges --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f498951c..6baca457 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) -[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.3-brightgreen.svg)](https://impactdevelopment.github.io/) +[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.5%20/%20v1.3.0-brightgreen.svg)](https://impactdevelopment.github.io/) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-red.svg)](https://github.com/zeroeightysix/KAMI/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) From 2e8fdd43ee9a72bc23b748dd74161404f7a8f9bd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 24 Mar 2019 13:53:19 -0700 Subject: [PATCH 304/682] no flowing --- src/main/java/baritone/pathing/movement/MovementHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index aeac6bcb..447e4f08 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -290,7 +290,7 @@ public interface MovementHelper extends ActionCosts, Helper { // if assumeWalkOnWater is off, we can only walk on water if there is water above it return isWater(up) ^ Baritone.settings().assumeWalkOnWater.value; } - if (Baritone.settings().assumeWalkOnLava.value && isLava(block)) { + if (Baritone.settings().assumeWalkOnLava.value && isLava(block) && !isFlowing(x, y, z, state, bsi)) { return true; } if (block == Blocks.GLASS || block == Blocks.STAINED_GLASS) { From 9fcae6560e350e91c7d2178fcd24b22477be1f57 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 25 Mar 2019 21:03:19 -0800 Subject: [PATCH 305/682] better feature branch example --- SETUP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SETUP.md b/SETUP.md index 49ab838f..1767e2c5 100644 --- a/SETUP.md +++ b/SETUP.md @@ -1,7 +1,7 @@ # Installation ## Prebuilt official releases -These releases are not always completely up to date with latest features, and are only released from `master`. (so if you want `builder` branch for example, you'll have to build it yourself) +These releases are not always completely up to date with latest features, and are only released from `master`. (so if you want `backfill-2` branch for example, you'll have to build it yourself) Link to the releases page: [Releases](https://github.com/cabaletta/baritone/releases) From d2de8828e7340452e1fa60913946e23ec8fdb695 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 26 Mar 2019 23:01:07 -0700 Subject: [PATCH 306/682] did this --- src/main/java/baritone/process/BuilderProcess.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 9dd6fc92..320d6030 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -275,13 +275,6 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { - // TODO somehow tell inventorybehavior what we'd like to have on the hotbar - // perhaps take the 16 closest positions in incorrectPositions to ctx.playerFeet that aren't desired to be air, and then snag the top 4 most common block states, then request those on the hotbar - - - // this will work as is, but it'll be trashy - // need to iterate over incorrectPositions and see which ones we can "correct" from our current standing position - baritone.getInputOverrideHandler().clearAllKeys(); BuilderCalculationContext bcc = new BuilderCalculationContext(); if (!recalc(bcc)) { From 926e2d56201a03705c8ee5e047580b22d27f5468 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 27 Mar 2019 17:32:02 -0700 Subject: [PATCH 307/682] add resuming to builder, fixes #371 --- .../java/baritone/process/BuilderProcess.java | 18 ++++++++++++++---- .../baritone/utils/ExampleBaritoneControl.java | 5 +++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 320d6030..8b2263ab 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -65,6 +65,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro private ISchematic schematic; private Vec3i origin; private int ticks; + private boolean paused; public boolean build(String schematicFile, BlockPos origin) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); @@ -77,6 +78,11 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro this.name = name; this.schematic = schematic; this.origin = origin; + this.paused = false; + } + + public void resume() { + paused = false; } @Override @@ -276,6 +282,9 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { baritone.getInputOverrideHandler().clearAllKeys(); + if (paused) { + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } BuilderCalculationContext bcc = new BuilderCalculationContext(); if (!recalc(bcc)) { logDirect("Done building"); @@ -352,9 +361,9 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro if (goal == null) { goal = assemble(bcc, approxPlacable); // we're far away, so assume that we have our whole inventory to recalculate placable properly if (goal == null) { - logDirect("Unable to do it =("); - onLostControl(); - return null; + logDirect("Unable to do it. Pausing. resume to resume, cancel to cancel"); + paused = true; + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } } return new PathingCommandContext(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc); @@ -533,11 +542,12 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro incorrectPositions = null; name = null; schematic = null; + paused = false; } @Override public String displayName0() { - return "Building " + name; + return paused ? "Builder Paused" : "Building " + name; } public List placable(int size) { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 6dbdf388..9b8dd488 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -353,6 +353,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { baritone.getBuilderProcess().clearArea(corner1, corner2); return true; } + if (msg.equals("resume")) { + baritone.getBuilderProcess().resume(); + logDirect("resumed"); + return true; + } if (msg.equals("reset")) { for (Settings.Setting setting : Baritone.settings().allSettings) { setting.reset(); From 3329db1dae08d0e709133fbfc89ac21f8c6ed7ba Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 28 Mar 2019 23:01:14 -0700 Subject: [PATCH 308/682] these show the exact same info; remove one --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 6baca457..ea03c406 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,6 @@ ![Code size](https://img.shields.io/github/languages/code-size/cabaletta/baritone.svg) ![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg) ![](https://tokei.rs/b1/github/cabaletta/baritone?category=code) -![](https://tokei.rs/b1/github/cabaletta/baritone?category=files) [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) From 71482cc9847e99e568d95889c93feb29d80a86b6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 29 Mar 2019 23:10:19 -0700 Subject: [PATCH 309/682] explain for brainlets --- src/api/java/baritone/api/Settings.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 1e34371e..c671b0fa 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -58,7 +58,9 @@ public final class Settings { /** * It doesn't actually take twenty ticks to place a block, this cost is so high - * because we want to generally conserve blocks which might be limited + * because we want to generally conserve blocks which might be limited. + *

+ * Decrease to make Baritone more often consider paths that would require placing blocks */ public final Setting blockPlacementPenalty = new Setting<>(20D); From 2c3dc5d6b181ffd817ed116353d1073b434616b9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 30 Mar 2019 23:23:12 -0700 Subject: [PATCH 310/682] add plea --- 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 c671b0fa..26b35f37 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -115,7 +115,7 @@ public final class Settings { /** * If true, parkour is allowed to make jumps when standing on blocks at the maximum height, so player feet is y=256 *

- * Defaults to false because this fails on constantiam + * Defaults to false because this fails on constantiam. Please let me know if this is ever disabled. Please. */ public final Setting allowJumpAt256 = new Setting<>(false); From af11e64cec40e2fc4ef0de11817fc61d14514164 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 31 Mar 2019 20:22:17 -0800 Subject: [PATCH 311/682] combine nested --- src/main/java/baritone/process/BuilderProcess.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 8b2263ab..852d239d 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -419,10 +419,8 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro for (int y = 0; y < schematic.heightY(); y++) { for (int z = 0; z < schematic.lengthZ(); z++) { for (int x = 0; x < schematic.widthX(); x++) { - if (schematic.inSchematic(x, y, z)) { - if (!valid(bcc.bsi.get0(x + origin.getX(), y + origin.getY(), z + origin.getZ()), schematic.desiredState(x, y, z))) { - incorrectPositions.add(new BetterBlockPos(x + origin.getX(), y + origin.getY(), z + origin.getZ())); - } + if (schematic.inSchematic(x, y, z) && !valid(bcc.bsi.get0(x + origin.getX(), y + origin.getY(), z + origin.getZ()), schematic.desiredState(x, y, z))) { + incorrectPositions.add(new BetterBlockPos(x + origin.getX(), y + origin.getY(), z + origin.getZ())); } } } From ccc3de2d7c96f04fcce667b3441fb396c6551bf6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Apr 2019 23:30:33 -0700 Subject: [PATCH 312/682] dawn of the 8th month --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ea03c406..e016fa94 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Baritone is the pathfinding system used in [Impact](https://impactdevelopment.gi 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. 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). -Have committed at least once a day for the last 7 months =D 🦀 +Have committed at least once a day for the last 8 months =D 🦀 1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2 From 71a2219b073fe8a01559dbd609e30b94e690021a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 2 Apr 2019 21:40:33 -0800 Subject: [PATCH 313/682] move fields to the top --- src/main/java/baritone/process/BuilderProcess.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 852d239d..0dabc697 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -55,11 +55,7 @@ import java.util.stream.Collectors; import static baritone.api.pathing.movement.ActionCosts.COST_INF; public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { - - public BuilderProcess(Baritone baritone) { - super(baritone); - } - + private HashSet incorrectPositions; private String name; private ISchematic schematic; @@ -67,6 +63,10 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro private int ticks; private boolean paused; + public BuilderProcess(Baritone baritone) { + super(baritone); + } + public boolean build(String schematicFile, BlockPos origin) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); System.out.println(file + " " + file.exists()); From 75b54dfaecaa9d9bd6b26a20739f22cceab44fc1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Apr 2019 23:19:32 -0700 Subject: [PATCH 314/682] nullpointer is confusing --- src/main/java/baritone/process/BuilderProcess.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 0dabc697..b0daf22d 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -55,7 +55,7 @@ import java.util.stream.Collectors; import static baritone.api.pathing.movement.ActionCosts.COST_INF; public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { - + private HashSet incorrectPositions; private String name; private ISchematic schematic; @@ -275,7 +275,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro double z = side.getZOffset() == 0 ? 0.5 : (1 + side.getZOffset()) / 2D; return new Vec3d[]{new Vec3d(x, 0.25, z), new Vec3d(x, 0.75, z)}; default: // null - throw new NullPointerException(); + throw new IllegalStateException(); } } From bf076f62464e0863b83bb2d4b7e492362ce79e45 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 4 Apr 2019 20:51:02 -0800 Subject: [PATCH 315/682] privatize --- src/main/java/baritone/process/BuilderProcess.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index b0daf22d..93c6734e 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -160,10 +160,10 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } public class Placement { - final int hotbarSelection; - final BlockPos placeAgainst; - final EnumFacing side; - final Rotation rot; + private final int hotbarSelection; + private final BlockPos placeAgainst; + private final EnumFacing side; + private final Rotation rot; public Placement(int hotbarSelection, BlockPos placeAgainst, EnumFacing side, Rotation rot) { this.hotbarSelection = hotbarSelection; From 87a9e67ba8956aed76eb48509141cb767d0c5af9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Apr 2019 11:59:28 -0700 Subject: [PATCH 316/682] dont reassign arg --- src/main/java/baritone/process/MineProcess.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index f2ebcd55..ff8d68ba 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -81,13 +81,14 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return null; } } + boolean shouldCancel = calcFailed; if (calcFailed && !knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) { logDirect("Unable to find any path to " + mining + ", blacklisting presumably unreachable closest instance..."); knownOreLocations.stream().sorted(Comparator.comparingDouble(ctx.player()::getDistanceSq)).findFirst().ifPresent(blacklist::add); knownOreLocations.removeIf(blacklist::contains); - calcFailed = false; // 😎 + shouldCancel = false; // 😎 } - if (calcFailed) { + if (shouldCancel) { logDirect("Unable to find any path to " + mining + ", canceling Mine"); cancel(); return null; From 867c01ff86588be6105c89d38647a948af2e7f34 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 6 Apr 2019 21:50:22 -0800 Subject: [PATCH 317/682] crucial performance optimization --- 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 ff8d68ba..07e47b91 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -84,7 +84,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro boolean shouldCancel = calcFailed; if (calcFailed && !knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) { logDirect("Unable to find any path to " + mining + ", blacklisting presumably unreachable closest instance..."); - knownOreLocations.stream().sorted(Comparator.comparingDouble(ctx.player()::getDistanceSq)).findFirst().ifPresent(blacklist::add); + knownOreLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(blacklist::add); knownOreLocations.removeIf(blacklist::contains); shouldCancel = false; // 😎 } From e54652941b9879301d6cb3769ddcbbe8947520bb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Apr 2019 17:44:23 -0700 Subject: [PATCH 318/682] codacy --- src/main/java/baritone/process/BuilderProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 93c6734e..56115b49 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -498,7 +498,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } public static class GoalAdjacent extends GoalGetToBlock { - boolean allowSameLevel; + private boolean allowSameLevel; public GoalAdjacent(BlockPos pos, boolean allowSameLevel) { super(pos); From 6b6eea2d8c165dd976245f530b76228ab3973358 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 8 Apr 2019 20:32:47 -0800 Subject: [PATCH 319/682] add renderSelectionBoxes, fixes #378 --- src/api/java/baritone/api/Settings.java | 5 +++++ src/main/java/baritone/utils/PathRenderer.java | 16 ++++++++-------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 26b35f37..9793cf6b 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -438,6 +438,11 @@ public final class Settings { */ public final Setting renderGoal = new Setting<>(true); + /** + * Render selection boxes + */ + public final Setting renderSelectionBoxes = new Setting<>(true); + /** * Ignore depth when rendering the goal */ diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 0c9a45f3..90fd2649 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -83,6 +83,14 @@ public final class PathRenderer implements Helper { if (goal != null && Baritone.settings().renderGoal.value) { drawDankLitGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.value); } + 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 && Baritone.settings().renderSelectionBoxes.value) { + drawManySelectionBoxes(renderView, current.toBreak(), Baritone.settings().colorBlocksToBreak.value); + drawManySelectionBoxes(renderView, current.toPlace(), Baritone.settings().colorBlocksToPlace.value); + drawManySelectionBoxes(renderView, current.toWalkInto(), Baritone.settings().colorBlocksToWalkInto.value); + } if (!Baritone.settings().renderPath.value) { return; } @@ -91,9 +99,6 @@ public final class PathRenderer implements Helper { //long start = System.nanoTime(); - PathExecutor current = behavior.getCurrent(); // this should prevent most race conditions? - PathExecutor next = behavior.getNext(); // like, now it's not possible for current!=null to be true, then suddenly false because of another thread - // Render the current path, if there is one if (current != null && current.getPath() != null) { int renderBegin = Math.max(current.getPosition() - 3, 0); @@ -104,11 +109,6 @@ public final class PathRenderer implements Helper { } //long split = System.nanoTime(); - if (current != null) { - drawManySelectionBoxes(renderView, current.toBreak(), Baritone.settings().colorBlocksToBreak.value); - drawManySelectionBoxes(renderView, current.toPlace(), Baritone.settings().colorBlocksToPlace.value); - drawManySelectionBoxes(renderView, current.toWalkInto(), Baritone.settings().colorBlocksToWalkInto.value); - } // If there is a path calculation currently running, render the path calculation process behavior.getInProgress().ifPresent(currentlyRunning -> { From fc3f183dce44ad8755061b94107d55143475b87b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 9 Apr 2019 08:45:30 -0700 Subject: [PATCH 320/682] actually don't render the boxes if renderpath is false --- src/main/java/baritone/utils/PathRenderer.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 90fd2649..e4fd58b1 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -83,17 +83,17 @@ public final class PathRenderer implements Helper { if (goal != null && Baritone.settings().renderGoal.value) { drawDankLitGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.value); } + + if (!Baritone.settings().renderPath.value) { + return; + } 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 && Baritone.settings().renderSelectionBoxes.value) { drawManySelectionBoxes(renderView, current.toBreak(), Baritone.settings().colorBlocksToBreak.value); drawManySelectionBoxes(renderView, current.toPlace(), Baritone.settings().colorBlocksToPlace.value); drawManySelectionBoxes(renderView, current.toWalkInto(), Baritone.settings().colorBlocksToWalkInto.value); } - if (!Baritone.settings().renderPath.value) { - return; - } //drawManySelectionBoxes(player, Collections.singletonList(behavior.pathStart()), partialTicks, Color.WHITE); //long start = System.nanoTime(); From ce59ef559fccfb2ceb925b539f88ea479038c950 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 9 Apr 2019 19:35:43 -0700 Subject: [PATCH 321/682] backport important world scanner fixes --- .../java/baritone/cache/WorldScanner.java | 37 +++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index 463dd22f..91cc0f54 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -28,15 +28,15 @@ import net.minecraft.world.chunk.BlockStateContainer; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; +import java.util.*; +import java.util.stream.IntStream; public enum WorldScanner implements IWorldScanner { INSTANCE; + private static final int[] DEFAULT_COORDINATE_ITERATION_ORDER = IntStream.range(0, 16).toArray(); + @Override public List scanChunkRadius(IPlayerContext ctx, List blocks, int max, int yLevelThreshold, int maxSearchRadius) { if (blocks.contains(null)) { @@ -53,6 +53,9 @@ public enum WorldScanner implements IWorldScanner { int playerChunkZ = ctx.playerFeet().getZ() >> 4; int playerY = ctx.playerFeet().getY(); + int playerYBlockStateContainerIndex = playerY >> 4; + int[] coordinateIterationOrder = IntStream.range(0, 16).boxed().sorted(Comparator.comparingInt(y -> Math.abs(y - playerYBlockStateContainerIndex))).mapToInt(x -> x).toArray(); + int searchRadiusSq = 0; boolean foundWithinY = false; while (true) { @@ -72,7 +75,9 @@ public enum WorldScanner implements IWorldScanner { continue; } allUnloaded = false; - scanChunkInto(chunkX << 4, chunkZ << 4, chunk, blocks, res, max, yLevelThreshold, playerY); + if (scanChunkInto(chunkX << 4, chunkZ << 4, chunk, blocks, res, max, yLevelThreshold, playerY, coordinateIterationOrder)) { + foundWithinY = true; + } } } if ((allUnloaded && foundChunks) @@ -100,13 +105,15 @@ public enum WorldScanner implements IWorldScanner { } ArrayList res = new ArrayList<>(); - scanChunkInto(pos.x << 4, pos.z << 4, chunk, blocks, res, max, yLevelThreshold, playerY); + scanChunkInto(pos.x << 4, pos.z << 4, chunk, blocks, res, max, yLevelThreshold, playerY, DEFAULT_COORDINATE_ITERATION_ORDER); return res; } - public void scanChunkInto(int chunkX, int chunkZ, Chunk chunk, List search, Collection result, int max, int yLevelThreshold, int playerY) { + private boolean scanChunkInto(int chunkX, int chunkZ, Chunk chunk, List search, Collection result, int max, int yLevelThreshold, int playerY, int[] coordinateIterationOrder) { ExtendedBlockStorage[] chunkInternalStorageArray = chunk.getBlockStorageArray(); - for (int y0 = 0; y0 < 16; y0++) { + boolean foundWithinY = false; + for (int yIndex = 0; yIndex < 16; yIndex++) { + int y0 = coordinateIterationOrder[yIndex]; ExtendedBlockStorage extendedblockstorage = chunkInternalStorageArray[y0]; if (extendedblockstorage == null) { continue; @@ -121,14 +128,22 @@ public enum WorldScanner implements IWorldScanner { IBlockState state = bsc.get(x, y, z); if (search.contains(state.getBlock())) { int yy = yReal | y; - result.add(new BlockPos(chunkX | x, yy, chunkZ | z)); - if (result.size() >= max && Math.abs(yy - playerY) < yLevelThreshold) { - return; + if (result.size() >= max) { + if (Math.abs(yy - playerY) < yLevelThreshold) { + foundWithinY = true; + } else { + if (foundWithinY) { + // have found within Y in this chunk, so don't need to consider outside Y + return true; + } + } } + result.add(new BlockPos(chunkX | x, yy, chunkZ | z)); } } } } } + return foundWithinY; } } From 76cdaaace614a9bd799aba42eeccd69dd5790844 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 10 Apr 2019 23:45:52 -0700 Subject: [PATCH 322/682] add todo --- src/main/java/baritone/cache/WorldScanner.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index 91cc0f54..d6cf69c3 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -134,6 +134,7 @@ public enum WorldScanner implements IWorldScanner { } else { if (foundWithinY) { // have found within Y in this chunk, so don't need to consider outside Y + // TODO continue iteration to one more sorted Y coordinate block return true; } } From 2bf475d84005f23823e68df2c174fa3b304d2c2a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Apr 2019 15:17:26 -0700 Subject: [PATCH 323/682] build in layers test --- src/api/java/baritone/api/Settings.java | 5 +++ .../java/baritone/process/BuilderProcess.java | 37 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 9793cf6b..3a1c9fba 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -566,6 +566,11 @@ public final class Settings { */ public final Setting exploreForBlocks = new Setting<>(true); + /** + * Don't consider the next layer in builder until the current one is done + */ + public final Setting buildInLayers = new Setting<>(false); + /** * While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)? */ diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 56115b49..6c38b7ff 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -58,10 +58,12 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro private HashSet incorrectPositions; private String name; + private ISchematic realSchematic; private ISchematic schematic; private Vec3i origin; private int ticks; private boolean paused; + private int layer; public BuilderProcess(Baritone baritone) { super(baritone); @@ -77,8 +79,10 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro public void build(String name, ISchematic schematic, Vec3i origin) { this.name = name; this.schematic = schematic; + this.realSchematic = null; this.origin = origin; this.paused = false; + this.layer = 0; } public void resume() { @@ -285,8 +289,39 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro if (paused) { return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } + if (Baritone.settings().buildInLayers.value) { + if (realSchematic == null) { + realSchematic = schematic; + } + schematic = new ISchematic() { + @Override + public IBlockState desiredState(int x, int y, int z) { + return realSchematic.desiredState(x, y, z); + } + + @Override + public int widthX() { + return realSchematic.widthX(); + } + + @Override + public int heightY() { + return layer; + } + + @Override + public int lengthZ() { + return realSchematic.lengthZ(); + } + }; + } BuilderCalculationContext bcc = new BuilderCalculationContext(); if (!recalc(bcc)) { + if (Baritone.settings().buildInLayers.value && layer < realSchematic.heightY()) { + logDirect("Starting layer " + layer); + layer++; + return onTick(calcFailed, isSafeToCancel); + } logDirect("Done building"); onLostControl(); return null; @@ -540,6 +575,8 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro incorrectPositions = null; name = null; schematic = null; + realSchematic = null; + layer = 0; paused = false; } From a09bb0d53865a17e5869b0eba14015e4ddc5e34a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Apr 2019 16:36:20 -0700 Subject: [PATCH 324/682] build repeat option --- src/api/java/baritone/api/Settings.java | 11 +++++++ .../java/baritone/api/utils/ISchematic.java | 14 +++++++++ .../java/baritone/process/BuilderProcess.java | 29 +++++++++++++------ 3 files changed, 45 insertions(+), 9 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 3a1c9fba..b61656a9 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -21,6 +21,7 @@ import baritone.api.utils.SettingsUtil; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.item.Item; +import net.minecraft.util.EnumFacing; import net.minecraft.util.text.ITextComponent; import java.awt.*; @@ -571,6 +572,16 @@ public final class Settings { */ public final Setting buildInLayers = new Setting<>(false); + /** + * How far to move before repeating the build. -1 for the size of the build in that axis. 0 to disable + */ + public final Setting buildRepeatDistance=new Setting<>(0); + + /** + * What direction te repeat the build in + */ + public final Setting buildRepeatDirection = new Setting<>(EnumFacing.NORTH); + /** * While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)? */ diff --git a/src/api/java/baritone/api/utils/ISchematic.java b/src/api/java/baritone/api/utils/ISchematic.java index 1f2cd874..821dc68c 100644 --- a/src/api/java/baritone/api/utils/ISchematic.java +++ b/src/api/java/baritone/api/utils/ISchematic.java @@ -18,6 +18,7 @@ package baritone.api.utils; import net.minecraft.block.state.IBlockState; +import net.minecraft.util.EnumFacing; /** * Basic representation of a schematic. Provides the dimensions and @@ -44,6 +45,19 @@ public interface ISchematic { return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ(); } + default int size(EnumFacing.Axis axis) { + switch (axis) { + case X: + return widthX(); + case Y: + return heightY(); + case Z: + return lengthZ(); + default: + throw new UnsupportedOperationException(axis + ""); + } + } + /** * Returns the desired block state at a given (X, Y, Z) position relative to the origin (0, 0, 0). * diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 6c38b7ff..4e4fc3df 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -285,6 +285,11 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) { + ticks = 5; + } else { + ticks--; + } baritone.getInputOverrideHandler().clearAllKeys(); if (paused) { return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); @@ -322,18 +327,24 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro layer++; return onTick(calcFailed, isSafeToCancel); } - logDirect("Done building"); - onLostControl(); - return null; + int distance = Baritone.settings().buildRepeatDistance.value; + EnumFacing direction = Baritone.settings().buildRepeatDirection.value; + if (distance == 0) { + logDirect("Done building"); + onLostControl(); + return null; + } + // build repeat time + if (distance == -1) { + distance = schematic.size(direction.getAxis()); + } + layer = 0; + origin = new BlockPos(origin).offset(direction, distance); + logDirect("Repeating build " + distance + " blocks to the " + direction + ", new origin is " + origin); } trim(bcc); - if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) { - ticks = 5; - } else { - ticks--; - } + Optional> toBreak = toBreakNearPlayer(bcc); - baritone.getInputOverrideHandler().clearAllKeys(); if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) { // we'd like to pause to break this block // only change look direction if it's safe (don't want to fuck up an in progress parkour for example From 65cd6a92d316dad4ce8346c69d69dd1438b1ed41 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Apr 2019 16:42:04 -0700 Subject: [PATCH 325/682] allow saving enumfacing value --- src/api/java/baritone/api/utils/SettingsUtil.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 051e8793..ae97ad7b 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -19,6 +19,7 @@ package baritone.api.utils; import baritone.api.Settings; import net.minecraft.item.Item; +import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import java.awt.*; @@ -147,7 +148,9 @@ public class SettingsUtil { LONG(Long.class, Long::parseLong), ITEM_LIST(ArrayList.class, str -> Stream.of(str.split(",")).map(Item::getByNameOrId).collect(Collectors.toCollection(ArrayList::new)), list -> ((ArrayList) list).stream().map(Item.REGISTRY::getNameForObject).map(ResourceLocation::toString).collect(Collectors.joining(","))), - COLOR(Color.class, str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])), color -> color.getRed() + "," + color.getGreen() + "," + color.getBlue()); + COLOR(Color.class, str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])), color -> color.getRed() + "," + color.getGreen() + "," + color.getBlue()), + ENUMFACING(EnumFacing.class, EnumFacing::byName); + Class klass; From fcadf68c900ba867ac71b410f6675ec40b4d9dcf Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Apr 2019 17:42:50 -0700 Subject: [PATCH 326/682] cool tunnel feature and various fixes --- .../baritone/api/pathing/goals/GoalNear.java | 2 +- .../pathing/goals/GoalStrictDirection.java | 76 +++++++++++++++++++ .../java/baritone/behavior/LookBehavior.java | 2 +- .../movement/movements/MovementTraverse.java | 17 +++-- .../utils/ExampleBaritoneControl.java | 5 ++ 5 files changed, 92 insertions(+), 10 deletions(-) create mode 100644 src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java diff --git a/src/api/java/baritone/api/pathing/goals/GoalNear.java b/src/api/java/baritone/api/pathing/goals/GoalNear.java index 6befda6b..4f75aba7 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalNear.java +++ b/src/api/java/baritone/api/pathing/goals/GoalNear.java @@ -61,6 +61,6 @@ public class GoalNear implements Goal, IGoalRenderPos { ", y=" + y + ", z=" + z + ", rangeSq=" + rangeSq + - '}'; + "}"; } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java new file mode 100644 index 00000000..749bed62 --- /dev/null +++ b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java @@ -0,0 +1,76 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.pathing.goals; + +import baritone.api.BaritoneAPI; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; + +/** + * Dig a tunnel in a certain direction, but if you have to deviate from the path, go back to where you started + */ +public class GoalStrictDirection implements Goal { + public final int x; + public final int y; + public final int z; + public final int dx; + public final int dz; + + public GoalStrictDirection(BlockPos origin, EnumFacing direction) { + x = origin.getX(); + y = origin.getY(); + z = origin.getZ(); + dx = direction.getXOffset(); + dz = direction.getZOffset(); + if (dx == 0 && dz == 0) { + throw new IllegalArgumentException(direction + ""); + } + } + + @Override + public boolean isInGoal(int x, int y, int z) { + return false; + } + + @Override + public double heuristic(int x, int y, int z) { + int distanceFromStartInDesiredDirection = (x - this.x) * dx + (z - this.z) * dz; + + int distanceFromStartInIncorrectDirection = Math.abs((x - this.x) * dz) + Math.abs((z - this.z) * dx); + + int verticalDistanceFromStart = Math.abs(y - this.y); + + // we want heuristic to decrease as desiredDirection increases + double heuristic = -distanceFromStartInDesiredDirection * 100; + + heuristic += distanceFromStartInIncorrectDirection * 1000; + heuristic += verticalDistanceFromStart * 1000; + return heuristic; + } + + @Override + public String toString() { + return "GoalStrictDirection{" + + "x=" + x + + ", y=" + y + + ", z=" + z + + ", dx=" + dx + + ", dz=" + dz + + "}"; + } +} diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index 4d226617..de131d12 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -72,7 +72,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior { float oldPitch = ctx.player().rotationPitch; float desiredPitch = this.target.getPitch(); ctx.player().rotationPitch = desiredPitch; - if (desiredPitch == oldPitch && Baritone.settings().freeLook.value) { + if (desiredPitch == oldPitch && !Baritone.settings().freeLook.value) { nudgeToLevel(); } this.target = null; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 966dae95..012180e5 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -30,10 +30,7 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; -import net.minecraft.block.Block; -import net.minecraft.block.BlockDoor; -import net.minecraft.block.BlockFenceGate; -import net.minecraft.block.BlockSlab; +import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; @@ -151,6 +148,8 @@ public class MovementTraverse extends Movement { @Override public MovementState updateState(MovementState state) { super.updateState(state); + IBlockState pb0 = BlockStateInterface.get(ctx, positionsToBreak[0]); + IBlockState pb1 = BlockStateInterface.get(ctx, positionsToBreak[1]); if (state.getStatus() != MovementStatus.RUNNING) { // if the setting is enabled if (!Baritone.settings().walkWhileBreaking.value) { @@ -161,10 +160,10 @@ public class MovementTraverse extends Movement { return state; } // and if it's fine to walk into the blocks in front - if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(ctx, positionsToBreak[0]).getBlock())) { + if (MovementHelper.avoidWalkingInto(pb0.getBlock())) { return state; } - if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(ctx, positionsToBreak[1]).getBlock())) { + if (MovementHelper.avoidWalkingInto(pb1.getBlock())) { return state; } // and we aren't already pressed up against the block @@ -177,6 +176,10 @@ public class MovementTraverse extends Movement { // it's safe to do this since the two blocks we break (in a traverse) are right on top of each other and so will have the same yaw float yawToDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), dest), ctx.playerRotations()).getYaw(); float pitchToBreak = state.getTarget().getRotation().get().getPitch(); + if ((pb0.isFullCube() || pb0.getBlock() instanceof BlockAir && (pb1.isFullCube() || pb1.getBlock() instanceof BlockAir))) { + // in the meantime, before we're right up against the block, we can break efficiently at this angle + pitchToBreak = 26; + } state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true)); return state.setInput(Input.MOVE_FORWARD, true).setInput(Input.SPRINT, true); @@ -187,8 +190,6 @@ public class MovementTraverse extends Movement { Block fd = BlockStateInterface.get(ctx, src.down()).getBlock(); boolean ladder = fd == Blocks.LADDER || fd == Blocks.VINE; - IBlockState pb0 = BlockStateInterface.get(ctx, positionsToBreak[0]); - IBlockState pb1 = BlockStateInterface.get(ctx, positionsToBreak[1]); boolean door = pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor; if (door) { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 9b8dd488..7b422ef2 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -366,6 +366,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Baritone settings reset"); return true; } + if (msg.equals("tunnel")) { + customGoalProcess.setGoalAndPath(new GoalStrictDirection(ctx.playerFeet(), ctx.player().getHorizontalFacing())); + logDirect("tunneling"); + return true; + } if (msg.equals("render")) { BetterBlockPos pf = ctx.playerFeet(); Minecraft.getMinecraft().renderGlobal.markBlockRangeForRenderUpdate(pf.x - 500, pf.y - 500, pf.z - 500, pf.x + 500, pf.y + 500, pf.z + 500); From 6e97fe22105ae744303516987613820ceab5bf52 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Apr 2019 21:48:02 -0700 Subject: [PATCH 327/682] dont crash when exiting a world --- src/main/java/baritone/process/BackfillProcess.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/baritone/process/BackfillProcess.java b/src/main/java/baritone/process/BackfillProcess.java index 193204ae..e2bb70da 100644 --- a/src/main/java/baritone/process/BackfillProcess.java +++ b/src/main/java/baritone/process/BackfillProcess.java @@ -45,6 +45,9 @@ public class BackfillProcess extends BaritoneProcessHelper { @Override public boolean isActive() { + if (ctx.player() == null || ctx.world() == null) { + return false; + } if (!Baritone.settings().backfill.value) { return false; } From 236d02cb47e25235e07380de4e35c8bed4b9a16f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 13 Apr 2019 08:36:14 -0700 Subject: [PATCH 328/682] add a way to pause builder --- src/main/java/baritone/process/BuilderProcess.java | 4 ++++ src/main/java/baritone/utils/ExampleBaritoneControl.java | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 4e4fc3df..4af6c800 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -89,6 +89,10 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro paused = false; } + public void pause() { + paused = true; + } + @Override public boolean build(String name, File schematic, Vec3i origin) { NBTTagCompound tag; diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 7b422ef2..f4261f07 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -358,6 +358,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("resumed"); return true; } + if (msg.equals("pause")) { + baritone.getBuilderProcess().pause(); + logDirect("paused"); + return true; + } if (msg.equals("reset")) { for (Settings.Setting setting : Baritone.settings().allSettings) { setting.reset(); From f7f003c0f982cf90cc1fee877a6a18f0b8c7399c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 13 Apr 2019 19:05:54 -0700 Subject: [PATCH 329/682] farm --- src/main/java/baritone/Baritone.java | 6 + .../movement/movements/MovementParkour.java | 4 +- .../java/baritone/process/FarmProcess.java | 121 ++++++++++++++++++ .../utils/ExampleBaritoneControl.java | 5 + 4 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 src/main/java/baritone/process/FarmProcess.java diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index f7a20b0f..33916d59 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 CustomGoalProcess customGoalProcess; private BuilderProcess builderProcess; private ExploreProcess exploreProcess; + private FarmProcess farmProcess; private PathingControlManager pathingControlManager; @@ -120,6 +121,7 @@ public class Baritone implements IBaritone { getToBlockProcess = new GetToBlockProcess(this); builderProcess = new BuilderProcess(this); exploreProcess = new ExploreProcess(this); + farmProcess = new FarmProcess(this); } this.worldProvider = new WorldProvider(); @@ -197,6 +199,10 @@ public class Baritone implements IBaritone { return this.mineProcess; } + public FarmProcess getFarmProcess() { + return this.farmProcess; + } + @Override public PathingBehavior getPathingBehavior() { return this.pathingBehavior; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index ce5f77e9..fbf57e6c 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -106,7 +106,9 @@ public class MovementParkour extends Movement { return; } } - if (MovementHelper.canWalkOn(context.bsi, x + xDiff * i, y - 1, z + zDiff * i)) { + IBlockState landingOn = context.bsi.get0(x + xDiff * i, y - 1, z + zDiff * i); + // farmland needs to be canwalkon otherwise farm can never work at all, but we want to specifically disallow ending a jumy on farmland haha + if (landingOn.getBlock() != Blocks.FARMLAND && MovementHelper.canWalkOn(context.bsi, x + xDiff * i, y - 1, z + zDiff * i, landingOn)) { res.x = x + xDiff * i; res.y = y; res.z = z + zDiff * i; diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java new file mode 100644 index 00000000..9d27f953 --- /dev/null +++ b/src/main/java/baritone/process/FarmProcess.java @@ -0,0 +1,121 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.process; + +import baritone.Baritone; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalBlock; +import baritone.api.pathing.goals.GoalComposite; +import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.api.utils.Rotation; +import baritone.api.utils.RotationUtils; +import baritone.api.utils.input.Input; +import baritone.cache.WorldScanner; +import baritone.utils.BaritoneProcessHelper; +import net.minecraft.block.BlockAir; +import net.minecraft.block.BlockCrops; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +public class FarmProcess extends BaritoneProcessHelper { + + private boolean active; + + public FarmProcess(Baritone baritone) { + super(baritone); + } + + @Override + public boolean isActive() { + return active; + } + + public void doit() { + active = true; + } + + @Override + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + List memes = WorldScanner.INSTANCE.scanChunkRadius(ctx, Arrays.asList(Blocks.FARMLAND, Blocks.WHEAT), 256, 10, 4); + + List toBreak = new ArrayList<>(); + List toRightClickOnTop = new ArrayList<>(); + for (BlockPos pos : memes) { + IBlockState state = ctx.world().getBlockState(pos); + if (state.getBlock() == Blocks.FARMLAND) { + if (ctx.world().getBlockState(pos.up()).getBlock() instanceof BlockAir) { + toRightClickOnTop.add(pos); + } + } else { + if (state.getValue(BlockCrops.AGE) == 7) { + toBreak.add(pos); + } + } + } + + baritone.getInputOverrideHandler().clearAllKeys(); + for (BlockPos pos : toBreak) { + Optional rot = RotationUtils.reachable(ctx, pos); + if (rot.isPresent()) { + baritone.getLookBehavior().updateTarget(rot.get(), true); + if (ctx.objectMouseOver() != null && ctx.objectMouseOver().typeOfHit == RayTraceResult.Type.BLOCK && ctx.objectMouseOver().getBlockPos().equals(pos)) { + baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); + } + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + } + for (BlockPos pos : toRightClickOnTop) { + Optional rot = RotationUtils.reachableOffset(ctx.player(), pos, new Vec3d(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance()); + if (rot.isPresent()) { + baritone.getLookBehavior().updateTarget(rot.get(), true); + if (ctx.objectMouseOver() != null && ctx.objectMouseOver().typeOfHit == RayTraceResult.Type.BLOCK && ctx.objectMouseOver().getBlockPos().equals(pos)) { + baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); + } + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + } + + List goalz = new ArrayList<>(); + for (BlockPos pos : toBreak) { + goalz.add(new GoalBlock(pos)); + } + for (BlockPos pos : toRightClickOnTop) { + goalz.add(new GoalBlock(pos.up())); + } + return new PathingCommand(new GoalComposite(goalz.toArray(new Goal[0])), PathingCommandType.SET_GOAL_AND_PATH); + } + + @Override + public void onLostControl() { + active = false; + } + + @Override + public String displayName0() { + return "Farming"; + } +} diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index f4261f07..4a819d74 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -382,6 +382,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("okay"); return true; } + if (msg.equals("farm")) { + baritone.getFarmProcess().doit(); + logDirect("farming"); + return true; + } if (msg.equals("echest")) { Optional> contents = baritone.getMemoryBehavior().echest(); if (contents.isPresent()) { From 3333797144f4e3150b6e93387c3236bb2c5aee3e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 14 Apr 2019 10:06:37 -0700 Subject: [PATCH 330/682] fix region pruning --- src/api/java/baritone/api/Settings.java | 6 ++++-- src/main/java/baritone/cache/CachedWorld.java | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index b61656a9..1de894dc 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -401,10 +401,12 @@ public final class Settings { * On save, delete from RAM any cached regions that are more than 1024 blocks away from the player *

* Temporarily disabled + *

+ * Temporarily reenabled * * @see Issue #248 */ - public final Setting pruneRegionsFromRAM = new Setting<>(false); + public final Setting pruneRegionsFromRAM = new Setting<>(true); /** * Remember the contents of containers (chests, echests, furnaces) @@ -575,7 +577,7 @@ public final class Settings { /** * How far to move before repeating the build. -1 for the size of the build in that axis. 0 to disable */ - public final Setting buildRepeatDistance=new Setting<>(0); + public final Setting buildRepeatDistance = new Setting<>(0); /** * What direction te repeat the build in diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index c025d489..949f818c 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -180,8 +180,8 @@ public final class CachedWorld implements ICachedWorld, Helper { if (region == null) { continue; } - int distX = (region.getX() << 9 + 256) - pruneCenter.getX(); - int distZ = (region.getZ() << 9 + 256) - pruneCenter.getZ(); + int distX = ((region.getX() << 9) + 256) - pruneCenter.getX(); + int distZ = ((region.getZ() << 9) + 256) - pruneCenter.getZ(); double dist = Math.sqrt(distX * distX + distZ * distZ); if (dist > 1024) { logDebug("Deleting cached region " + region.getX() + "," + region.getZ() + " from ram"); @@ -216,7 +216,7 @@ public final class CachedWorld implements ICachedWorld, Helper { if (mostRecentlyModified == null) { return new BlockPos(0, 0, 0); } - return new BlockPos(mostRecentlyModified.x << 4 + 8, 0, mostRecentlyModified.z << 4 + 8); + return new BlockPos((mostRecentlyModified.x << 4) + 8, 0, (mostRecentlyModified.z << 4) + 8); } private synchronized List allRegions() { From e0a618a791a63b4fe945446bec2edf4c2808ad7f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Apr 2019 17:12:20 -0700 Subject: [PATCH 331/682] epic farm --- src/api/java/baritone/api/Settings.java | 5 +- .../baritone/api/utils/IPlayerContext.java | 14 +- .../movement/movements/MovementFall.java | 4 +- .../baritone/pathing/path/PathExecutor.java | 5 +- .../java/baritone/process/BuilderProcess.java | 4 +- .../java/baritone/process/FarmProcess.java | 200 ++++++++++++++++-- 6 files changed, 201 insertions(+), 31 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index b61656a9..fbf0baef 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -142,7 +142,8 @@ public final class Settings { public final Setting> acceptableThrowawayItems = new Setting<>(new ArrayList<>(Arrays.asList( Item.getItemFromBlock(Blocks.DIRT), Item.getItemFromBlock(Blocks.COBBLESTONE), - Item.getItemFromBlock(Blocks.NETHERRACK) + Item.getItemFromBlock(Blocks.NETHERRACK), + Item.getItemFromBlock(Blocks.STONE) ))); /** @@ -575,7 +576,7 @@ public final class Settings { /** * How far to move before repeating the build. -1 for the size of the build in that axis. 0 to disable */ - public final Setting buildRepeatDistance=new Setting<>(0); + public final Setting buildRepeatDistance = new Setting<>(0); /** * What direction te repeat the build in diff --git a/src/api/java/baritone/api/utils/IPlayerContext.java b/src/api/java/baritone/api/utils/IPlayerContext.java index 83040ab5..9acb2ad9 100644 --- a/src/api/java/baritone/api/utils/IPlayerContext.java +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -71,20 +71,26 @@ public interface IPlayerContext { * @return The position of the highlighted block */ default Optional getSelectedBlock() { - if (objectMouseOver() != null && objectMouseOver().typeOfHit == RayTraceResult.Type.BLOCK) { - return Optional.of(objectMouseOver().getBlockPos()); + RayTraceResult result = objectMouseOver(); + if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { + return Optional.of(result.getBlockPos()); } return Optional.empty(); } + default boolean isLookingAt(BlockPos pos) { + return getSelectedBlock().equals(Optional.of(pos)); + } + /** * Returns the entity that the crosshair is currently placed over. Updated once per tick. * * @return The entity */ default Optional getSelectedEntity() { - if (objectMouseOver() != null && objectMouseOver().typeOfHit == RayTraceResult.Type.ENTITY) { - return Optional.of(objectMouseOver().entityHit); + RayTraceResult result = objectMouseOver(); + if (result != null && result.typeOfHit == RayTraceResult.Type.ENTITY) { + return Optional.of(result.entityHit); } return Optional.empty(); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 93f60f5d..0a4c38c7 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -39,7 +39,6 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3i; @@ -92,8 +91,7 @@ public class MovementFall extends Movement { targetRotation = new Rotation(toDest.getYaw(), 90.0F); - RayTraceResult trace = ctx.objectMouseOver(); - if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK && (trace.getBlockPos().equals(dest) || trace.getBlockPos().equals(dest.down()))) { + if (ctx.isLookingAt(dest) || ctx.isLookingAt(dest.down())) { state.setInput(Input.CLICK_RIGHT, true); } } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 6ddcda0f..3e767499 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -441,7 +441,10 @@ public class PathExecutor implements IPathExecutor, Helper { IMovement prev = path.movements().get(pathPosition - 1); if (prev instanceof MovementDescend && prev.getDirection().up().equals(current.getDirection().down())) { BlockPos center = current.getSrc().up(); - if (ctx.player().posY >= center.getY()) { // playerFeet adds 0.1251 to account for soul sand + // playerFeet adds 0.1251 to account for soul sand + // farmland is 0.9375 + // 0.07 is to account for farmland + if (ctx.player().posY >= center.getY() - 0.07) { behavior.baritone.getInputOverrideHandler().setInputForceState(Input.JUMP, false); return true; } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 4af6c800..982e22ce 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -362,7 +362,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro // and is unable since it's unsneaked in the intermediary tick baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true); } - if (Objects.equals(ctx.objectMouseOver().getBlockPos(), pos) || ctx.playerRotations().isReallyCloseTo(rot)) { + if (ctx.isLookingAt(pos) || ctx.playerRotations().isReallyCloseTo(rot)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); } return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); @@ -374,7 +374,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro baritone.getLookBehavior().updateTarget(rot, true); ctx.player().inventory.currentItem = toPlace.get().hotbarSelection; baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true); - if ((Objects.equals(ctx.objectMouseOver().getBlockPos(), toPlace.get().placeAgainst) && ctx.objectMouseOver().sideHit.equals(toPlace.get().side)) || ctx.playerRotations().isReallyCloseTo(rot)) { + if ((ctx.isLookingAt(toPlace.get().placeAgainst) && ctx.objectMouseOver().sideHit.equals(toPlace.get().side)) || ctx.playerRotations().isReallyCloseTo(rot)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); } return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index 9d27f953..0e2fdaae 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -27,24 +27,60 @@ import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; import baritone.cache.WorldScanner; +import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; -import net.minecraft.block.BlockAir; -import net.minecraft.block.BlockCrops; +import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.Entity; +import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.EnumDyeColor; +import net.minecraft.item.Item; +import net.minecraft.item.ItemDye; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; +import net.minecraft.world.World; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.function.Predicate; public class FarmProcess extends BaritoneProcessHelper { private boolean active; + private static final List FARMLAND_PLANTABLE = Arrays.asList( + Items.BEETROOT_SEEDS, + Items.MELON_SEEDS, + Items.WHEAT_SEEDS, + Items.PUMPKIN_SEEDS, + Items.POTATO, + Items.CARROT + ); + + private static final List PICKUP_DROPPED = Arrays.asList( + Items.BEETROOT_SEEDS, + Items.WHEAT, + Items.MELON_SEEDS, + Items.MELON, + Items.WHEAT_SEEDS, + Items.WHEAT, + Items.PUMPKIN_SEEDS, + Items.POTATO, + Items.CARROT, + Items.BEETROOT, + Item.getItemFromBlock(Blocks.PUMPKIN), + Item.getItemFromBlock(Blocks.MELON_BLOCK), + Items.NETHER_WART, + Items.REEDS, + Item.getItemFromBlock(Blocks.CACTUS) + ); + public FarmProcess(Baritone baritone) { super(baritone); } @@ -58,21 +94,115 @@ public class FarmProcess extends BaritoneProcessHelper { active = true; } + private enum Harvest { + WHEAT((BlockCrops) Blocks.WHEAT), + CARROTS((BlockCrops) Blocks.CARROTS), + POTATOES((BlockCrops) Blocks.POTATOES), + BEETROOT((BlockCrops) Blocks.BEETROOTS), + PUMPKIN(Blocks.PUMPKIN, state -> true), + MELON(Blocks.MELON_BLOCK, state -> true), + NETHERWART(Blocks.NETHER_WART, state -> state.getValue(BlockNetherWart.AGE) >= 3), + SUGARCANE(Blocks.REEDS, null) { + @Override + public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { + return world.getBlockState(pos.down()).getBlock() instanceof BlockReed; + } + }, + CACTUS(Blocks.CACTUS, null) { + @Override + public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { + return world.getBlockState(pos.down()).getBlock() instanceof BlockCactus; + } + }; + public final Block block; + public final Predicate readyToHarvest; + + Harvest(BlockCrops blockCrops) { + this(blockCrops, blockCrops::isMaxAge); + // max age is 7 for wheat, carrots, and potatoes, but 3 for beetroot + } + + Harvest(Block block, Predicate readyToHarvest) { + this.block = block; + this.readyToHarvest = readyToHarvest; + } + + public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { + return readyToHarvest.test(state); + } + } + + private boolean readyForHarvest(World world, BlockPos pos, IBlockState state) { + for (Harvest harvest : Harvest.values()) { + if (harvest.block == state.getBlock()) { + return harvest.readyToHarvest(world, pos, state); + } + } + return false; + } + + private boolean selectFarmlandPlantable(boolean doSelect) {//EnumDyeColor.WHITE == EnumDyeColor.byDyeDamage(stack.getMetadata()) + NonNullList invy = ctx.player().inventory.mainInventory; + for (int i = 0; i < 9; i++) { + if (FARMLAND_PLANTABLE.contains(invy.get(i).getItem())) { + if (doSelect) { + ctx.player().inventory.currentItem = i; + } + return true; + } + } + return false; + } + + private boolean selectBoneMeal(boolean doSelect) { + if (isBoneMeal(ctx.player().inventory.offHandInventory.get(0))) { + return true; + } + NonNullList invy = ctx.player().inventory.mainInventory; + for (int i = 0; i < 9; i++) { + if (isBoneMeal(invy.get(i))) { + if (doSelect) { + ctx.player().inventory.currentItem = i; + } + return true; + } + } + return false; + } + + private boolean isBoneMeal(ItemStack stack) { + return !stack.isEmpty() && stack.getItem() instanceof ItemDye && EnumDyeColor.byDyeDamage(stack.getMetadata()) == EnumDyeColor.WHITE; + } + @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { - List memes = WorldScanner.INSTANCE.scanChunkRadius(ctx, Arrays.asList(Blocks.FARMLAND, Blocks.WHEAT), 256, 10, 4); + ArrayList scan = new ArrayList<>(); + for (Harvest harvest : Harvest.values()) { + scan.add(harvest.block); + } + scan.add(Blocks.FARMLAND); + + List locations = WorldScanner.INSTANCE.scanChunkRadius(ctx, scan, 256, 10, 4); List toBreak = new ArrayList<>(); - List toRightClickOnTop = new ArrayList<>(); - for (BlockPos pos : memes) { + List openFarmland = new ArrayList<>(); + List bonemealable = new ArrayList<>(); + for (BlockPos pos : locations) { IBlockState state = ctx.world().getBlockState(pos); if (state.getBlock() == Blocks.FARMLAND) { if (ctx.world().getBlockState(pos.up()).getBlock() instanceof BlockAir) { - toRightClickOnTop.add(pos); + openFarmland.add(pos); } - } else { - if (state.getValue(BlockCrops.AGE) == 7) { - toBreak.add(pos); + continue; + } + if (readyForHarvest(ctx.world(), pos, state)) { + toBreak.add(pos); + continue; + } + if (state.getBlock() instanceof IGrowable) { + IGrowable ig = (IGrowable) state.getBlock(); + if (ig.canGrow(ctx.world(), pos, state, true) && ig.canUseBonemeal(ctx.world(), ctx.world().rand, pos, state)) { + bonemealable.add(pos); } } } @@ -80,31 +210,63 @@ public class FarmProcess extends BaritoneProcessHelper { baritone.getInputOverrideHandler().clearAllKeys(); for (BlockPos pos : toBreak) { Optional rot = RotationUtils.reachable(ctx, pos); - if (rot.isPresent()) { + if (rot.isPresent() && isSafeToCancel) { baritone.getLookBehavior().updateTarget(rot.get(), true); - if (ctx.objectMouseOver() != null && ctx.objectMouseOver().typeOfHit == RayTraceResult.Type.BLOCK && ctx.objectMouseOver().getBlockPos().equals(pos)) { + MovementHelper.switchToBestToolFor(ctx, ctx.world().getBlockState(pos)); + if (ctx.isLookingAt(pos)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); } return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } } - for (BlockPos pos : toRightClickOnTop) { - Optional rot = RotationUtils.reachableOffset(ctx.player(), pos, new Vec3d(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance()); - if (rot.isPresent()) { + for (BlockPos pos : openFarmland) { + Optional rot = RotationUtils.reachableOffset(ctx.player(), pos, new Vec3d(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance()); + if (rot.isPresent() && isSafeToCancel && selectFarmlandPlantable(true)) { baritone.getLookBehavior().updateTarget(rot.get(), true); - if (ctx.objectMouseOver() != null && ctx.objectMouseOver().typeOfHit == RayTraceResult.Type.BLOCK && ctx.objectMouseOver().getBlockPos().equals(pos)) { + 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 && selectBoneMeal(true)) { + baritone.getLookBehavior().updateTarget(rot.get(), true); + if (ctx.isLookingAt(pos)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); } return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } } + if (calcFailed) { + logDirect("Farm failed"); + onLostControl(); + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + List goalz = new ArrayList<>(); for (BlockPos pos : toBreak) { - goalz.add(new GoalBlock(pos)); + goalz.add(new BuilderProcess.GoalBreak(pos)); } - for (BlockPos pos : toRightClickOnTop) { - goalz.add(new GoalBlock(pos.up())); + if (selectFarmlandPlantable(false)) { + for (BlockPos pos : openFarmland) { + goalz.add(new GoalBlock(pos.up())); + } + } + if (selectBoneMeal(false)) { + for (BlockPos pos : bonemealable) { + goalz.add(new GoalBlock(pos)); + } + } + for (Entity entity : ctx.world().loadedEntityList) { + if (entity instanceof EntityItem && entity.onGround) { + EntityItem ei = (EntityItem) entity; + if (PICKUP_DROPPED.contains(ei.getItem().getItem())) { + goalz.add(new GoalBlock(new BlockPos(entity.posX, entity.posY + 0.1, entity.posZ))); + } + } } return new PathingCommand(new GoalComposite(goalz.toArray(new Goal[0])), PathingCommandType.SET_GOAL_AND_PATH); } From 96414b37f3994c245f9548a8e7b217cb2db8c7d3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Apr 2019 18:14:20 -0700 Subject: [PATCH 332/682] whoops this was fixed monthhs ago --- USAGE.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/USAGE.md b/USAGE.md index 22460378..085f49c2 100644 --- a/USAGE.md +++ b/USAGE.md @@ -63,9 +63,6 @@ There are about a hundred settings, but here are some fun / interesting / import # Troubleshooting / common issues -## Baritone highlights a block in green but gets completely stuck? Also I'm using Baritone with Future? -Baritone is trying to right click to place a block there, but it can't since there's a conflicting mixin. Baritone can't force click right click when Future is also installed. Left click **does work** on recent Baritone even with Future, however. For now, turn off `allowPlace` and Baritone will only search for paths that don't require placing blocks to complete. `allowBreak` can remain on. - ## Why doesn't Baritone respond to any of my chat commands? This could be one of many things. From f49df63183423ae5ba8e707fc3623e851f6df79d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Apr 2019 10:20:23 -0700 Subject: [PATCH 333/682] that can never be null --- src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index a7d104cf..588b773e 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -186,7 +186,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder, Helper { } protected Optional bestSoFar(boolean logInfo, int numNodes) { - if (startNode == null || bestSoFar == null) { + if (startNode == null) { return Optional.empty(); } double bestDist = 0; From a1a9b4e6b915d0143b7a11984f846c5becf293d4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Apr 2019 10:25:32 -0700 Subject: [PATCH 334/682] allow spaces --- src/api/java/baritone/api/utils/SettingsUtil.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index ae97ad7b..60014bbd 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -147,12 +147,11 @@ public class SettingsUtil { FLOAT(Float.class, Float::parseFloat), LONG(Long.class, Long::parseLong), - ITEM_LIST(ArrayList.class, str -> Stream.of(str.split(",")).map(Item::getByNameOrId).collect(Collectors.toCollection(ArrayList::new)), list -> ((ArrayList) list).stream().map(Item.REGISTRY::getNameForObject).map(ResourceLocation::toString).collect(Collectors.joining(","))), + ITEM_LIST(ArrayList.class, str -> Stream.of(str.split(",")).map(String::trim).map(Item::getByNameOrId).collect(Collectors.toCollection(ArrayList::new)), list -> ((ArrayList) list).stream().map(Item.REGISTRY::getNameForObject).map(ResourceLocation::toString).collect(Collectors.joining(","))), COLOR(Color.class, str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])), color -> color.getRed() + "," + color.getGreen() + "," + color.getBlue()), ENUMFACING(EnumFacing.class, EnumFacing::byName); - Class klass; Function parser; Function toString; From c136182e176056feb8fbb0d82badfbfcd01cb6da Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Apr 2019 18:04:43 -0700 Subject: [PATCH 335/682] add option to manually blacklist closest --- .../java/baritone/process/GetToBlockProcess.java | 3 ++- .../baritone/utils/ExampleBaritoneControl.java | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 2dbefd50..0116df83 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -117,7 +117,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } // blacklist the closest block and its adjacent blocks - public synchronized void blacklistClosest() { + public synchronized boolean blacklistClosest() { List newBlacklist = new ArrayList<>(); knownLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(newBlacklist::add); outer: @@ -140,6 +140,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } logDebug("Blacklisting unreachable locations " + newBlacklist); blacklist.addAll(newBlacklist); + return !newBlacklist.isEmpty(); } // safer than direct double comparison from distanceSq diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 4a819d74..0f80ea54 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -35,6 +35,7 @@ import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; +import baritone.process.GetToBlockProcess; import baritone.utils.pathing.SegmentedCalculator; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; @@ -466,6 +467,19 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Exploring from " + centerX + "," + centerZ); return true; } + if (msg.equals("blacklist")) { + GetToBlockProcess proc = baritone.getGetToBlockProcess(); + if (!proc.isActive()) { + logDirect("GetToBlockProcess is not currently active"); + return true; + } + if (proc.blacklistClosest()) { + logDirect("Blacklisted closest instances"); + } else { + logDirect("No known locations, unable to blacklist"); + } + return true; + } if (msg.startsWith("find")) { String blockType = msg.substring(4).trim(); ArrayList locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4); From 44d757347bb8e4d3aa5905173c04df082bd16863 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Apr 2019 22:43:33 -0700 Subject: [PATCH 336/682] fix unable to move while paused --- src/main/java/baritone/process/BuilderProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 982e22ce..286f8cf8 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -296,7 +296,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } baritone.getInputOverrideHandler().clearAllKeys(); if (paused) { - return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); } if (Baritone.settings().buildInLayers.value) { if (realSchematic == null) { From fe51220e3c9fd9431e0f2f121bb5b434b89d5024 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 16 Apr 2019 23:19:55 -0700 Subject: [PATCH 337/682] this might help --- src/main/java/baritone/process/BuilderProcess.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 286f8cf8..2550f84d 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -365,7 +365,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro if (ctx.isLookingAt(pos) || ctx.playerRotations().isReallyCloseTo(rot)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); } - return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); } List desirableOnHotbar = new ArrayList<>(); Optional toPlace = searchForPlacables(bcc, desirableOnHotbar); @@ -377,7 +377,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro if ((ctx.isLookingAt(toPlace.get().placeAgainst) && ctx.objectMouseOver().sideHit.equals(toPlace.get().side)) || ctx.playerRotations().isReallyCloseTo(rot)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); } - return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); } List approxPlacable = placable(36); From c013d1e0d91206c4560956b50fcd0c7f77f37a83 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 17 Apr 2019 18:10:47 -0700 Subject: [PATCH 338/682] fix various toxic clouds --- src/api/java/baritone/api/IBaritone.java | 14 ++ .../api/behavior/IPathingBehavior.java | 7 + .../java/baritone/api/cache/ICachedWorld.java | 2 + .../java/baritone/api}/cache/Waypoint.java | 5 +- .../baritone/api/process/IBuilderProcess.java | 13 ++ .../baritone/api/process/IExploreProcess.java | 22 +++ .../baritone/api/process/IFarmProcess.java | 22 +++ .../api/process/IGetToBlockProcess.java | 2 + .../java/baritone/api/utils/BlockUtils.java | 63 ++++++++ .../api}/utils/ExampleBaritoneControl.java | 137 ++++++++---------- .../java/baritone/api}/utils/Helper.java | 8 +- src/main/java/baritone/Baritone.java | 21 +-- .../baritone/behavior/MemoryBehavior.java | 2 +- .../baritone/behavior/PathingBehavior.java | 9 +- src/main/java/baritone/cache/CachedChunk.java | 3 +- .../java/baritone/cache/CachedRegion.java | 7 +- src/main/java/baritone/cache/CachedWorld.java | 2 +- src/main/java/baritone/cache/ChunkPacker.java | 25 +--- .../baritone/cache/WaypointCollection.java | 1 + .../java/baritone/cache/WorldProvider.java | 2 +- .../java/baritone/event/GameEventHandler.java | 2 +- .../pathing/calc/AbstractNodeCostSearch.java | 2 +- src/main/java/baritone/pathing/calc/Path.java | 2 +- .../pathing/movement/MovementHelper.java | 2 +- .../baritone/pathing/path/PathExecutor.java | 2 +- .../java/baritone/process/BuilderProcess.java | 6 - .../java/baritone/process/ExploreProcess.java | 4 +- .../java/baritone/process/FarmProcess.java | 6 +- .../java/baritone/process/MineProcess.java | 5 +- .../java/baritone/utils/BaritoneAutoTest.java | 1 + .../baritone/utils/BaritoneProcessHelper.java | 1 + .../java/baritone/utils/BlockBreakHelper.java | 1 + .../java/baritone/utils/BlockPlaceHelper.java | 1 + .../java/baritone/utils/PathRenderer.java | 1 + .../utils/player/PrimaryPlayerContext.java | 2 +- .../utils/player/PrimaryPlayerController.java | 2 +- 36 files changed, 262 insertions(+), 145 deletions(-) rename src/{main/java/baritone => api/java/baritone/api}/cache/Waypoint.java (94%) create mode 100644 src/api/java/baritone/api/process/IExploreProcess.java create mode 100644 src/api/java/baritone/api/process/IFarmProcess.java create mode 100644 src/api/java/baritone/api/utils/BlockUtils.java rename src/{main/java/baritone => api/java/baritone/api}/utils/ExampleBaritoneControl.java (85%) rename src/{main/java/baritone => api/java/baritone/api}/utils/Helper.java (93%) diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index a12b206d..a356922c 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -71,6 +71,18 @@ public interface IBaritone { */ IBuilderProcess getBuilderProcess(); + /** + * @return The {@link IExploreProcess} instance + * @see IExploreProcess + */ + IExploreProcess getExploreProcess(); + + /** + * @return The {@link IFarmProcess} instance + * @see IFarmProcess + */ + IFarmProcess getFarmProcess(); + /** * @return The {@link ICustomGoalProcess} instance * @see ICustomGoalProcess @@ -115,4 +127,6 @@ public interface IBaritone { * @see IEventBus */ IEventBus getGameEventHandler(); + + void openClick(); } diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index 64be71d5..15777448 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -80,6 +80,13 @@ public interface IPathingBehavior extends IBehavior { */ boolean cancelEverything(); + /** + * PLEASE never call this + *

+ * If cancelEverything was like "kill" this is "sudo kill -9". Or shutting off your computer. + */ + void forceCancel(); + /** * Returns the current path, from the current path executor, if there is one. * diff --git a/src/api/java/baritone/api/cache/ICachedWorld.java b/src/api/java/baritone/api/cache/ICachedWorld.java index e681ce51..837ae076 100644 --- a/src/api/java/baritone/api/cache/ICachedWorld.java +++ b/src/api/java/baritone/api/cache/ICachedWorld.java @@ -81,4 +81,6 @@ public interface ICachedWorld { * in a new thread by default. */ void save(); + + } diff --git a/src/main/java/baritone/cache/Waypoint.java b/src/api/java/baritone/api/cache/Waypoint.java similarity index 94% rename from src/main/java/baritone/cache/Waypoint.java rename to src/api/java/baritone/api/cache/Waypoint.java index 19e574f9..2b9a7232 100644 --- a/src/main/java/baritone/cache/Waypoint.java +++ b/src/api/java/baritone/api/cache/Waypoint.java @@ -15,9 +15,8 @@ * along with Baritone. If not, see . */ -package baritone.cache; +package baritone.api.cache; -import baritone.api.cache.IWaypoint; import net.minecraft.util.math.BlockPos; import java.util.Date; @@ -47,7 +46,7 @@ public class Waypoint implements IWaypoint { * @param location The waypoint location * @param creationTimestamp When the waypoint was created */ - Waypoint(String name, Tag tag, BlockPos location, long creationTimestamp) { + public Waypoint(String name, Tag tag, BlockPos location, long creationTimestamp) { this.name = name; this.tag = tag; this.location = location; diff --git a/src/api/java/baritone/api/process/IBuilderProcess.java b/src/api/java/baritone/api/process/IBuilderProcess.java index 694c8752..d9397786 100644 --- a/src/api/java/baritone/api/process/IBuilderProcess.java +++ b/src/api/java/baritone/api/process/IBuilderProcess.java @@ -18,6 +18,8 @@ package baritone.api.process; import baritone.api.utils.ISchematic; +import net.minecraft.client.Minecraft; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import java.io.File; @@ -46,4 +48,15 @@ public interface IBuilderProcess extends IBaritoneProcess { * @return Whether or not the schematic was able to load from file */ boolean build(String name, File schematic, Vec3i origin); + + default boolean build(String schematicFile, BlockPos origin) { + File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); + return build(schematicFile, file, origin); + } + + void pause(); + + void resume(); + + void clearArea(BlockPos corner1, BlockPos corner2); } diff --git a/src/api/java/baritone/api/process/IExploreProcess.java b/src/api/java/baritone/api/process/IExploreProcess.java new file mode 100644 index 00000000..bf30fa22 --- /dev/null +++ b/src/api/java/baritone/api/process/IExploreProcess.java @@ -0,0 +1,22 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.process; + +public interface IExploreProcess extends IBaritoneProcess { + void explore(int centerX, int centerZ); +} diff --git a/src/api/java/baritone/api/process/IFarmProcess.java b/src/api/java/baritone/api/process/IFarmProcess.java new file mode 100644 index 00000000..c9234a24 --- /dev/null +++ b/src/api/java/baritone/api/process/IFarmProcess.java @@ -0,0 +1,22 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.process; + +public interface IFarmProcess extends IBaritoneProcess { + void farm(); +} diff --git a/src/api/java/baritone/api/process/IGetToBlockProcess.java b/src/api/java/baritone/api/process/IGetToBlockProcess.java index ff3dc9b5..a5a35577 100644 --- a/src/api/java/baritone/api/process/IGetToBlockProcess.java +++ b/src/api/java/baritone/api/process/IGetToBlockProcess.java @@ -25,4 +25,6 @@ import net.minecraft.block.Block; public interface IGetToBlockProcess extends IBaritoneProcess { void getToBlock(Block block); + + boolean blacklistClosest(); } diff --git a/src/api/java/baritone/api/utils/BlockUtils.java b/src/api/java/baritone/api/utils/BlockUtils.java new file mode 100644 index 00000000..a7e00608 --- /dev/null +++ b/src/api/java/baritone/api/utils/BlockUtils.java @@ -0,0 +1,63 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils; + +import net.minecraft.block.Block; +import net.minecraft.util.ResourceLocation; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +public class BlockUtils { + private static transient Map resourceCache = new HashMap<>(); + + public static String blockToString(Block block) { + ResourceLocation loc = Block.REGISTRY.getNameForObject(block); + String name = loc.getPath(); // normally, only write the part after the minecraft: + if (!loc.getNamespace().equals("minecraft")) { + // Baritone is running on top of forge with mods installed, perhaps? + name = loc.toString(); // include the namespace with the colon + } + return name; + } + + public static Block stringToBlockRequired(String name) { + Block block = stringToBlockNullable(name); + Objects.requireNonNull(block); + return block; + } + + public static Block stringToBlockNullable(String name) { + // do NOT just replace this with a computeWithAbsent, it isn't thread safe + Block block = resourceCache.get(name); // map is never mutated in place so this is safe + if (block != null) { + return block; + } + if (resourceCache.containsKey(name)) { + return null; // cached as null + } + block = Block.getBlockFromName(name.contains(":") ? name : "minecraft:" + name); + Map copy = new HashMap<>(resourceCache); // read only copy is safe, wont throw concurrentmodification + copy.put(name, block); + resourceCache = copy; + return block; + } + + private BlockUtils() {} +} diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java similarity index 85% rename from src/main/java/baritone/utils/ExampleBaritoneControl.java rename to src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 0f80ea54..f758d15e 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -15,28 +15,21 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.api.utils; -import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; import baritone.api.Settings; +import baritone.api.behavior.IPathingBehavior; import baritone.api.cache.IRememberedInventory; import baritone.api.cache.IWaypoint; +import baritone.api.cache.Waypoint; import baritone.api.event.events.ChatEvent; +import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.pathing.goals.*; -import baritone.api.pathing.movement.ActionCosts; import baritone.api.process.IBaritoneProcess; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.SettingsUtil; -import baritone.behavior.Behavior; -import baritone.behavior.PathingBehavior; -import baritone.cache.ChunkPacker; -import baritone.cache.Waypoint; -import baritone.pathing.movement.CalculationContext; -import baritone.pathing.movement.Movement; -import baritone.pathing.movement.Moves; -import baritone.process.CustomGoalProcess; -import baritone.process.GetToBlockProcess; -import baritone.utils.pathing.SegmentedCalculator; +import baritone.api.process.ICustomGoalProcess; +import baritone.api.process.IGetToBlockProcess; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ChunkProviderClient; @@ -47,10 +40,8 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.Chunk; import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; -public class ExampleBaritoneControl extends Behavior implements Helper { +public class ExampleBaritoneControl implements Helper, AbstractGameEventListener { private static final String HELP_MSG = "baritone - Output settings into chat\n" + @@ -84,21 +75,26 @@ public class ExampleBaritoneControl extends Behavior implements Helper { private static final String COMMAND_PREFIX = "#"; - public ExampleBaritoneControl(Baritone baritone) { - super(baritone); + public final IBaritone baritone; + public final IPlayerContext ctx; + + public ExampleBaritoneControl(IBaritone baritone) { + this.baritone = baritone; + this.ctx = baritone.getPlayerContext(); + baritone.getGameEventHandler().registerEventListener(this); } @Override public void onSendChatMessage(ChatEvent event) { String msg = event.getMessage(); - if (Baritone.settings().prefixControl.value && msg.startsWith(COMMAND_PREFIX)) { + if (BaritoneAPI.getSettings().prefixControl.value && msg.startsWith(COMMAND_PREFIX)) { if (!runCommand(msg.substring(COMMAND_PREFIX.length()))) { logDirect("Invalid command"); } event.cancel(); // always cancel if using prefixControl return; } - if (!Baritone.settings().chatControl.value && !Baritone.settings().removePrefix.value) { + if (!BaritoneAPI.getSettings().chatControl.value && !BaritoneAPI.getSettings().removePrefix.value) { return; } if (runCommand(msg)) { @@ -108,20 +104,20 @@ public class ExampleBaritoneControl extends Behavior implements Helper { public boolean runCommand(String msg0) { // you may think this can be private, but impcat calls it from .b =) String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL - PathingBehavior pathingBehavior = baritone.getPathingBehavior(); - CustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); - List> toggleable = Baritone.settings().getAllValuesByType(Boolean.class); + IPathingBehavior pathingBehavior = baritone.getPathingBehavior(); + ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); + List> toggleable = BaritoneAPI.getSettings().getAllValuesByType(Boolean.class); for (Settings.Setting setting : toggleable) { if (msg.equalsIgnoreCase(setting.getName())) { setting.value ^= true; logDirect("Toggled " + setting.getName() + " to " + setting.value); - SettingsUtil.save(Baritone.settings()); + SettingsUtil.save(BaritoneAPI.getSettings()); return true; } } if (msg.equals("baritone") || msg.equals("modifiedsettings") || msg.startsWith("settings m") || msg.equals("modified")) { logDirect("All settings that have been modified from their default values:"); - for (Settings.Setting setting : SettingsUtil.modifiedSettings(Baritone.settings())) { + for (Settings.Setting setting : SettingsUtil.modifiedSettings(BaritoneAPI.getSettings())) { logDirect(setting.toString()); } return true; @@ -131,15 +127,15 @@ public class ExampleBaritoneControl extends Behavior implements Helper { try { int page = Integer.parseInt(rest.trim()); int min = page * 10; - int max = Math.min(Baritone.settings().allSettings.size(), (page + 1) * 10); + int max = Math.min(BaritoneAPI.getSettings().allSettings.size(), (page + 1) * 10); logDirect("Settings " + min + " to " + (max - 1) + ":"); for (int i = min; i < max; i++) { - logDirect(Baritone.settings().allSettings.get(i).toString()); + logDirect(BaritoneAPI.getSettings().allSettings.get(i).toString()); } } catch (Exception ex) { // NumberFormatException | ArrayIndexOutOfBoundsException and probably some others I'm forgetting lol ex.printStackTrace(); logDirect("All settings:"); - for (Settings.Setting setting : Baritone.settings().allSettings) { + for (Settings.Setting setting : BaritoneAPI.getSettings().allSettings) { logDirect(setting.toString()); } logDirect("To get one page of ten settings at a time, do settings "); @@ -155,26 +151,26 @@ public class ExampleBaritoneControl extends Behavior implements Helper { if (msg.contains(" ")) { String settingName = msg.substring(0, msg.indexOf(' ')); String settingValue = msg.substring(msg.indexOf(' ') + 1); - Settings.Setting setting = Baritone.settings().byLowerName.get(settingName); + Settings.Setting setting = BaritoneAPI.getSettings().byLowerName.get(settingName); if (setting != null) { if (settingValue.equals("reset")) { logDirect("Resetting setting " + settingName + " to default value."); setting.reset(); } else { try { - SettingsUtil.parseAndApply(Baritone.settings(), settingName, settingValue); + SettingsUtil.parseAndApply(BaritoneAPI.getSettings(), settingName, settingValue); } catch (Exception ex) { logDirect("Unable to parse setting"); return true; } } - SettingsUtil.save(Baritone.settings()); + SettingsUtil.save(BaritoneAPI.getSettings()); logDirect(setting.toString()); return true; } } - if (Baritone.settings().byLowerName.containsKey(msg)) { - Settings.Setting setting = Baritone.settings().byLowerName.get(msg); + if (BaritoneAPI.getSettings().byLowerName.containsKey(msg)) { + Settings.Setting setting = BaritoneAPI.getSettings().byLowerName.get(msg); logDirect(setting.toString()); return true; } @@ -210,7 +206,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } return true; } - if (msg.equals("fullpath")) { + /*if (msg.equals("fullpath")) { if (pathingBehavior.getGoal() == null) { logDirect("No goal."); } else { @@ -226,7 +222,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { }); } return true; - } + }*/ if (msg.equals("proc")) { Optional proc = baritone.getPathingControlManager().mostRecentInControl(); if (!proc.isPresent()) { @@ -284,7 +280,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("come")) { - customGoalProcess.setGoalAndPath(new GoalBlock(new BlockPos(mc.getRenderViewEntity()))); + customGoalProcess.setGoalAndPath(new GoalBlock(new BlockPos(Helper.mc.getRenderViewEntity()))); logDirect("Coming"); return true; } @@ -365,10 +361,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("reset")) { - for (Settings.Setting setting : Baritone.settings().allSettings) { + for (Settings.Setting setting : BaritoneAPI.getSettings().allSettings) { setting.reset(); } - SettingsUtil.save(Baritone.settings()); + SettingsUtil.save(BaritoneAPI.getSettings()); logDirect("Baritone settings reset"); return true; } @@ -384,11 +380,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("farm")) { - baritone.getFarmProcess().doit(); + baritone.getFarmProcess().farm(); logDirect("farming"); return true; } - if (msg.equals("echest")) { + // this literally doesn't work, memory is disabled lol + /*if (msg.equals("echest")) { Optional> contents = baritone.getMemoryBehavior().echest(); if (contents.isPresent()) { logDirect("echest contents:"); @@ -397,18 +394,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("echest contents unknown"); } return true; - } + }*/ if (msg.equals("chests")) { - System.out.println(baritone.getWorldProvider()); - System.out.println(baritone.getWorldProvider().getCurrentWorld()); - - System.out.println(baritone.getWorldProvider().getCurrentWorld().getContainerMemory()); - - System.out.println(baritone.getWorldProvider().getCurrentWorld().getContainerMemory().getRememberedInventories()); - - System.out.println(baritone.getWorldProvider().getCurrentWorld().getContainerMemory().getRememberedInventories().entrySet()); - - System.out.println(baritone.getWorldProvider().getCurrentWorld().getContainerMemory().getRememberedInventories().entrySet()); for (Map.Entry entry : baritone.getWorldProvider().getCurrentWorld().getContainerMemory().getRememberedInventories().entrySet()) { logDirect(entry.getKey() + ""); log(entry.getValue().getContents()); @@ -468,7 +455,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("blacklist")) { - GetToBlockProcess proc = baritone.getGetToBlockProcess(); + IGetToBlockProcess proc = baritone.getGetToBlockProcess(); if (!proc.isActive()) { logDirect("GetToBlockProcess is not currently active"); return true; @@ -485,9 +472,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper { ArrayList locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4); logDirect("Have " + locs.size() + " locations"); for (BlockPos pos : locs) { - Block actually = BlockStateInterface.get(ctx, pos).getBlock(); - if (!ChunkPacker.blockToString(actually).equalsIgnoreCase(blockType)) { - System.out.println("Was looking for " + blockType + " but actually found " + actually + " " + ChunkPacker.blockToString(actually)); + Block actually = ctx.world().getBlockState(pos).getBlock(); + if (!BlockUtils.blockToString(actually).equalsIgnoreCase(blockType)) { + logDebug("Was looking for " + blockType + " but actually found " + actually + " " + BlockUtils.blockToString(actually)); } } return true; @@ -496,13 +483,13 @@ public class ExampleBaritoneControl extends Behavior implements Helper { String[] blockTypes = msg.substring(4).trim().split(" "); try { int quantity = Integer.parseInt(blockTypes[1]); - Block block = ChunkPacker.stringToBlockRequired(blockTypes[0]); + Block block = BlockUtils.stringToBlockRequired(blockTypes[0]); baritone.getMineProcess().mine(quantity, block); logDirect("Will mine " + quantity + " " + blockTypes[0]); return true; } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {} for (String s : blockTypes) { - if (ChunkPacker.stringToBlockNullable(s) == null) { + if (BlockUtils.stringToBlockNullable(s) == null) { logDirect(s + " isn't a valid block name"); return true; } @@ -513,12 +500,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("click")) { - new Thread(() -> { - try { - Thread.sleep(100); - mc.addScheduledTask(() -> mc.displayGuiScreen(new GuiClick())); - } catch (Exception ignored) {} - }).start(); + baritone.openClick(); logDirect("aight dude"); return true; } @@ -538,9 +520,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper { // for example, "show deaths" waypointType = waypointType.substring(0, waypointType.length() - 1); } - Waypoint.Tag tag = Waypoint.Tag.fromString(waypointType); + IWaypoint.Tag tag = IWaypoint.Tag.fromString(waypointType); if (tag == null) { - logDirect("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase()); + logDirect("Not a valid tag. Tags are: " + Arrays.asList(IWaypoint.Tag.values()).toString().toLowerCase()); return true; } Set waypoints = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getByTag(tag); @@ -571,21 +553,21 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } name = parts[0]; } - baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, Waypoint.Tag.USER, pos)); + baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, IWaypoint.Tag.USER, pos)); logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto " + name + "' to set goal, say 'list user' to list custom waypoints."); return true; } if (msg.startsWith("goto")) { String waypointType = msg.substring(4).trim(); - if (waypointType.endsWith("s") && Waypoint.Tag.fromString(waypointType.substring(0, waypointType.length() - 1)) != null) { + if (waypointType.endsWith("s") && IWaypoint.Tag.fromString(waypointType.substring(0, waypointType.length() - 1)) != null) { // for example, "show deaths" waypointType = waypointType.substring(0, waypointType.length() - 1); } - Waypoint.Tag tag = Waypoint.Tag.fromString(waypointType); + IWaypoint.Tag tag = IWaypoint.Tag.fromString(waypointType); IWaypoint waypoint; if (tag == null) { String mining = waypointType; - Block block = ChunkPacker.stringToBlockNullable(mining); + Block block = BlockUtils.stringToBlockNullable(mining); //logDirect("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase()); if (block == null) { waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null); @@ -608,12 +590,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } - Goal goal = waypoint.getTag() == Waypoint.Tag.BED ? new GoalGetToBlock(waypoint.getLocation()) : new GoalBlock(waypoint.getLocation()); + Goal goal = waypoint.getTag() == IWaypoint.Tag.BED ? new GoalGetToBlock(waypoint.getLocation()) : new GoalBlock(waypoint.getLocation()); customGoalProcess.setGoalAndPath(goal); return true; } if (msg.equals("spawn") || msg.equals("bed")) { - IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(Waypoint.Tag.BED); + IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(IWaypoint.Tag.BED); if (waypoint == null) { BlockPos spawnPoint = ctx.player().getBedLocation(); // for some reason the default spawnpoint is underground sometimes @@ -628,12 +610,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("sethome")) { - baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", Waypoint.Tag.HOME, ctx.playerFeet())); + baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", IWaypoint.Tag.HOME, ctx.playerFeet())); logDirect("Saved. Say home to set goal."); return true; } if (msg.equals("home")) { - IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(Waypoint.Tag.HOME); + IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(IWaypoint.Tag.HOME); if (waypoint == null) { logDirect("home not saved"); } else { @@ -643,7 +625,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } return true; } - if (msg.equals("costs")) { + // this is completely impossible from api + /*if (msg.equals("costs")) { List moves = Stream.of(Moves.values()).map(x -> x.apply0(new CalculationContext(baritone), ctx.playerFeet())).collect(Collectors.toCollection(ArrayList::new)); while (moves.contains(null)) { moves.remove(null); @@ -659,7 +642,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect(parts[parts.length - 1] + " " + move.getDest().getX() + "," + move.getDest().getY() + "," + move.getDest().getZ() + " " + strCost); } return true; - } + }*/ if (msg.equals("damn")) { logDirect("daniel"); } diff --git a/src/main/java/baritone/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java similarity index 93% rename from src/main/java/baritone/utils/Helper.java rename to src/api/java/baritone/api/utils/Helper.java index 7bcc605c..99683d8a 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -15,9 +15,9 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.api.utils; -import baritone.Baritone; +import baritone.api.BaritoneAPI; import net.minecraft.client.Minecraft; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; @@ -50,7 +50,7 @@ public interface Helper { * @param message The message to display in chat */ default void logDebug(String message) { - if (!Baritone.settings().chatDebug.value) { + if (!BaritoneAPI.getSettings().chatDebug.value) { //System.out.println("Suppressed debug message:"); //System.out.println(message); return; @@ -67,6 +67,6 @@ public interface Helper { ITextComponent component = MESSAGE_PREFIX.createCopy(); component.getStyle().setColor(TextFormatting.GRAY); component.appendSibling(new TextComponentString(" " + message)); - Minecraft.getMinecraft().addScheduledTask(() -> Baritone.settings().logger.value.accept(component)); + Minecraft.getMinecraft().addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component)); } } diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 33916d59..65937c46 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -21,6 +21,8 @@ import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.event.listener.IEventBus; +import baritone.api.utils.ExampleBaritoneControl; +import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.behavior.*; import baritone.cache.WorldProvider; @@ -33,8 +35,6 @@ import net.minecraft.client.Minecraft; import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; @@ -67,7 +67,6 @@ public class Baritone implements IBaritone { private GameEventHandler gameEventHandler; - private List behaviors; private PathingBehavior pathingBehavior; private LookBehavior lookBehavior; private MemoryBehavior memoryBehavior; @@ -102,7 +101,6 @@ public class Baritone implements IBaritone { // Define this before behaviors try and get it, or else it will be null and the builds will fail! this.playerContext = PrimaryPlayerContext.INSTANCE; - this.behaviors = new ArrayList<>(); { // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist pathingBehavior = new PathingBehavior(this); @@ -138,12 +136,7 @@ public class Baritone implements IBaritone { return this.pathingControlManager; } - public List getBehaviors() { - return this.behaviors; - } - public void registerBehavior(Behavior behavior) { - this.behaviors.add(behavior); this.gameEventHandler.registerEventListener(behavior); } @@ -218,6 +211,16 @@ public class Baritone implements IBaritone { return this.gameEventHandler; } + @Override + public void openClick() { + new Thread(() -> { + try { + Thread.sleep(100); + Helper.mc.addScheduledTask(() -> Helper.mc.displayGuiScreen(new GuiClick())); + } catch (Exception ignored) {} + }).start(); + } + public static Settings settings() { return BaritoneAPI.getSettings(); } diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 50beda0f..72d648d9 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -24,7 +24,7 @@ import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.TickEvent; import baritone.api.event.events.type.EventState; import baritone.cache.ContainerMemory; -import baritone.cache.Waypoint; +import baritone.api.cache.Waypoint; import baritone.utils.BlockStateInterface; import net.minecraft.block.Block; import net.minecraft.block.BlockBed; diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 00ac5a4c..ac826fbf 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -32,7 +32,7 @@ import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.pathing.path.PathExecutor; -import baritone.utils.Helper; +import baritone.api.utils.Helper; import baritone.utils.PathRenderer; import baritone.utils.PathingCommandContext; import baritone.utils.pathing.Favoring; @@ -350,7 +350,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } } - public void forceCancel() { // NOT exposed on public api + @Override + public void forceCancel() { // exposed on public api because :sob: cancelEverything(); secretInternalSegmentCancel(); synchronized (pathCalcLock) { @@ -358,11 +359,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } } - public void secretCursedFunctionDoNotCall(IPath path) { + /*public void secretCursedFunctionDoNotCall(IPath path) { synchronized (pathPlanLock) { current = new PathExecutor(this, path); } - } + }*/ public CalculationContext secretInternalGetCalculationContext() { return context; diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index bc5e2ac9..631b7150 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -17,6 +17,7 @@ package baritone.cache; +import baritone.api.utils.BlockUtils; import baritone.utils.pathing.PathingBlockType; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.block.Block; @@ -177,7 +178,7 @@ public final class CachedChunk { if (special != null) { String str = special.get(index); if (str != null) { - return ChunkPacker.stringToBlockRequired(str).getDefaultState(); + return BlockUtils.stringToBlockRequired(str).getDefaultState(); } } diff --git a/src/main/java/baritone/cache/CachedRegion.java b/src/main/java/baritone/cache/CachedRegion.java index d395f168..630dcc9e 100644 --- a/src/main/java/baritone/cache/CachedRegion.java +++ b/src/main/java/baritone/cache/CachedRegion.java @@ -19,6 +19,7 @@ package baritone.cache; import baritone.Baritone; import baritone.api.cache.ICachedRegion; +import baritone.api.utils.BlockUtils; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; @@ -149,7 +150,7 @@ public final class CachedRegion implements ICachedRegion { for (int z = 0; z < 32; z++) { if (chunks[x][z] != null) { for (int i = 0; i < 256; i++) { - out.writeUTF(ChunkPacker.blockToString(chunks[x][z].getOverview()[i].getBlock())); + out.writeUTF(BlockUtils.blockToString(chunks[x][z].getOverview()[i].getBlock())); } } } @@ -240,7 +241,7 @@ public final class CachedRegion implements ICachedRegion { for (int z = 0; z < 32; z++) { if (present[x][z]) { for (int i = 0; i < 256; i++) { - overview[x][z][i] = ChunkPacker.stringToBlockRequired(in.readUTF()).getDefaultState(); + overview[x][z][i] = BlockUtils.stringToBlockRequired(in.readUTF()).getDefaultState(); } } } @@ -255,7 +256,7 @@ public final class CachedRegion implements ICachedRegion { int numSpecialBlockTypes = in.readShort() & 0xffff; for (int i = 0; i < numSpecialBlockTypes; i++) { String blockName = in.readUTF(); - ChunkPacker.stringToBlockRequired(blockName); + BlockUtils.stringToBlockRequired(blockName); List locs = new ArrayList<>(); location[x][z].put(blockName, locs); int numLocations = in.readShort() & 0xffff; diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 949f818c..7c8e4291 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -22,7 +22,7 @@ import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.cache.ICachedWorld; import baritone.api.cache.IWorldData; -import baritone.utils.Helper; +import baritone.api.utils.Helper; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import net.minecraft.util.math.BlockPos; diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index 6834549b..cc5f2188 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -17,12 +17,12 @@ package baritone.cache; +import baritone.api.utils.BlockUtils; import baritone.pathing.movement.MovementHelper; import baritone.utils.pathing.PathingBlockType; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; -import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.BlockStateContainer; import net.minecraft.world.chunk.Chunk; @@ -36,8 +36,6 @@ import java.util.*; */ public final class ChunkPacker { - private static final Map resourceCache = new HashMap<>(); - private ChunkPacker() {} public static CachedChunk pack(Chunk chunk) { @@ -75,7 +73,7 @@ public final class ChunkPacker { bitSet.set(index + 1, bits[1]); Block block = state.getBlock(); if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(block)) { - String name = blockToString(block); + String name = BlockUtils.blockToString(block); specialBlocks.computeIfAbsent(name, b -> new ArrayList<>()).add(new BlockPos(x, y, z)); } } @@ -105,25 +103,6 @@ public final class ChunkPacker { return new CachedChunk(chunk.x, chunk.z, bitSet, blocks, specialBlocks, System.currentTimeMillis()); } - public static String blockToString(Block block) { - ResourceLocation loc = Block.REGISTRY.getNameForObject(block); - String name = loc.getPath(); // normally, only write the part after the minecraft: - if (!loc.getNamespace().equals("minecraft")) { - // Baritone is running on top of forge with mods installed, perhaps? - name = loc.toString(); // include the namespace with the colon - } - return name; - } - - public static Block stringToBlockRequired(String name) { - Block block = stringToBlockNullable(name); - Objects.requireNonNull(block); - return block; - } - - public static Block stringToBlockNullable(String name) { - return resourceCache.computeIfAbsent(name, n -> Block.getBlockFromName(n.contains(":") ? n : "minecraft:" + n)); - } private static PathingBlockType getPathingBlockType(IBlockState state, Chunk chunk, int x, int y, int z) { Block block = state.getBlock(); diff --git a/src/main/java/baritone/cache/WaypointCollection.java b/src/main/java/baritone/cache/WaypointCollection.java index ef319602..18b13b89 100644 --- a/src/main/java/baritone/cache/WaypointCollection.java +++ b/src/main/java/baritone/cache/WaypointCollection.java @@ -19,6 +19,7 @@ package baritone.cache; import baritone.api.cache.IWaypoint; import baritone.api.cache.IWaypointCollection; +import baritone.api.cache.Waypoint; import net.minecraft.util.math.BlockPos; import java.io.*; diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index fe2efa4e..63d0b219 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -19,7 +19,7 @@ package baritone.cache; import baritone.Baritone; import baritone.api.cache.IWorldProvider; -import baritone.utils.Helper; +import baritone.api.utils.Helper; import baritone.utils.accessor.IAnvilChunkLoader; import baritone.utils.accessor.IChunkProviderServer; import net.minecraft.server.integrated.IntegratedServer; diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index b1bb1182..465b5c3f 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -24,7 +24,7 @@ import baritone.api.event.listener.IEventBus; import baritone.api.event.listener.IGameEventListener; import baritone.cache.WorldProvider; import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; +import baritone.api.utils.Helper; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 588b773e..4ab7dc1a 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -24,7 +24,7 @@ import baritone.api.pathing.goals.Goal; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.PathCalculationResult; import baritone.pathing.movement.CalculationContext; -import baritone.utils.Helper; +import baritone.api.utils.Helper; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import java.util.Optional; diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 37441743..92b7c440 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -25,7 +25,7 @@ import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.pathing.path.CutoffPath; -import baritone.utils.Helper; +import baritone.api.utils.Helper; import baritone.utils.pathing.PathBase; import java.util.ArrayList; diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 447e4f08..7215faeb 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -25,7 +25,7 @@ import baritone.api.utils.*; import baritone.api.utils.input.Input; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; +import baritone.api.utils.Helper; import baritone.utils.ToolSet; import net.minecraft.block.*; import net.minecraft.block.properties.PropertyBool; diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 3e767499..e63bf8f1 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -35,7 +35,7 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.movements.*; import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; +import baritone.api.utils.Helper; import net.minecraft.block.BlockLiquid; import net.minecraft.init.Blocks; import net.minecraft.util.Tuple; diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 2550f84d..74912464 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -69,12 +69,6 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro super(baritone); } - public boolean build(String schematicFile, BlockPos origin) { - File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); - System.out.println(file + " " + file.exists()); - return build(schematicFile, file, origin); - } - @Override public void build(String name, ISchematic schematic, Vec3i origin) { this.name = name; diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index eff4d2de..fa252f76 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -22,6 +22,7 @@ import baritone.api.cache.ICachedWorld; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalXZ; +import baritone.api.process.IExploreProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; import baritone.cache.CachedWorld; @@ -31,7 +32,7 @@ import net.minecraft.util.math.BlockPos; import java.util.ArrayList; import java.util.List; -public class ExploreProcess extends BaritoneProcessHelper { +public class ExploreProcess extends BaritoneProcessHelper implements IExploreProcess { private BlockPos explorationOrigin; @@ -44,6 +45,7 @@ public class ExploreProcess extends BaritoneProcessHelper { return explorationOrigin != null; } + @Override public void explore(int centerX, int centerZ) { explorationOrigin = new BlockPos(centerX, 0, centerZ); } diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index 0e2fdaae..43b8b424 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -21,6 +21,7 @@ import baritone.Baritone; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalComposite; +import baritone.api.process.IFarmProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; import baritone.api.utils.Rotation; @@ -50,7 +51,7 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -public class FarmProcess extends BaritoneProcessHelper { +public class FarmProcess extends BaritoneProcessHelper implements IFarmProcess { private boolean active; @@ -90,7 +91,8 @@ public class FarmProcess extends BaritoneProcessHelper { return active; } - public void doit() { + @Override + public void farm() { active = true; } diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 07e47b91..708666a7 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -22,6 +22,7 @@ import baritone.api.pathing.goals.*; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; +import baritone.api.utils.BlockUtils; import baritone.api.utils.IPlayerContext; import baritone.api.utils.RotationUtils; import baritone.cache.CachedChunk; @@ -219,7 +220,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro for (Block m : mining) { if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(m)) { // maxRegionDistanceSq 2 means adjacent directly or adjacent diagonally; nothing further than that - locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), Baritone.settings().maxCachedWorldScanCount.value, ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2)); + locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(BlockUtils.blockToString(m), Baritone.settings().maxCachedWorldScanCount.value, ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2)); } else { uninteresting.add(m); } @@ -303,7 +304,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro @Override public void mineByName(int quantity, String... blocks) { - mine(quantity, blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlockRequired).toArray(Block[]::new)); + mine(quantity, blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(BlockUtils::stringToBlockRequired).toArray(Block[]::new)); } @Override diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index c798c563..a723ebc5 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -22,6 +22,7 @@ import baritone.api.event.events.TickEvent; import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; +import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiMainMenu; diff --git a/src/main/java/baritone/utils/BaritoneProcessHelper.java b/src/main/java/baritone/utils/BaritoneProcessHelper.java index 61c2fd44..6abec949 100644 --- a/src/main/java/baritone/utils/BaritoneProcessHelper.java +++ b/src/main/java/baritone/utils/BaritoneProcessHelper.java @@ -19,6 +19,7 @@ package baritone.utils; import baritone.Baritone; import baritone.api.process.IBaritoneProcess; +import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper { diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index db56b91f..36e2dfea 100644 --- a/src/main/java/baritone/utils/BlockBreakHelper.java +++ b/src/main/java/baritone/utils/BlockBreakHelper.java @@ -17,6 +17,7 @@ package baritone.utils; +import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; diff --git a/src/main/java/baritone/utils/BlockPlaceHelper.java b/src/main/java/baritone/utils/BlockPlaceHelper.java index ed472d57..ee8f2b73 100644 --- a/src/main/java/baritone/utils/BlockPlaceHelper.java +++ b/src/main/java/baritone/utils/BlockPlaceHelper.java @@ -18,6 +18,7 @@ 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; diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index e4fd58b1..d1afe34d 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -23,6 +23,7 @@ import baritone.api.event.events.RenderEvent; 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.interfaces.IGoalRenderPos; import baritone.behavior.PathingBehavior; import baritone.pathing.path.PathExecutor; diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java index 20fe9836..61c0f9b0 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java @@ -22,7 +22,7 @@ import baritone.api.cache.IWorldData; import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerController; import baritone.api.utils.RayTraceUtils; -import baritone.utils.Helper; +import baritone.api.utils.Helper; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerController.java b/src/main/java/baritone/utils/player/PrimaryPlayerController.java index b9828c80..5445c105 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerController.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerController.java @@ -18,7 +18,7 @@ package baritone.utils.player; import baritone.api.utils.IPlayerController; -import baritone.utils.Helper; +import baritone.api.utils.Helper; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; From 0b72a8b4b38681cb3ce6f700cc2b0b187c2f4086 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 17 Apr 2019 19:46:25 -0700 Subject: [PATCH 339/682] fix overshoot --- .../baritone/pathing/movement/MovementHelper.java | 5 ++++- src/main/java/baritone/pathing/path/PathExecutor.java | 11 +++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 7215faeb..3abba65f 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -25,7 +25,6 @@ import baritone.api.utils.*; import baritone.api.utils.input.Input; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.BlockStateInterface; -import baritone.api.utils.Helper; import baritone.utils.ToolSet; import net.minecraft.block.*; import net.minecraft.block.properties.PropertyBool; @@ -312,6 +311,10 @@ public interface MovementHelper extends ActionCosts, Helper { return canWalkOn(new BlockStateInterface(ctx), pos.x, pos.y, pos.z, state); } + static boolean canWalkOn(IPlayerContext ctx, BlockPos pos) { + return canWalkOn(new BlockStateInterface(ctx), pos.getX(), pos.getY(), pos.getZ()); + } + static boolean canWalkOn(IPlayerContext ctx, BetterBlockPos pos) { return canWalkOn(new BlockStateInterface(ctx), pos.x, pos.y, pos.z); } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index e63bf8f1..c848f42b 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -23,10 +23,7 @@ import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; import baritone.api.pathing.path.IPathExecutor; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.IPlayerContext; -import baritone.api.utils.RotationUtils; -import baritone.api.utils.VecUtils; +import baritone.api.utils.*; import baritone.api.utils.input.Input; import baritone.behavior.PathingBehavior; import baritone.pathing.calc.AbstractNodeCostSearch; @@ -35,7 +32,6 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.movements.*; import baritone.utils.BlockStateInterface; -import baritone.api.utils.Helper; import net.minecraft.block.BlockLiquid; import net.minecraft.init.Blocks; import net.minecraft.util.Tuple; @@ -569,7 +565,10 @@ public class PathExecutor implements IPathExecutor, Helper { if (next instanceof MovementDescend && next.getDirection().equals(current.getDirection())) { return true; } - if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(ctx, next.getDest().down())) { + if (!MovementHelper.canWalkOn(ctx, current.getDest().add(current.getDirection()))) { + return false; + } + if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection())) { return true; } return next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.value; From 518fa1c74daa7e8b9f764038410cc7b4fb982e94 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 17 Apr 2019 19:49:04 -0700 Subject: [PATCH 340/682] reformat all files --- src/api/java/baritone/api/behavior/IBehavior.java | 3 +-- .../java/baritone/api/pathing/goals/GoalStrictDirection.java | 1 - src/main/java/baritone/behavior/MemoryBehavior.java | 2 +- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- src/main/java/baritone/event/GameEventHandler.java | 2 +- .../java/baritone/pathing/calc/AbstractNodeCostSearch.java | 2 +- src/main/java/baritone/pathing/calc/Path.java | 2 +- .../baritone/pathing/movement/movements/MovementAscend.java | 2 +- src/main/java/baritone/process/BuilderProcess.java | 1 - src/main/java/baritone/process/MineProcess.java | 1 - src/main/java/baritone/utils/player/PrimaryPlayerContext.java | 2 +- .../java/baritone/utils/player/PrimaryPlayerController.java | 2 +- 12 files changed, 9 insertions(+), 13 deletions(-) diff --git a/src/api/java/baritone/api/behavior/IBehavior.java b/src/api/java/baritone/api/behavior/IBehavior.java index fbef5258..811563b9 100644 --- a/src/api/java/baritone/api/behavior/IBehavior.java +++ b/src/api/java/baritone/api/behavior/IBehavior.java @@ -23,9 +23,8 @@ import baritone.api.event.listener.IGameEventListener; /** * A behavior is simply a type that is able to listen to events. * - * @see IGameEventListener - * * @author Brady + * @see IGameEventListener * @since 9/23/2018 */ public interface IBehavior extends AbstractGameEventListener {} diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java index 749bed62..24ae385a 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java +++ b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java @@ -17,7 +17,6 @@ package baritone.api.pathing.goals; -import baritone.api.BaritoneAPI; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 72d648d9..d98e3237 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -18,13 +18,13 @@ package baritone.behavior; import baritone.Baritone; +import baritone.api.cache.Waypoint; import baritone.api.event.events.BlockInteractEvent; import baritone.api.event.events.PacketEvent; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.TickEvent; import baritone.api.event.events.type.EventState; import baritone.cache.ContainerMemory; -import baritone.api.cache.Waypoint; import baritone.utils.BlockStateInterface; import net.minecraft.block.Block; import net.minecraft.block.BlockBed; diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index ac826fbf..e0031c8c 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -25,6 +25,7 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; import baritone.api.process.PathingCommand; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Helper; import baritone.api.utils.PathCalculationResult; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.pathing.calc.AStarPathFinder; @@ -32,7 +33,6 @@ import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.pathing.path.PathExecutor; -import baritone.api.utils.Helper; import baritone.utils.PathRenderer; import baritone.utils.PathingCommandContext; import baritone.utils.pathing.Favoring; diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 465b5c3f..2ff688ad 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -22,9 +22,9 @@ import baritone.api.event.events.*; import baritone.api.event.events.type.EventState; import baritone.api.event.listener.IEventBus; import baritone.api.event.listener.IGameEventListener; +import baritone.api.utils.Helper; import baritone.cache.WorldProvider; import baritone.utils.BlockStateInterface; -import baritone.api.utils.Helper; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 4ab7dc1a..30282748 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -22,9 +22,9 @@ import baritone.api.pathing.calc.IPath; import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Helper; import baritone.api.utils.PathCalculationResult; import baritone.pathing.movement.CalculationContext; -import baritone.api.utils.Helper; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import java.util.Optional; diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 92b7c440..a3f9dd22 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -21,11 +21,11 @@ import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Helper; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.pathing.path.CutoffPath; -import baritone.api.utils.Helper; import baritone.utils.pathing.PathBase; import java.util.ArrayList; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 2ba10f70..b37fd4d0 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -197,7 +197,7 @@ public class MovementAscend extends Movement { if (headBonkClear()) { return state.setInput(Input.JUMP, true); } - + if (flatDistToNext > 1.2 || sideDist > 0.2) { return state; } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 74912464..299862cc 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -36,7 +36,6 @@ import baritone.utils.PathingCommandContext; import baritone.utils.schematic.AirSchematic; import baritone.utils.schematic.Schematic; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 708666a7..cc168c56 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -26,7 +26,6 @@ import baritone.api.utils.BlockUtils; import baritone.api.utils.IPlayerContext; import baritone.api.utils.RotationUtils; import baritone.cache.CachedChunk; -import baritone.cache.ChunkPacker; import baritone.cache.WorldScanner; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java index 61c0f9b0..3cb498ac 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java @@ -19,10 +19,10 @@ package baritone.utils.player; 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.Helper; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerController.java b/src/main/java/baritone/utils/player/PrimaryPlayerController.java index 5445c105..120f996c 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerController.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerController.java @@ -17,8 +17,8 @@ package baritone.utils.player; -import baritone.api.utils.IPlayerController; import baritone.api.utils.Helper; +import baritone.api.utils.IPlayerController; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; From 343bb20bd861d48bc7a04e1fd7faf2783721be6f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 17 Apr 2019 20:02:02 -0700 Subject: [PATCH 341/682] fix weird cache behavior at chunk edge --- src/main/java/baritone/cache/ChunkPacker.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index cc5f2188..864f23d6 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -112,15 +112,20 @@ public final class ChunkPacker { if (MovementHelper.possiblyFlowing(state)) { return PathingBlockType.AVOID; } + if ( + (x != 15 && MovementHelper.possiblyFlowing(chunk.getBlockState(x + 1, y, z))) + || (x != 0 && MovementHelper.possiblyFlowing(chunk.getBlockState(x - 1, y, z))) + || (z != 15 && MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z + 1))) + || (z != 0 && MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z - 1))) + ) { + return PathingBlockType.AVOID; + } if (x == 0 || x == 15 || z == 0 || z == 15) { if (BlockLiquid.getSlopeAngle(chunk.getWorld(), new BlockPos(x + chunk.x << 4, y, z + chunk.z << 4), state.getMaterial(), state) == -1000.0F) { return PathingBlockType.WATER; } return PathingBlockType.AVOID; } - if (MovementHelper.possiblyFlowing(chunk.getBlockState(x + 1, y, z)) || MovementHelper.possiblyFlowing(chunk.getBlockState(x - 1, y, z)) || MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z + 1)) || MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z - 1))) { - return PathingBlockType.AVOID; - } return PathingBlockType.WATER; } From 6599736e00bda2f6358d9880d86999e68e41af10 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 17 Apr 2019 20:23:30 -0700 Subject: [PATCH 342/682] fix that reference --- .../pathing/movement/movements/MovementTraverse.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 012180e5..881571bc 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -246,12 +246,13 @@ public class MovementTraverse extends Movement { if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, ctx.playerFeet()) || Baritone.settings().sprintInWater.value) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) { state.setInput(Input.SPRINT, true); } - Block destDown = BlockStateInterface.get(ctx, dest.down()).getBlock(); - if (whereAmI.getY() != dest.getY() && ladder && (destDown == Blocks.VINE || destDown == Blocks.LADDER)) { - new MovementPillar(baritone, dest.down(), dest).updateState(state); // i'm sorry - return state; + + IBlockState destDown = BlockStateInterface.get(ctx, dest.down()); + BlockPos against = positionsToBreak[0]; + if (whereAmI.getY() != dest.getY() && ladder && (destDown.getBlock() == Blocks.VINE || destDown.getBlock() == Blocks.LADDER)) { + against = destDown.getBlock() == Blocks.VINE ? MovementPillar.getAgainst(new CalculationContext(baritone), dest.down()) : dest.offset(destDown.getValue(BlockLadder.FACING).getOpposite()); } - MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); + MovementHelper.moveTowards(ctx, state, against); return state; } else { wasTheBridgeBlockAlwaysThere = false; From 26256e71554e379cc2b8a5f55eb83f728b1c4eee Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 17 Apr 2019 22:17:09 -0700 Subject: [PATCH 343/682] mine is now MUCH more epic --- .../api/pathing/goals/GoalTwoBlocks.java | 6 +- .../java/baritone/process/MineProcess.java | 62 +++++++++++++++++-- .../java/baritone/utils/pathing/Favoring.java | 3 +- 3 files changed, 62 insertions(+), 9 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java index b1dc07a1..f1026ab5 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java +++ b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java @@ -31,17 +31,17 @@ public class GoalTwoBlocks implements Goal, IGoalRenderPos { /** * The X block position of this goal */ - private final int x; + protected final int x; /** * The Y block position of this goal */ - private final int y; + protected final int y; /** * The Z block position of this goal */ - private final int z; + protected final int z; public GoalTwoBlocks(BlockPos pos) { this(pos.getX(), pos.getY(), pos.getZ()); diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index cc168c56..5ace2130 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -24,7 +24,9 @@ import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; import baritone.api.utils.BlockUtils; import baritone.api.utils.IPlayerContext; +import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; +import baritone.api.utils.input.Input; import baritone.cache.CachedChunk; import baritone.cache.WorldScanner; import baritone.pathing.movement.CalculationContext; @@ -32,6 +34,8 @@ import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; import net.minecraft.block.Block; +import net.minecraft.block.BlockAir; +import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; @@ -94,14 +98,35 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return null; } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.value; + List curr = new ArrayList<>(knownOreLocations); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain - List curr = new ArrayList<>(knownOreLocations); CalculationContext context = new CalculationContext(baritone, true); Baritone.getExecutor().execute(() -> rescan(curr, context)); } if (Baritone.settings().legitMine.value) { addNearby(); } + Optional shaft = curr.stream() + .filter(pos -> pos.getX() == ctx.playerFeet().getX() && pos.getZ() == ctx.playerFeet().getZ()) + .filter(pos -> pos.getY() > ctx.playerFeet().getY()) + .filter(pos -> !(BlockStateInterface.get(ctx, pos).getBlock() instanceof BlockAir)) // after breaking a block, it takes mineGoalUpdateInterval ticks for it to actually update this list =( + .min(Comparator.comparingDouble(ctx.player()::getDistanceSq)); + baritone.getInputOverrideHandler().clearAllKeys(); + if (shaft.isPresent()) { + BlockPos pos = shaft.get(); + IBlockState state = baritone.bsi.get0(pos); + if (!MovementHelper.avoidBreaking(baritone.bsi, pos.getX(), pos.getY(), pos.getZ(), state)) { + Optional rot = RotationUtils.reachable(ctx, pos); + if (rot.isPresent() && isSafeToCancel) { + baritone.getLookBehavior().updateTarget(rot.get(), true); + MovementHelper.switchToBestToolFor(ctx, ctx.world().getBlockState(pos)); + if (ctx.isLookingAt(pos) || ctx.playerRotations().isReallyCloseTo(rot.get())) { + baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); + } + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + } + } PathingCommand command = updateGoal(); if (command == null) { // none in range @@ -178,15 +203,42 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro knownOreLocations = locs; } + private static boolean internalMiningGoal(BlockPos pos, IPlayerContext ctx, List locs) { + return locs.contains(pos) || (Baritone.settings().internalMiningAirException.value && BlockStateInterface.getBlock(ctx, pos) instanceof BlockAir); + } + private static Goal coalesce(IPlayerContext ctx, BlockPos loc, List locs) { if (!Baritone.settings().forceInternalMining.value) { - return new GoalTwoBlocks(loc); + return new GoalThreeBlocks(loc); } + //if upwardGoal is false, and downward is true + // Here, BlockStateInterface is used because the position may be in a cached chunk (the targeted block is one that is kept track of) - boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.value && BlockStateInterface.getBlock(ctx, loc.up()) == Blocks.AIR); - boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.value && BlockStateInterface.getBlock(ctx, loc.down()) == Blocks.AIR); - return upwardGoal == downwardGoal ? new GoalTwoBlocks(loc) : upwardGoal ? new GoalBlock(loc) : new GoalBlock(loc.down()); + boolean upwardGoal = internalMiningGoal(loc.up(), ctx, locs); + boolean downwardGoal = internalMiningGoal(loc.down(), ctx, locs); + boolean doubleDownwardGoal = internalMiningGoal(loc.down(2), ctx, locs); + return upwardGoal == downwardGoal ? doubleDownwardGoal ? new GoalThreeBlocks(loc) : new GoalTwoBlocks(loc) : upwardGoal ? new GoalBlock(loc) : doubleDownwardGoal ? new GoalTwoBlocks(loc.down()) : new GoalBlock(loc.down()); + } + + private static class GoalThreeBlocks extends GoalTwoBlocks { + + public GoalThreeBlocks(BlockPos pos) { + super(pos); + } + + @Override + public boolean isInGoal(int x, int y, int z) { + return x == this.x && (y == this.y || y == this.y - 1 || y == this.y - 2) && z == this.z; + } + + @Override + public double heuristic(int x, int y, int z) { + int xDiff = x - this.x; + int yDiff = y - this.y; + int zDiff = z - this.z; + return GoalBlock.calculate(xDiff, yDiff < -1 ? yDiff + 2 : yDiff == -1 ? 0 : yDiff, zDiff); + } } public static List droppedItemsScan(List mining, World world) { diff --git a/src/main/java/baritone/utils/pathing/Favoring.java b/src/main/java/baritone/utils/pathing/Favoring.java index 8a601758..56ccb006 100644 --- a/src/main/java/baritone/utils/pathing/Favoring.java +++ b/src/main/java/baritone/utils/pathing/Favoring.java @@ -19,6 +19,7 @@ package baritone.utils.pathing; import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.pathing.movement.CalculationContext; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; @@ -31,7 +32,7 @@ public final class Favoring { for (Avoidance avoid : Avoidance.create(ctx)) { avoid.applySpherical(favorings); } - System.out.println("Favoring size: " + favorings.size()); + Helper.HELPER.logDebug("Favoring size: " + favorings.size()); } public Favoring(IPath previous, CalculationContext context) { // create one just from previous path, no mob avoidances From b64154e3b370a8e39c38428a68bef68a37b5cf63 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 17 Apr 2019 23:25:55 -0700 Subject: [PATCH 344/682] meme for cached blocks that arent packed yet --- src/api/java/baritone/api/Settings.java | 7 +++++++ src/main/java/baritone/process/MineProcess.java | 6 +----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 0892f28d..89dc6565 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -570,6 +570,13 @@ public final class Settings { */ public final Setting exploreForBlocks = new Setting<>(true); + /** + * When the cache scan gives less blocks than the maximum threshold (but still above zero), scan the main world too. + *

+ * Only if you have a beefy CPU and automatically mine blocks that are in cache + */ + public final Setting extendCacheOnThreshold = new Setting<>(false); + /** * Don't consider the next layer in builder until the current one is done */ diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 5ace2130..bda8e446 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -267,7 +267,6 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro public static List searchWorld(CalculationContext ctx, List mining, int max, List alreadyKnown, List blacklist) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); - //long b = System.currentTimeMillis(); for (Block m : mining) { if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(m)) { // maxRegionDistanceSq 2 means adjacent directly or adjacent diagonally; nothing further than that @@ -277,14 +276,11 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } locs = prune(ctx, locs, mining, max, blacklist); - //System.out.println("Scan of cached chunks took " + (System.currentTimeMillis() - b) + "ms"); - if (locs.isEmpty()) { + if (locs.isEmpty() || (Baritone.settings().extendCacheOnThreshold.value && locs.size() < max)) { uninteresting = mining; } if (!uninteresting.isEmpty()) { - //long before = System.currentTimeMillis(); locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), uninteresting, max, 10, 32)); // maxSearchRadius is NOT sq - //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); } locs.addAll(alreadyKnown); return prune(ctx, locs, mining, max, blacklist); From 7a2f26ef620e015f0292f6477fed257c8bbeff02 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 18 Apr 2019 10:36:20 -0700 Subject: [PATCH 345/682] replace scuffed ternary with commented if --- .../java/baritone/process/MineProcess.java | 31 ++++++++++++++++--- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index bda8e446..a1a69526 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -204,6 +204,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } private static boolean internalMiningGoal(BlockPos pos, IPlayerContext ctx, List locs) { + // Here, BlockStateInterface is used because the position may be in a cached chunk (the targeted block is one that is kept track of) return locs.contains(pos) || (Baritone.settings().internalMiningAirException.value && BlockStateInterface.getBlock(ctx, pos) instanceof BlockAir); } @@ -211,14 +212,34 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (!Baritone.settings().forceInternalMining.value) { return new GoalThreeBlocks(loc); } - - //if upwardGoal is false, and downward is true - - // Here, BlockStateInterface is used because the position may be in a cached chunk (the targeted block is one that is kept track of) boolean upwardGoal = internalMiningGoal(loc.up(), ctx, locs); boolean downwardGoal = internalMiningGoal(loc.down(), ctx, locs); boolean doubleDownwardGoal = internalMiningGoal(loc.down(2), ctx, locs); - return upwardGoal == downwardGoal ? doubleDownwardGoal ? new GoalThreeBlocks(loc) : new GoalTwoBlocks(loc) : upwardGoal ? new GoalBlock(loc) : doubleDownwardGoal ? new GoalTwoBlocks(loc.down()) : new GoalBlock(loc.down()); + if (upwardGoal == downwardGoal) { // symmetric + if (doubleDownwardGoal) { + // we have a checkerboard like pattern + // this one, and the one two below it + // therefore it's fine to path to immediately below this one, since your feet will be in the doubleDownwardGoal + return new GoalThreeBlocks(loc); + } else { + // this block has nothing interesting two below, but is symmetric vertically so we can get either feet or head into it + return new GoalTwoBlocks(loc); + } + } + if (upwardGoal) { + // downwardGoal known to be false + // ignore the gap then potential doubleDownward, because we want to path feet into this one and head into upwardGoal + return new GoalBlock(loc); + } + // upwardGoal known to be false, downwardGoal known to be true + if (doubleDownwardGoal) { + // this block and two below it are goals + // path into the center of the one below, because that includes directly below this one + return new GoalTwoBlocks(loc.down()); + } + // upwardGoal false, downwardGoal true, doubleDownwardGoal false + // just this block and the one immediately below, no others + return new GoalBlock(loc.down()); } private static class GoalThreeBlocks extends GoalTwoBlocks { From 47e1c67bd8191430ad2d19d75cc023ae6cb51d5b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 19 Apr 2019 14:20:00 -0700 Subject: [PATCH 346/682] fix that null exception --- src/api/java/baritone/api/process/PathingCommandType.java | 7 ++++++- src/main/java/baritone/process/BackfillProcess.java | 4 ++-- src/main/java/baritone/utils/PathingControlManager.java | 8 ++++---- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/api/java/baritone/api/process/PathingCommandType.java b/src/api/java/baritone/api/process/PathingCommandType.java index da64748a..af25591a 100644 --- a/src/api/java/baritone/api/process/PathingCommandType.java +++ b/src/api/java/baritone/api/process/PathingCommandType.java @@ -51,5 +51,10 @@ public enum PathingCommandType { *

* Cancel the current path if the goals are not equal */ - FORCE_REVALIDATE_GOAL_AND_PATH + FORCE_REVALIDATE_GOAL_AND_PATH, + + /** + * Go and ask the next process what to do + */ + DEFER } diff --git a/src/main/java/baritone/process/BackfillProcess.java b/src/main/java/baritone/process/BackfillProcess.java index e2bb70da..c3461faa 100644 --- a/src/main/java/baritone/process/BackfillProcess.java +++ b/src/main/java/baritone/process/BackfillProcess.java @@ -87,7 +87,7 @@ public class BackfillProcess extends BaritoneProcessHelper { return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } } - return null; // cede to other process + return new PathingCommand(null, PathingCommandType.DEFER); // cede to other process } public void amIBreakingABlockHMMMMMMM() { @@ -119,7 +119,7 @@ public class BackfillProcess extends BaritoneProcessHelper { @Override public void onLostControl() { - blocksToReplace = new HashMap<>(); + blocksToReplace.clear(); } @Override diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 46b69ec2..92b66c49 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -199,11 +199,11 @@ public class PathingControlManager implements IPathingControlManager { PathingCommand exec = proc.onTick(Objects.equals(proc, inControlLastTick) && baritone.getPathingBehavior().calcFailedLastTick(), baritone.getPathingBehavior().isSafeToCancel()); if (exec == null) { - /*if (proc.isActive()) { - throw new IllegalStateException(proc.displayName() + " returned null PathingCommand"); + if (proc.isActive()) { + throw new IllegalStateException(proc.displayName() + " actively returned null PathingCommand"); } - proc.onLostControl();*/ - } else { + // no need to call onLostControl; they are reporting inactive. + } else if (exec.commandType != PathingCommandType.DEFER) { inControlThisTick = proc; if (!proc.isTemporary()) { iterator.forEachRemaining(IBaritoneProcess::onLostControl); From 2fcf9ace6403b515ee62e3d0e04250cae358cb4f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 19 Apr 2019 15:10:10 -0700 Subject: [PATCH 347/682] exploration chunk offset --- src/api/java/baritone/api/Settings.java | 7 +++++++ .../java/baritone/process/ExploreProcess.java | 16 ++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 89dc6565..8fbc6b85 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -570,6 +570,13 @@ public final class Settings { */ public final Setting exploreForBlocks = new Setting<>(true); + /** + * While exploring the world, offset the closest unloaded chunk by this much in both axes. + *

+ * This can result in more efficient loading, if you set this to the render distance. + */ + public final Setting worldExploringChunkOffset = new Setting<>(0); + /** * When the cache scan gives less blocks than the maximum threshold (but still above zero), scan the main world too. *

diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index fa252f76..0b26887e 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -62,7 +62,6 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro logDebug("awaiting region load from disk"); return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } - System.out.println("Closest uncached: " + closestUncached); return new PathingCommand(new GoalComposite(closestUncached), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); } @@ -90,7 +89,20 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro }); return null; // we still need to load regions from disk in order to decide properly } - centers.add(new BlockPos(centerX, 0, centerZ)); + int offsetCenterX = centerX; + int offsetCenterZ = centerZ; + int offset = 16 * Baritone.settings().worldExploringChunkOffset.value; + if (dx < 0) { + offsetCenterX -= offset; + } else { + offsetCenterX += offset; + } + if (dz < 0) { + offsetCenterZ -= offset; + } else { + offsetCenterZ += offset; + } + centers.add(new BlockPos(offsetCenterX, 0, offsetCenterZ)); } } if (!centers.isEmpty()) { From af0c3bbd5c1a6a6f95180c52c6171a3d43458a37 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 19 Apr 2019 21:02:58 -0700 Subject: [PATCH 348/682] just one is not good enough tbh --- src/api/java/baritone/api/Settings.java | 7 ++++++- src/main/java/baritone/process/ExploreProcess.java | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 8fbc6b85..0676049d 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -577,6 +577,11 @@ public final class Settings { */ public final Setting worldExploringChunkOffset = new Setting<>(0); + /** + * Take the 10 closest chunks, even if they aren't strictly tied for distance metric from origin. + */ + public final Setting exploreChunkSetMinimumSize = new Setting<>(10); + /** * When the cache scan gives less blocks than the maximum threshold (but still above zero), scan the main world too. *

@@ -595,7 +600,7 @@ public final class Settings { public final Setting buildRepeatDistance = new Setting<>(0); /** - * What direction te repeat the build in + * What direction to repeat the build in */ public final Setting buildRepeatDirection = new Setting<>(EnumFacing.NORTH); diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 0b26887e..b848b679 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -105,7 +105,7 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro centers.add(new BlockPos(offsetCenterX, 0, offsetCenterZ)); } } - if (!centers.isEmpty()) { + if (centers.size() > Baritone.settings().exploreChunkSetMinimumSize.value) { return centers.stream().map(pos -> new GoalXZ(pos.getX(), pos.getZ())).toArray(Goal[]::new); } } From c4c85b4f49b1721f8e003c76febdda4fc38a0970 Mon Sep 17 00:00:00 2001 From: cdagaming Date: Sat, 20 Apr 2019 12:04:07 -0500 Subject: [PATCH 349/682] [Change] Add Block Avoidance Settings Fixes #392 --- src/api/java/baritone/api/Settings.java | 17 +++++++++++++++++ .../pathing/movement/MovementHelper.java | 3 +++ .../java/baritone/utils/pathing/Avoidance.java | 8 ++++++++ 3 files changed, 28 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 0676049d..ece3b23f 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -18,6 +18,7 @@ package baritone.api; import baritone.api.utils.SettingsUtil; +import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.item.Item; @@ -146,6 +147,13 @@ public final class Settings { Item.getItemFromBlock(Blocks.STONE) ))); + /** + * Blocks that Baritone will attempt to avoid (Used in avoidance) + */ + public final Setting> blocksToAvoid = new Setting<>(new ArrayList<>(Arrays.asList( + Blocks.VINE + ))); + /** * Enables some more advanced vine features. They're honestly just gimmicks and won't ever be needed in real * pathing scenarios. And they can cause Baritone to get trapped indefinitely in a strange scenario. @@ -250,6 +258,15 @@ public final class Settings { public final Setting mobAvoidanceRadius = new Setting<>(8); + /** + * Set to 1.0 to effectively disable this feature + *

+ * Set below 1.0 to go out of your way to walk near blocks + */ + public final Setting blockAvoidanceCoefficient = new Setting<>(1.5); + + public final Setting blockAvoidanceRadius = new Setting<>(8); + /** * When running a goto towards a container block (chest, ender chest, furnace, etc), * right click and open it once you arrive. diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 3abba65f..52ed9924 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -74,6 +74,9 @@ public interface MovementHelper extends ActionCosts, Helper { if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.WEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof BlockSkull || block instanceof BlockTrapDoor) { return false; } + if (Baritone.settings().blocksToAvoid.value.contains(block)) { + return false; + } if (block instanceof BlockDoor || block instanceof BlockFenceGate) { // Because there's no nice method in vanilla to check if a door is openable or not, we just have to assume // that anything that isn't an iron door isn't openable, ignoring that some doors introduced in mods can't diff --git a/src/main/java/baritone/utils/pathing/Avoidance.java b/src/main/java/baritone/utils/pathing/Avoidance.java index 9b32b1df..f1b2cac7 100644 --- a/src/main/java/baritone/utils/pathing/Avoidance.java +++ b/src/main/java/baritone/utils/pathing/Avoidance.java @@ -19,8 +19,10 @@ package baritone.utils.pathing; import baritone.Baritone; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.BlockUtils; import baritone.api.utils.IPlayerContext; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; +import net.minecraft.block.Block; import net.minecraft.entity.monster.EntityMob; import net.minecraft.util.math.BlockPos; @@ -63,12 +65,18 @@ public class Avoidance { List res = new ArrayList<>(); double mobSpawnerCoeff = Baritone.settings().mobSpawnerAvoidanceCoefficient.value; double mobCoeff = Baritone.settings().mobAvoidanceCoefficient.value; + double blockCoeff = Baritone.settings().blockAvoidanceCoefficient.value; if (mobSpawnerCoeff != 1.0D) { ctx.worldData().getCachedWorld().getLocationsOf("mob_spawner", 1, ctx.playerFeet().x, ctx.playerFeet().z, 2).forEach(mobspawner -> res.add(new Avoidance(mobspawner, mobSpawnerCoeff, Baritone.settings().mobSpawnerAvoidanceRadius.value))); } if (mobCoeff != 1.0D) { ctx.world().loadedEntityList.stream().filter(entity -> entity instanceof EntityMob).forEach(entity -> res.add(new Avoidance(new BlockPos(entity), mobCoeff, Baritone.settings().mobAvoidanceRadius.value))); } + if (blockCoeff != 1.0D) { + for (Block block : Baritone.settings().blocksToAvoid.value) { + ctx.worldData().getCachedWorld().getLocationsOf(BlockUtils.blockToString(block), 1, ctx.playerFeet().x, ctx.playerFeet().z, 2).forEach(blockPos -> res.add(new Avoidance(blockPos, blockCoeff, Baritone.settings().blockAvoidanceRadius.value))); + } + } return res; } From 13469053b9ccc92dbc90ce32e1ac0976d4f83c26 Mon Sep 17 00:00:00 2001 From: cdagaming Date: Sat, 20 Apr 2019 12:11:46 -0500 Subject: [PATCH 350/682] [Change] Suggested Changes --- src/api/java/baritone/api/Settings.java | 2 +- src/main/java/baritone/utils/pathing/Avoidance.java | 8 -------- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index ece3b23f..42273335 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -151,7 +151,7 @@ public final class Settings { * Blocks that Baritone will attempt to avoid (Used in avoidance) */ public final Setting> blocksToAvoid = new Setting<>(new ArrayList<>(Arrays.asList( - Blocks.VINE + // Leave Empty by Default ))); /** diff --git a/src/main/java/baritone/utils/pathing/Avoidance.java b/src/main/java/baritone/utils/pathing/Avoidance.java index f1b2cac7..9b32b1df 100644 --- a/src/main/java/baritone/utils/pathing/Avoidance.java +++ b/src/main/java/baritone/utils/pathing/Avoidance.java @@ -19,10 +19,8 @@ package baritone.utils.pathing; import baritone.Baritone; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.BlockUtils; import baritone.api.utils.IPlayerContext; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; -import net.minecraft.block.Block; import net.minecraft.entity.monster.EntityMob; import net.minecraft.util.math.BlockPos; @@ -65,18 +63,12 @@ public class Avoidance { List res = new ArrayList<>(); double mobSpawnerCoeff = Baritone.settings().mobSpawnerAvoidanceCoefficient.value; double mobCoeff = Baritone.settings().mobAvoidanceCoefficient.value; - double blockCoeff = Baritone.settings().blockAvoidanceCoefficient.value; if (mobSpawnerCoeff != 1.0D) { ctx.worldData().getCachedWorld().getLocationsOf("mob_spawner", 1, ctx.playerFeet().x, ctx.playerFeet().z, 2).forEach(mobspawner -> res.add(new Avoidance(mobspawner, mobSpawnerCoeff, Baritone.settings().mobSpawnerAvoidanceRadius.value))); } if (mobCoeff != 1.0D) { ctx.world().loadedEntityList.stream().filter(entity -> entity instanceof EntityMob).forEach(entity -> res.add(new Avoidance(new BlockPos(entity), mobCoeff, Baritone.settings().mobAvoidanceRadius.value))); } - if (blockCoeff != 1.0D) { - for (Block block : Baritone.settings().blocksToAvoid.value) { - ctx.worldData().getCachedWorld().getLocationsOf(BlockUtils.blockToString(block), 1, ctx.playerFeet().x, ctx.playerFeet().z, 2).forEach(blockPos -> res.add(new Avoidance(blockPos, blockCoeff, Baritone.settings().blockAvoidanceRadius.value))); - } - } return res; } From dd8406c39ab78ecd93a14d5298c06ca2e53c8d56 Mon Sep 17 00:00:00 2001 From: cdagaming Date: Sat, 20 Apr 2019 12:13:28 -0500 Subject: [PATCH 351/682] [Fix] Remove unused Settings --- src/api/java/baritone/api/Settings.java | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 42273335..651b6af3 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -257,16 +257,7 @@ public final class Settings { public final Setting mobAvoidanceCoefficient = new Setting<>(1.5); public final Setting mobAvoidanceRadius = new Setting<>(8); - - /** - * Set to 1.0 to effectively disable this feature - *

- * Set below 1.0 to go out of your way to walk near blocks - */ - public final Setting blockAvoidanceCoefficient = new Setting<>(1.5); - - public final Setting blockAvoidanceRadius = new Setting<>(8); - + /** * When running a goto towards a container block (chest, ender chest, furnace, etc), * right click and open it once you arrive. From d5a8ed5cb162a461326b6372984ac2b0e032f18d Mon Sep 17 00:00:00 2001 From: cdagaming Date: Sat, 20 Apr 2019 12:32:35 -0500 Subject: [PATCH 352/682] [Change] More Suggested changes --- src/api/java/baritone/api/Settings.java | 4 ++-- src/api/java/baritone/api/utils/SettingsUtil.java | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 651b6af3..47459ae8 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -150,7 +150,7 @@ public final class Settings { /** * Blocks that Baritone will attempt to avoid (Used in avoidance) */ - public final Setting> blocksToAvoid = new Setting<>(new ArrayList<>(Arrays.asList( + public final Setting> blocksToAvoid = new Setting<>(new LinkedList<>(Arrays.asList( // Leave Empty by Default ))); @@ -257,7 +257,7 @@ public final class Settings { public final Setting mobAvoidanceCoefficient = new Setting<>(1.5); public final Setting mobAvoidanceRadius = new Setting<>(8); - + /** * When running a goto towards a container block (chest, ender chest, furnace, etc), * right click and open it once you arrive. diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 60014bbd..f5cb17e1 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -18,6 +18,7 @@ package baritone.api.utils; import baritone.api.Settings; +import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; @@ -147,6 +148,7 @@ public class SettingsUtil { FLOAT(Float.class, Float::parseFloat), LONG(Long.class, Long::parseLong), + BLOCK_LIST(LinkedList.class, str -> Stream.of(str.split(",")).map(String::trim).map(BlockUtils::stringToBlockRequired).collect(Collectors.toCollection(LinkedList::new)), list -> ((LinkedList) list).stream().map(BlockUtils::blockToString).collect(Collectors.joining(","))), ITEM_LIST(ArrayList.class, str -> Stream.of(str.split(",")).map(String::trim).map(Item::getByNameOrId).collect(Collectors.toCollection(ArrayList::new)), list -> ((ArrayList) list).stream().map(Item.REGISTRY::getNameForObject).map(ResourceLocation::toString).collect(Collectors.joining(","))), COLOR(Color.class, str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])), color -> color.getRed() + "," + color.getGreen() + "," + color.getBlue()), ENUMFACING(EnumFacing.class, EnumFacing::byName); From 498e4e2d6c1c3b802115df32f4e7f97394ec001a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 20 Apr 2019 11:03:59 -0700 Subject: [PATCH 353/682] replant nether wart setting --- src/api/java/baritone/api/Settings.java | 5 ++ .../baritone/behavior/InventoryBehavior.java | 12 ++-- .../java/baritone/process/FarmProcess.java | 66 +++++++++---------- 3 files changed, 43 insertions(+), 40 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 47459ae8..419ee236 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -590,6 +590,11 @@ public final class Settings { */ public final Setting exploreChunkSetMinimumSize = new Setting<>(10); + /** + * Replant nether wart + */ + public final Setting replantNetherWart = new Setting<>(false); + /** * When the cache scan gives less blocks than the maximum threshold (but still above zero), scan the main world too. *

diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 120bc748..b751c2ce 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -123,7 +123,7 @@ public class InventoryBehavior extends Behavior { public boolean hasGenericThrowaway() { for (Item item : Baritone.settings().acceptableThrowawayItems.value) { - if (throwaway(false, item::equals)) { + if (throwaway(false, stack -> item.equals(stack.getItem()))) { return true; } } @@ -132,18 +132,18 @@ public class InventoryBehavior extends Behavior { public boolean selectThrowawayForLocation(int x, int y, int z) { IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z); - if (maybe != null && throwaway(true, item -> item instanceof ItemBlock && ((ItemBlock) item).getBlock().equals(maybe.getBlock()))) { + if (maybe != null && throwaway(true, stack -> stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().equals(maybe.getBlock()))) { return true; // gotem } for (Item item : Baritone.settings().acceptableThrowawayItems.value) { - if (throwaway(true, item::equals)) { + if (throwaway(true, stack -> item.equals(stack.getItem()))) { return true; } } return false; } - private boolean throwaway(boolean select, Predicate desired) { + public boolean throwaway(boolean select, Predicate desired) { EntityPlayerSP p = ctx.player(); NonNullList inv = p.inventory.mainInventory; for (byte i = 0; i < 9; i++) { @@ -153,14 +153,14 @@ public class InventoryBehavior extends Behavior { // and then it's called during execution // since this function is never called during cost calculation, we don't need to migrate // acceptableThrowawayItems to the CalculationContext - if (desired.test(item.getItem())) { + if (desired.test(item)) { if (select) { p.inventory.currentItem = i; } return true; } } - if (desired.test(p.inventory.offHandInventory.get(0).getItem())) { + if (desired.test(p.inventory.offHandInventory.get(0))) { // main hand takes precedence over off hand // that means that if we have block A selected in main hand and block B in off hand, right clicking places block B // we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index 43b8b424..ac6d488f 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -40,7 +40,6 @@ import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; -import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; @@ -143,39 +142,18 @@ public class FarmProcess extends BaritoneProcessHelper implements IFarmProcess { return false; } - private boolean selectFarmlandPlantable(boolean doSelect) {//EnumDyeColor.WHITE == EnumDyeColor.byDyeDamage(stack.getMetadata()) - NonNullList invy = ctx.player().inventory.mainInventory; - for (int i = 0; i < 9; i++) { - if (FARMLAND_PLANTABLE.contains(invy.get(i).getItem())) { - if (doSelect) { - ctx.player().inventory.currentItem = i; - } - return true; - } - } - return false; - } - - private boolean selectBoneMeal(boolean doSelect) { - if (isBoneMeal(ctx.player().inventory.offHandInventory.get(0))) { - return true; - } - NonNullList invy = ctx.player().inventory.mainInventory; - for (int i = 0; i < 9; i++) { - if (isBoneMeal(invy.get(i))) { - if (doSelect) { - ctx.player().inventory.currentItem = i; - } - return true; - } - } - return false; + private boolean isPlantable(ItemStack stack) { + return FARMLAND_PLANTABLE.contains(stack.getItem()); } private boolean isBoneMeal(ItemStack stack) { return !stack.isEmpty() && stack.getItem() instanceof ItemDye && EnumDyeColor.byDyeDamage(stack.getMetadata()) == EnumDyeColor.WHITE; } + private boolean isNetherWart(ItemStack stack) { + return !stack.isEmpty() && stack.getItem().equals(Items.NETHER_WART); + } + @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { ArrayList scan = new ArrayList<>(); @@ -183,20 +161,31 @@ public class FarmProcess extends BaritoneProcessHelper implements IFarmProcess { scan.add(harvest.block); } scan.add(Blocks.FARMLAND); + if (Baritone.settings().replantNetherWart.value) { + scan.add(Blocks.SOUL_SAND); + } List locations = WorldScanner.INSTANCE.scanChunkRadius(ctx, scan, 256, 10, 4); List toBreak = new ArrayList<>(); List openFarmland = new ArrayList<>(); List bonemealable = new ArrayList<>(); + List openSoulsand = new ArrayList<>(); for (BlockPos pos : locations) { IBlockState state = ctx.world().getBlockState(pos); + boolean airAbove = ctx.world().getBlockState(pos.up()).getBlock() instanceof BlockAir; if (state.getBlock() == Blocks.FARMLAND) { - if (ctx.world().getBlockState(pos.up()).getBlock() instanceof BlockAir) { + if (airAbove) { openFarmland.add(pos); } continue; } + if (state.getBlock() == Blocks.SOUL_SAND) { + if (airAbove) { + openSoulsand.add(pos); + } + continue; + } if (readyForHarvest(ctx.world(), pos, state)) { toBreak.add(pos); continue; @@ -221,9 +210,12 @@ public class FarmProcess extends BaritoneProcessHelper implements IFarmProcess { return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } } - for (BlockPos pos : openFarmland) { + ArrayList both = new ArrayList<>(openFarmland); + 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()); - if (rot.isPresent() && isSafeToCancel && selectFarmlandPlantable(true)) { + if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, soulsand ? this::isNetherWart : this::isPlantable)) { baritone.getLookBehavior().updateTarget(rot.get(), true); if (ctx.isLookingAt(pos)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); @@ -233,7 +225,7 @@ public class FarmProcess extends BaritoneProcessHelper implements IFarmProcess { } for (BlockPos pos : bonemealable) { Optional rot = RotationUtils.reachable(ctx, pos); - if (rot.isPresent() && isSafeToCancel && selectBoneMeal(true)) { + if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, this::isBoneMeal)) { baritone.getLookBehavior().updateTarget(rot.get(), true); if (ctx.isLookingAt(pos)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); @@ -252,12 +244,17 @@ public class FarmProcess extends BaritoneProcessHelper implements IFarmProcess { for (BlockPos pos : toBreak) { goalz.add(new BuilderProcess.GoalBreak(pos)); } - if (selectFarmlandPlantable(false)) { + if (baritone.getInventoryBehavior().throwaway(false, this::isPlantable)) { for (BlockPos pos : openFarmland) { goalz.add(new GoalBlock(pos.up())); } } - if (selectBoneMeal(false)) { + if (baritone.getInventoryBehavior().throwaway(false, this::isNetherWart)) { + for (BlockPos pos : openSoulsand) { + goalz.add(new GoalBlock(pos.up())); + } + } + if (baritone.getInventoryBehavior().throwaway(false, this::isBoneMeal)) { for (BlockPos pos : bonemealable) { goalz.add(new GoalBlock(pos)); } @@ -266,6 +263,7 @@ public class FarmProcess extends BaritoneProcessHelper implements IFarmProcess { if (entity instanceof EntityItem && entity.onGround) { EntityItem ei = (EntityItem) entity; if (PICKUP_DROPPED.contains(ei.getItem().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 0b8fa3ffe3b49fbf0d16c0c806f1c5af21aa4a38 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 20 Apr 2019 17:10:35 -0500 Subject: [PATCH 354/682] Fix the scuffed usage of LinkedList and ArrayList for list setting types --- src/api/java/baritone/api/Settings.java | 30 +++-- .../java/baritone/api/utils/SettingsUtil.java | 127 ++++++++++++++---- .../java/baritone/api/utils/TypeUtils.java | 44 ++++++ 3 files changed, 168 insertions(+), 33 deletions(-) create mode 100644 src/api/java/baritone/api/utils/TypeUtils.java diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 419ee236..bc95438c 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -18,6 +18,7 @@ package baritone.api; import baritone.api.utils.SettingsUtil; +import baritone.api.utils.TypeUtils; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; @@ -27,6 +28,9 @@ import net.minecraft.util.text.ITextComponent; import java.awt.*; import java.lang.reflect.Field; +import java.lang.reflect.Parameter; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.util.*; import java.util.List; import java.util.function.Consumer; @@ -150,7 +154,7 @@ public final class Settings { /** * Blocks that Baritone will attempt to avoid (Used in avoidance) */ - public final Setting> blocksToAvoid = new Setting<>(new LinkedList<>(Arrays.asList( + public final Setting> blocksToAvoid = new Setting<>(new ArrayList<>(Arrays.asList( // Leave Empty by Default ))); @@ -789,11 +793,12 @@ public final class Settings { */ public final List> allSettings; + public final Map, Type> settingTypes; + public final class Setting { public T value; public final T defaultValue; private String name; - private final Class klass; @SuppressWarnings("unchecked") private Setting(T value) { @@ -802,7 +807,6 @@ public final class Settings { } this.value = value; this.defaultValue = value; - this.klass = (Class) value.getClass(); } /** @@ -820,7 +824,8 @@ public final class Settings { } public Class getValueClass() { - return klass; + // noinspection unchecked + return (Class) TypeUtils.resolveBaseClass(getType()); } @Override @@ -834,14 +839,21 @@ public final class Settings { public void reset() { value = defaultValue; } + + public final Type getType() { + return settingTypes.get(this); + } } // here be dragons Settings() { Field[] temp = getClass().getFields(); - HashMap> tmpByName = new HashMap<>(); - List> tmpAll = new ArrayList<>(); + + Map> tmpByName = new HashMap<>(); + List> tmpAll = new ArrayList<>(); + Map, Type> tmpSettingTypes = new HashMap<>(); + try { for (Field field : temp) { if (field.getType().equals(Setting.class)) { @@ -854,13 +866,15 @@ public final class Settings { } tmpByName.put(name, setting); tmpAll.add(setting); + tmpSettingTypes.put(setting, ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]); } } } catch (IllegalAccessException e) { throw new IllegalStateException(e); } - byLowerName = Collections.unmodifiableMap(tmpByName); - allSettings = Collections.unmodifiableList(tmpAll); + byLowerName = Collections.unmodifiableMap(tmpByName); + allSettings = Collections.unmodifiableList(tmpAll); + settingTypes = Collections.unmodifiableMap(tmpSettingTypes); } @SuppressWarnings("unchecked") diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index f5cb17e1..fc0abb28 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -21,12 +21,13 @@ import baritone.api.Settings; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.util.EnumFacing; -import net.minecraft.util.ResourceLocation; import java.awt.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; @@ -36,7 +37,6 @@ import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; -import java.util.stream.Stream; import static net.minecraft.client.Minecraft.getMinecraft; @@ -45,8 +45,6 @@ public class SettingsUtil { private static final Path SETTINGS_PATH = getMinecraft().gameDir.toPath().resolve("baritone").resolve("settings.txt"); private static final Pattern SETTING_PATTERN = Pattern.compile("^(?[^ ]+) +(?[^ ]+)"); // 2 words separated by spaces - private static final Map, SettingsIO> map; - private static boolean isComment(String line) { return line.startsWith("#") || line.startsWith("//"); } @@ -120,11 +118,11 @@ public class SettingsUtil { if (setting.getName().equals("logger")) { return "logger"; } - SettingsIO io = map.get(setting.getValueClass()); + Parser io = Parser.getParser(setting.getType()); if (io == null) { throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName()); } - return setting.getName() + " " + io.toString.apply(setting.value); + return setting.getName() + " " + io.toString(new ParserContext(setting), setting.value); } public static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException { @@ -133,47 +131,126 @@ public class SettingsUtil { throw new IllegalStateException("No setting by that name"); } Class intendedType = setting.getValueClass(); - SettingsIO ioMethod = map.get(intendedType); - Object parsed = ioMethod.parser.apply(settingValue); + Parser ioMethod = Parser.getParser(setting.getType()); + Object parsed = ioMethod.parse(new ParserContext(setting), settingValue); if (!intendedType.isInstance(parsed)) { throw new IllegalStateException(ioMethod + " parser returned incorrect type, expected " + intendedType + " got " + parsed + " which is " + parsed.getClass()); } setting.value = parsed; } - private enum SettingsIO { + private interface ISettingParser { + + T parse(ParserContext context, String raw); + + String toString(ParserContext context, T value); + + boolean accepts(Type type); + } + + private static class ParserContext { + + private final Settings.Setting setting; + + public ParserContext(Settings.Setting setting) { + this.setting = setting; + } + + final Settings.Setting getSetting() { + return this.setting; + } + } + + private enum Parser implements ISettingParser { + DOUBLE(Double.class, Double::parseDouble), BOOLEAN(Boolean.class, Boolean::parseBoolean), INTEGER(Integer.class, Integer::parseInt), - FLOAT(Float.class, Float::parseFloat), + FLOAT(Float.class,Float::parseFloat), LONG(Long.class, Long::parseLong), + ENUMFACING(EnumFacing.class, EnumFacing::byName), + COLOR( + Color.class, + str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])), + color -> color.getRed() + "," + color.getGreen() + "," + color.getBlue() + ), + BLOCK( + Block.class, + str -> BlockUtils.stringToBlockRequired(str.trim()), + BlockUtils::blockToString + ), + ITEM( + Item.class, + str -> Item.getByNameOrId(str.trim()), + item -> Item.REGISTRY.getNameForObject(item).toString() + ), + LIST() { - BLOCK_LIST(LinkedList.class, str -> Stream.of(str.split(",")).map(String::trim).map(BlockUtils::stringToBlockRequired).collect(Collectors.toCollection(LinkedList::new)), list -> ((LinkedList) list).stream().map(BlockUtils::blockToString).collect(Collectors.joining(","))), - ITEM_LIST(ArrayList.class, str -> Stream.of(str.split(",")).map(String::trim).map(Item::getByNameOrId).collect(Collectors.toCollection(ArrayList::new)), list -> ((ArrayList) list).stream().map(Item.REGISTRY::getNameForObject).map(ResourceLocation::toString).collect(Collectors.joining(","))), - COLOR(Color.class, str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])), color -> color.getRed() + "," + color.getGreen() + "," + color.getBlue()), - ENUMFACING(EnumFacing.class, EnumFacing::byName); + @Override + public Object parse(ParserContext context, String raw) { + Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0]; + Parser parser = Parser.getParser(type); + return Arrays.stream(raw.split(",")) + .map(s -> parser.parse(context, s)) + .collect(Collectors.toList()); + } - Class klass; - Function parser; - Function toString; + @Override + public String toString(ParserContext context, Object value) { + Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0]; + Parser parser = Parser.getParser(type); - SettingsIO(Class klass, Function parser) { + return ((List) value).stream() + .map(o -> parser.toString(context, o)) + .collect(Collectors.joining(",")); + } + + @Override + public boolean accepts(Type type) { + return List.class.isAssignableFrom(TypeUtils.resolveBaseClass(type)); + } + }; + + private final Class klass; + private final Function parser; + private final Function toString; + + Parser() { + this.klass = null; + this.parser = null; + this.toString = null; + } + + Parser(Class klass, Function parser) { this(klass, parser, Object::toString); } - SettingsIO(Class klass, Function parser, Function toString) { + Parser(Class klass, Function parser, Function toString) { this.klass = klass; this.parser = parser::apply; this.toString = x -> toString.apply((T) x); } - } - static { - HashMap, SettingsIO> tempMap = new HashMap<>(); - for (SettingsIO type : SettingsIO.values()) { - tempMap.put(type.klass, type); + @Override + public Object parse(ParserContext context, String raw) { + return this.parser.apply(raw); + } + + @Override + public String toString(ParserContext context, Object value) { + return this.toString.apply(value); + } + + @Override + public boolean accepts(Type type) { + return type instanceof Class && this.klass.isAssignableFrom((Class) type); + } + + public static Parser getParser(Type type) { + return Arrays.stream(values()) + .filter(parser -> parser.accepts(type)) + .findFirst().orElse(null); } - map = Collections.unmodifiableMap(tempMap); } } diff --git a/src/api/java/baritone/api/utils/TypeUtils.java b/src/api/java/baritone/api/utils/TypeUtils.java new file mode 100644 index 00000000..457cc449 --- /dev/null +++ b/src/api/java/baritone/api/utils/TypeUtils.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.utils; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +/** + * @author Brady + * @since 4/20/2019 + */ +public final class TypeUtils { + + private TypeUtils() {} + + /** + * Resolves the "base type" for the specified type. For example, if the specified + * type is {@code List}, then {@code List.class} will be returned. If the + * specified type is already a class, then it is directly returned. + * + * @param type The type to resolve + * @return The base class + */ + public static Class resolveBaseClass(Type type) { + return type instanceof Class ? (Class) type + : type instanceof ParameterizedType ? (Class) ((ParameterizedType) type).getRawType() + : null; + } +} From 1047d4ade903844dc780d997ef10a7985bb4edaf Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 20 Apr 2019 17:26:41 -0500 Subject: [PATCH 355/682] Babbaj doesn't know how to convert imperative shitcode into a regex and leijurv doesn't know how to verify that the regex reflects the original behavior im literally raging --- src/api/java/baritone/api/utils/SettingsUtil.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index fc0abb28..b4436bc2 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -43,7 +43,7 @@ import static net.minecraft.client.Minecraft.getMinecraft; public class SettingsUtil { private static final Path SETTINGS_PATH = getMinecraft().gameDir.toPath().resolve("baritone").resolve("settings.txt"); - private static final Pattern SETTING_PATTERN = Pattern.compile("^(?[^ ]+) +(?[^ ]+)"); // 2 words separated by spaces + private static final Pattern SETTING_PATTERN = Pattern.compile("^(?[^ ]+) +(?.+)"); // key and value split by the first space private static boolean isComment(String line) { return line.startsWith("#") || line.startsWith("//"); @@ -176,12 +176,12 @@ public class SettingsUtil { ), BLOCK( Block.class, - str -> BlockUtils.stringToBlockRequired(str.trim()), + BlockUtils::stringToBlockRequired, BlockUtils::blockToString ), ITEM( Item.class, - str -> Item.getByNameOrId(str.trim()), + Item::getByNameOrId, item -> Item.REGISTRY.getNameForObject(item).toString() ), LIST() { From 5da14fcb3fd44a7dfc95d1794c78b09370d84fbd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 20 Apr 2019 15:35:11 -0700 Subject: [PATCH 356/682] fix --- src/api/java/baritone/api/Settings.java | 11 +++++------ src/api/java/baritone/api/utils/SettingsUtil.java | 12 ++++++------ 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index bc95438c..838bef88 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -28,7 +28,6 @@ import net.minecraft.util.text.ITextComponent; import java.awt.*; import java.lang.reflect.Field; -import java.lang.reflect.Parameter; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.*; @@ -850,9 +849,9 @@ public final class Settings { Settings() { Field[] temp = getClass().getFields(); - Map> tmpByName = new HashMap<>(); - List> tmpAll = new ArrayList<>(); - Map, Type> tmpSettingTypes = new HashMap<>(); + Map> tmpByName = new HashMap<>(); + List> tmpAll = new ArrayList<>(); + Map, Type> tmpSettingTypes = new HashMap<>(); try { for (Field field : temp) { @@ -872,8 +871,8 @@ public final class Settings { } catch (IllegalAccessException e) { throw new IllegalStateException(e); } - byLowerName = Collections.unmodifiableMap(tmpByName); - allSettings = Collections.unmodifiableList(tmpAll); + byLowerName = Collections.unmodifiableMap(tmpByName); + allSettings = Collections.unmodifiableList(tmpAll); settingTypes = Collections.unmodifiableMap(tmpSettingTypes); } diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index b4436bc2..8667f554 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -30,7 +30,8 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; @@ -131,7 +132,7 @@ public class SettingsUtil { throw new IllegalStateException("No setting by that name"); } Class intendedType = setting.getValueClass(); - Parser ioMethod = Parser.getParser(setting.getType()); + ISettingParser ioMethod = Parser.getParser(setting.getType()); Object parsed = ioMethod.parse(new ParserContext(setting), settingValue); if (!intendedType.isInstance(parsed)) { throw new IllegalStateException(ioMethod + " parser returned incorrect type, expected " + intendedType + " got " + parsed + " which is " + parsed.getClass()); @@ -166,7 +167,7 @@ public class SettingsUtil { DOUBLE(Double.class, Double::parseDouble), BOOLEAN(Boolean.class, Boolean::parseBoolean), INTEGER(Integer.class, Integer::parseInt), - FLOAT(Float.class,Float::parseFloat), + FLOAT(Float.class, Float::parseFloat), LONG(Long.class, Long::parseLong), ENUMFACING(EnumFacing.class, EnumFacing::byName), COLOR( @@ -176,16 +177,15 @@ public class SettingsUtil { ), BLOCK( Block.class, - BlockUtils::stringToBlockRequired, + str -> BlockUtils.stringToBlockRequired(str.trim()), BlockUtils::blockToString ), ITEM( Item.class, - Item::getByNameOrId, + str -> Item.getByNameOrId(str.trim()), item -> Item.REGISTRY.getNameForObject(item).toString() ), LIST() { - @Override public Object parse(ParserContext context, String raw) { Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0]; From 794a7612434034d1bd08a6aa28972f22007e89b7 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 21 Apr 2019 17:05:33 -0500 Subject: [PATCH 357/682] Remove redundant Arrays.asList call --- src/api/java/baritone/api/Settings.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 838bef88..4bfd3e1a 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -153,9 +153,9 @@ public final class Settings { /** * Blocks that Baritone will attempt to avoid (Used in avoidance) */ - public final Setting> blocksToAvoid = new Setting<>(new ArrayList<>(Arrays.asList( + public final Setting> blocksToAvoid = new Setting<>(new ArrayList<>( // Leave Empty by Default - ))); + )); /** * Enables some more advanced vine features. They're honestly just gimmicks and won't ever be needed in real From 4eaa6e20c33328ec0e769853f356054ab444a4a3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 22 Apr 2019 09:46:26 -0700 Subject: [PATCH 358/682] thanks for the tip cda --- src/main/java/baritone/process/BackfillProcess.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/process/BackfillProcess.java b/src/main/java/baritone/process/BackfillProcess.java index c3461faa..be16f8b4 100644 --- a/src/main/java/baritone/process/BackfillProcess.java +++ b/src/main/java/baritone/process/BackfillProcess.java @@ -119,9 +119,11 @@ public class BackfillProcess extends BaritoneProcessHelper { @Override public void onLostControl() { - blocksToReplace.clear(); + if (blocksToReplace != null && !blocksToReplace.isEmpty()) { + blocksToReplace.clear(); + } } - + @Override public String displayName0() { return "Backfill"; From 4bec49de5bd0c99d094b24dd9c7450c5b4332ddd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 22 Apr 2019 14:34:31 -0700 Subject: [PATCH 359/682] filter explored chunks with json --- scripts/proguard.pro | 2 + .../baritone/api/process/IExploreProcess.java | 4 + .../api/utils/ExampleBaritoneControl.java | 18 ++ .../java/baritone/api/utils/MyChunkPos.java | 31 ++++ .../baritone/process/BackfillProcess.java | 2 +- .../java/baritone/process/ExploreProcess.java | 175 +++++++++++++++--- 6 files changed, 210 insertions(+), 22 deletions(-) create mode 100644 src/api/java/baritone/api/utils/MyChunkPos.java diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 4bed6b5d..bb8df2ae 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -21,6 +21,8 @@ -keep class baritone.BaritoneProvider -keep class baritone.api.IBaritoneProvider +-keep class baritone.api.utils.MyChunkPos { *; } # even in standalone we need to keep this for gson reflect + # setting names are reflected from field names, so keep field names -keepclassmembers class baritone.api.Settings { public ; diff --git a/src/api/java/baritone/api/process/IExploreProcess.java b/src/api/java/baritone/api/process/IExploreProcess.java index bf30fa22..811a509f 100644 --- a/src/api/java/baritone/api/process/IExploreProcess.java +++ b/src/api/java/baritone/api/process/IExploreProcess.java @@ -17,6 +17,10 @@ package baritone.api.process; +import java.nio.file.Path; + public interface IExploreProcess extends IBaritoneProcess { void explore(int centerX, int centerZ); + + void applyJsonFilter(Path path, boolean invert) throws Exception; } diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index f758d15e..34761a0b 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -39,6 +39,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.Chunk; +import java.nio.file.Path; import java.util.*; public class ExampleBaritoneControl implements Helper, AbstractGameEventListener { @@ -429,6 +430,23 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener logDirect("Following " + toFollow.get()); return true; } + if (msg.startsWith("explorefilter")) { + // explorefilter blah.json + // means that entries in blah.json are already explored + // explorefilter blah.json invert + // means that entries in blah.json are NOT already explored + String path = msg.substring("explorefilter".length()).trim(); + String[] parts = path.split(" "); + Path path1 = Minecraft.getMinecraft().gameDir.toPath().resolve(parts[0]); + try { + baritone.getExploreProcess().applyJsonFilter(path1, parts.length > 1); + logDirect("Loaded filter"); + } catch (Exception e) { + e.printStackTrace(); + logDirect("Unable to load " + path1); + } + return true; + } if (msg.equals("reloadall")) { baritone.getWorldProvider().getCurrentWorld().getCachedWorld().reloadAllFromDisk(); logDirect("ok"); diff --git a/src/api/java/baritone/api/utils/MyChunkPos.java b/src/api/java/baritone/api/utils/MyChunkPos.java new file mode 100644 index 00000000..5748a13d --- /dev/null +++ b/src/api/java/baritone/api/utils/MyChunkPos.java @@ -0,0 +1,31 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils; + +/** + * Need a non obfed chunkpos that we can load using GSON + */ +public class MyChunkPos { + public int x; + public int z; + + @Override + public String toString() { + return x + ", " + z; + } +} \ No newline at end of file diff --git a/src/main/java/baritone/process/BackfillProcess.java b/src/main/java/baritone/process/BackfillProcess.java index be16f8b4..8567a049 100644 --- a/src/main/java/baritone/process/BackfillProcess.java +++ b/src/main/java/baritone/process/BackfillProcess.java @@ -123,7 +123,7 @@ public class BackfillProcess extends BaritoneProcessHelper { blocksToReplace.clear(); } } - + @Override public String displayName0() { return "Backfill"; diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index b848b679..6818e45b 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -25,10 +25,18 @@ import baritone.api.pathing.goals.GoalXZ; import baritone.api.process.IExploreProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; +import baritone.api.utils.MyChunkPos; import baritone.cache.CachedWorld; import baritone.utils.BaritoneProcessHelper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -36,6 +44,8 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro private BlockPos explorationOrigin; + private IChunkFilter filter; + public ExploreProcess(Baritone baritone) { super(baritone); } @@ -50,6 +60,21 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro explorationOrigin = new BlockPos(centerX, 0, centerZ); } + @Override + public void applyJsonFilter(Path path, boolean invert) throws Exception { + filter = new JsonChunkFilter(path, invert); + } + + public IChunkFilter calcFilter() { + IChunkFilter filter; + if (this.filter != null) { + filter = new EitherChunk(this.filter, new BaritoneChunkCache()); + } else { + filter = new BaritoneChunkCache(); + } + return filter; + } + @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (calcFailed) { @@ -57,7 +82,13 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro onLostControl(); return null; } - Goal[] closestUncached = closestUncachedChunks(explorationOrigin); + IChunkFilter filter = calcFilter(); + if (filter.finished()) { + logDirect("Explored all chunks"); + onLostControl(); + return null; + } + Goal[] closestUncached = closestUncachedChunks(explorationOrigin, filter); if (closestUncached == null) { logDebug("awaiting region load from disk"); return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); @@ -65,10 +96,9 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro return new PathingCommand(new GoalComposite(closestUncached), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH); } - private Goal[] closestUncachedChunks(BlockPos center) { + private Goal[] closestUncachedChunks(BlockPos center, IChunkFilter filter) { int chunkX = center.getX() >> 4; int chunkZ = center.getZ() >> 4; - ICachedWorld cache = baritone.getWorldProvider().getCurrentWorld().getCachedWorld(); for (int dist = 0; ; dist++) { List centers = new ArrayList<>(); for (int dx = -dist; dx <= dist; dx++) { @@ -77,32 +107,28 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro if (trueDist != dist) { continue; // not considering this one just yet in our expanding search } + switch (filter.isAlreadyExplored(chunkX + dx, chunkZ + dz)) { + case UNKNOWN: + return null; // awaiting load + case NOT_EXPLORED: + break; // note: this breaks the switch not the for + case EXPLORED: + continue; // note: this continues the for + } int centerX = (chunkX + dx) * 16 + 8; int centerZ = (chunkZ + dz) * 18 + 8; - - if (cache.isCached(centerX, centerZ)) { - continue; - } - if (!((CachedWorld) cache).regionLoaded(centerX, centerZ)) { - Baritone.getExecutor().execute(() -> { - ((CachedWorld) cache).tryLoadFromDisk(centerX >> 9, centerZ >> 9); - }); - return null; // we still need to load regions from disk in order to decide properly - } - int offsetCenterX = centerX; - int offsetCenterZ = centerZ; int offset = 16 * Baritone.settings().worldExploringChunkOffset.value; if (dx < 0) { - offsetCenterX -= offset; + centerX -= offset; } else { - offsetCenterX += offset; + centerX += offset; } if (dz < 0) { - offsetCenterZ -= offset; + centerZ -= offset; } else { - offsetCenterZ += offset; + centerZ += offset; } - centers.add(new BlockPos(offsetCenterX, 0, offsetCenterZ)); + centers.add(new BlockPos(centerX, 0, centerZ)); } } if (centers.size() > Baritone.settings().exploreChunkSetMinimumSize.value) { @@ -111,6 +137,113 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro } } + private enum Status { + EXPLORED, NOT_EXPLORED, UNKNOWN; + } + + private interface IChunkFilter { + Status isAlreadyExplored(int chunkX, int chunkZ); + + boolean finished(); + } + + private class BaritoneChunkCache implements IChunkFilter { + + private final ICachedWorld cache = baritone.getWorldProvider().getCurrentWorld().getCachedWorld(); + + @Override + public Status isAlreadyExplored(int chunkX, int chunkZ) { + int centerX = chunkX << 4; + int centerZ = chunkZ << 4; + if (cache.isCached(centerX, centerZ)) { + return Status.EXPLORED; + } + if (!((CachedWorld) cache).regionLoaded(centerX, centerZ)) { + Baritone.getExecutor().execute(() -> { + ((CachedWorld) cache).tryLoadFromDisk(centerX >> 9, centerZ >> 9); + }); + return Status.UNKNOWN; // we still need to load regions from disk in order to decide properly + } + return Status.NOT_EXPLORED; + } + + @Override + public boolean finished() { + return false; + } + } + + private class JsonChunkFilter implements IChunkFilter { + private final boolean invert; // if true, the list is interpreted as a list of chunks that are NOT explored, if false, the list is interpreted as a list of chunks that ARE explored + private final LongOpenHashSet inFilter; + private final MyChunkPos[] positions; + + private JsonChunkFilter(Path path, boolean invert) throws Exception { // ioexception, json exception, etc + this.invert = invert; + Gson gson = new GsonBuilder().create(); + positions = gson.fromJson(new InputStreamReader(Files.newInputStream(path)), MyChunkPos[].class); + logDirect("Loaded " + positions.length + " positions"); + inFilter = new LongOpenHashSet(); + for (MyChunkPos mcp : positions) { + inFilter.add(ChunkPos.asLong(mcp.x, mcp.z)); + } + } + + @Override + public Status isAlreadyExplored(int chunkX, int chunkZ) { + if (inFilter.contains(ChunkPos.asLong(chunkX, chunkZ)) ^ invert) { + // either it's on the list of explored chunks, or it's not on the list of unexplored chunks + // either way, we have it + return Status.EXPLORED; + } else { + // either it's not on the list of explored chunks, or it's on the list of unexplored chunks + // either way, it depends on if baritone has cached it so defer to that + return Status.UNKNOWN; + } + } + + @Override + public boolean finished() { + if (!invert) { + // if invert is false, anything not on the list is uncached + return false; + } + // but if invert is true, anything not on the list IS assumed cached + // so we are done if everything on our list is cached! + BaritoneChunkCache bcc = new BaritoneChunkCache(); + for (MyChunkPos pos : positions) { + if (bcc.isAlreadyExplored(pos.x, pos.z) != Status.EXPLORED) { + // either waiting for it or dont have it at all + return false; + } + } + return true; // we have everything cached + } + } + + private class EitherChunk implements IChunkFilter { + private final IChunkFilter a; + private final IChunkFilter b; + + private EitherChunk(IChunkFilter a, IChunkFilter b) { + this.a = a; + this.b = b; + } + + @Override + public Status isAlreadyExplored(int chunkX, int chunkZ) { + if (a.isAlreadyExplored(chunkX, chunkZ) == Status.EXPLORED) { + return Status.EXPLORED; + } + return b.isAlreadyExplored(chunkX, chunkZ); + } + + @Override + public boolean finished() { + return a.finished() || b.finished(); + } + } + @Override public void onLostControl() { explorationOrigin = null; @@ -118,6 +251,6 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro @Override public String displayName0() { - return "Exploring around " + explorationOrigin + ", currently going to " + new GoalComposite(closestUncachedChunks(explorationOrigin)); + return "Exploring around " + explorationOrigin + ", currently going to " + new GoalComposite(closestUncachedChunks(explorationOrigin, calcFilter())); } } From 2fac594315b3b4fc417d9b9dfcfaf743d8a6fe22 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 22 Apr 2019 14:36:12 -0700 Subject: [PATCH 360/682] say if its inverted --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 34761a0b..7985abde 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -438,9 +438,10 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener String path = msg.substring("explorefilter".length()).trim(); String[] parts = path.split(" "); Path path1 = Minecraft.getMinecraft().gameDir.toPath().resolve(parts[0]); + boolean invert = parts.length > 1; try { - baritone.getExploreProcess().applyJsonFilter(path1, parts.length > 1); - logDirect("Loaded filter"); + baritone.getExploreProcess().applyJsonFilter(path1, invert); + logDirect("Loaded filter. Inverted: " + invert); } catch (Exception e) { e.printStackTrace(); logDirect("Unable to load " + path1); From 714c6773c3957b0a813c57645827f4f18077f512 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 22 Apr 2019 14:51:07 -0700 Subject: [PATCH 361/682] explain what invert means --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 7985abde..715d8edb 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -442,6 +442,11 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener try { baritone.getExploreProcess().applyJsonFilter(path1, invert); logDirect("Loaded filter. Inverted: " + invert); + if (invert) { + logDirect("Chunks on this list will be treated as possibly unexplored, all others will be treated as certainly explored"); + } else { + logDirect("Chunks on this list will be treated as certainly explored, all others will be treated as possibly unexplored"); + } } catch (Exception e) { e.printStackTrace(); logDirect("Unable to load " + path1); From e8b4f4d2b6938753b3bcb53b1b070d40135db74f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 22 Apr 2019 15:33:40 -0700 Subject: [PATCH 362/682] make the completion check a setting --- src/api/java/baritone/api/Settings.java | 6 ++++++ src/main/java/baritone/process/ExploreProcess.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 f67ebcf6..5d672047 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -717,6 +717,12 @@ public final class Settings { */ public final Setting exploreUsePythagorean = new Setting<>(false); + /** + * Turn this on if your exploration filter is enormous, you don't want it to check if it's done, + * and you are just fine with it just hanging on completion + */ + public final Setting disableCompletionCheck = new Setting<>(false); + /** * Cached chunks (regardless of if they're in RAM or saved to disk) expire and are deleted after this number of seconds * -1 to disable diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 6818e45b..4abb2629 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -83,7 +83,7 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro return null; } IChunkFilter filter = calcFilter(); - if (filter.finished()) { + if (!Baritone.settings().disableCompletionCheck.value && filter.finished()) { logDirect("Explored all chunks"); onLostControl(); return null; From 83265fcb542beb0550031c1e77e86db33252be74 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 22 Apr 2019 19:52:04 -0700 Subject: [PATCH 363/682] add blocks to avoid breaking, fixes #368 --- src/api/java/baritone/api/Settings.java | 7 +++++++ .../java/baritone/pathing/movement/MovementHelper.java | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 5d672047..9306e9b0 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -157,6 +157,13 @@ public final class Settings { // Leave Empty by Default )); + /** + * Blocks that Baritone is not allowed to break + */ + public final Setting> blocksToAvoidBreaking = new Setting<>(new ArrayList<>( + // e.g. crafting table, beds + )); + /** * Enables some more advanced vine features. They're honestly just gimmicks and won't ever be needed in real * pathing scenarios. And they can cause Baritone to get trapped indefinitely in a strange scenario. diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 322b9ac6..c0683d47 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -55,7 +55,8 @@ public interface MovementHelper extends ActionCosts, Helper { || bsi.get0(x + 1, y, z).getBlock() instanceof BlockLiquid || bsi.get0(x - 1, y, z).getBlock() instanceof BlockLiquid || bsi.get0(x, y, z + 1).getBlock() instanceof BlockLiquid - || bsi.get0(x, y, z - 1).getBlock() instanceof BlockLiquid; + || bsi.get0(x, y, z - 1).getBlock() instanceof BlockLiquid + || Baritone.settings().blocksToAvoidBreaking.value.contains(b); } static boolean canWalkThrough(IPlayerContext ctx, BetterBlockPos pos) { From 2ee119fc64f6fec5df57895928de264972c50977 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 22 Apr 2019 20:41:27 -0700 Subject: [PATCH 364/682] v1.2.6 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 739e3d35..27b0d7a3 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.2.5' +version '1.2.6' buildscript { repositories { From 09fbf675ec3e28f82ef22dde1819cd974102bc1c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 23 Apr 2019 17:42:13 -0700 Subject: [PATCH 365/682] fix build repeat --- 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 299862cc..6185b300 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -338,6 +338,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro layer = 0; origin = new BlockPos(origin).offset(direction, distance); logDirect("Repeating build " + distance + " blocks to the " + direction + ", new origin is " + origin); + return onTick(calcFailed, isSafeToCancel); } trim(bcc); From bc419cfd1a5272ab2934b1932cbe53f03c37484b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 24 Apr 2019 22:10:41 -0800 Subject: [PATCH 366/682] fix loophole with falling blocks above ore --- src/main/java/baritone/process/MineProcess.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index a1a69526..47f70617 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -47,6 +47,8 @@ import net.minecraft.world.World; import java.util.*; import java.util.stream.Collectors; +import static baritone.api.pathing.movement.ActionCosts.COST_INF; + /** * Mine blocks of a certain type * @@ -334,7 +336,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro List dropped = droppedItemsScan(mining, ctx.world); dropped.removeIf(drop -> { for (BlockPos pos : locs2) { - if (pos.distanceSq(drop) <= 9 && mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) && MineProcess.plausibleToBreak(ctx.bsi, pos)) { // TODO maybe drop also has to be supported? no lava below? + if (pos.distanceSq(drop) <= 9 && mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) && MineProcess.plausibleToBreak(ctx, pos)) { // TODO maybe drop also has to be supported? no lava below? return true; } } @@ -348,7 +350,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro .filter(pos -> !ctx.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ()) || mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos)) // remove any that are implausible to mine (encased in bedrock, or touching lava) - .filter(pos -> MineProcess.plausibleToBreak(ctx.bsi, pos)) + .filter(pos -> MineProcess.plausibleToBreak(ctx, pos)) .filter(pos -> !blacklist.contains(pos)) @@ -361,13 +363,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return locs; } - public static boolean plausibleToBreak(BlockStateInterface bsi, BlockPos pos) { - if (MovementHelper.avoidBreaking(bsi, pos.getX(), pos.getY(), pos.getZ(), bsi.get0(pos))) { + public static boolean plausibleToBreak(CalculationContext ctx, BlockPos pos) { + if (MovementHelper.getMiningDurationTicks(ctx, pos.getX(), pos.getY(), pos.getZ(), ctx.bsi.get0(pos), true) >= COST_INF) { return false; } // bedrock above and below makes it implausible, otherwise we're good - return !(bsi.get0(pos.up()).getBlock() == Blocks.BEDROCK && bsi.get0(pos.down()).getBlock() == Blocks.BEDROCK); + return !(ctx.bsi.get0(pos.up()).getBlock() == Blocks.BEDROCK && ctx.bsi.get0(pos.down()).getBlock() == Blocks.BEDROCK); } @Override From 79c433b14da868613c3a22ff78d6c9641250b9f4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 25 Apr 2019 10:49:54 -0700 Subject: [PATCH 367/682] reduce suffocation from falling blocks above ore --- .../java/baritone/process/MineProcess.java | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 47f70617..6051fe4a 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -35,6 +35,7 @@ import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; import net.minecraft.block.Block; import net.minecraft.block.BlockAir; +import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; @@ -155,7 +156,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (!locs.isEmpty()) { List locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT, blacklist); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final - Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(ctx, loc, locs2)).toArray(Goal[]::new)); + Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new)); knownOreLocations = locs2; return new PathingCommand(goal, legit ? PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH : PathingCommandType.REVALIDATE_GOAL_AND_PATH); } @@ -210,18 +211,26 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return locs.contains(pos) || (Baritone.settings().internalMiningAirException.value && BlockStateInterface.getBlock(ctx, pos) instanceof BlockAir); } - private static Goal coalesce(IPlayerContext ctx, BlockPos loc, List locs) { + private Goal coalesce(BlockPos loc, List locs) { + boolean assumeVerticalShaftMine = !(baritone.bsi.get0(loc.up()).getBlock() instanceof BlockFalling); if (!Baritone.settings().forceInternalMining.value) { - return new GoalThreeBlocks(loc); + if (assumeVerticalShaftMine) { + // we can get directly below the block + return new GoalThreeBlocks(loc); + } else { + // we need to get feet or head into the block + return new GoalTwoBlocks(loc); + } } boolean upwardGoal = internalMiningGoal(loc.up(), ctx, locs); boolean downwardGoal = internalMiningGoal(loc.down(), ctx, locs); boolean doubleDownwardGoal = internalMiningGoal(loc.down(2), ctx, locs); if (upwardGoal == downwardGoal) { // symmetric - if (doubleDownwardGoal) { + if (doubleDownwardGoal && assumeVerticalShaftMine) { // we have a checkerboard like pattern // this one, and the one two below it // therefore it's fine to path to immediately below this one, since your feet will be in the doubleDownwardGoal + // but only if assumeVerticalShaftMine return new GoalThreeBlocks(loc); } else { // this block has nothing interesting two below, but is symmetric vertically so we can get either feet or head into it @@ -234,7 +243,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return new GoalBlock(loc); } // upwardGoal known to be false, downwardGoal known to be true - if (doubleDownwardGoal) { + if (doubleDownwardGoal && assumeVerticalShaftMine) { // this block and two below it are goals // path into the center of the one below, because that includes directly below this one return new GoalTwoBlocks(loc.down()); From 30469e2de26bb4ec9d2dc921f7889fe0bb63db7d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 25 Apr 2019 11:10:18 -0700 Subject: [PATCH 368/682] pause mining for falling blocks, fixes #157 --- src/api/java/baritone/api/Settings.java | 5 +++++ src/main/java/baritone/pathing/movement/Movement.java | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 9306e9b0..a4d35283 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -204,6 +204,11 @@ public final class Settings { */ public final Setting sprintAscends = new Setting<>(true); + /** + * When breaking blocks for a movement, wait until all falling blocks have settled before continuing + */ + public final Setting pauseMiningForFallingBlocks = new Setting<>(true); + /** * How many ticks between right clicks are allowed. Default in game is 4 */ diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 8c0ba2f8..4bdd4f95 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -17,6 +17,7 @@ package baritone.pathing.movement; +import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; @@ -24,7 +25,9 @@ import baritone.api.utils.*; import baritone.api.utils.input.Input; import baritone.utils.BlockStateInterface; import net.minecraft.block.BlockLiquid; +import net.minecraft.entity.item.EntityFallingBlock; import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import java.util.ArrayList; @@ -140,6 +143,9 @@ public abstract class Movement implements IMovement, MovementHelper { } boolean somethingInTheWay = false; for (BetterBlockPos blockPos : positionsToBreak) { + if (!ctx.world().getEntitiesWithinAABB(EntityFallingBlock.class, new AxisAlignedBB(0, 0, 0, 1, 1.1, 1).offset(blockPos)).isEmpty() && Baritone.settings().pauseMiningForFallingBlocks.value) { + return false; + } if (!MovementHelper.canWalkThrough(ctx, blockPos) && !(BlockStateInterface.getBlock(ctx, blockPos) instanceof BlockLiquid)) { // can't break liquid, so don't try somethingInTheWay = true; Optional reachable = RotationUtils.reachable(ctx.player(), blockPos, ctx.playerController().getBlockReachDistance()); From 36858ca219ceafb45b14f6b95e65e0def80194d6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 25 Apr 2019 11:22:11 -0700 Subject: [PATCH 369/682] small cleanup --- src/api/java/baritone/api/utils/RotationUtils.java | 2 +- src/main/java/baritone/pathing/movement/Movement.java | 2 +- .../baritone/pathing/movement/movements/MovementTraverse.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index 3010d283..e19f531d 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -154,7 +154,7 @@ public final class RotationUtils { */ public static Optional reachable(EntityPlayerSP entity, BlockPos pos, double blockReachDistance) { IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(entity); - if (pos.equals(baritone.getPlayerContext().getSelectedBlock().orElse(null))) { + if (baritone.getPlayerContext().isLookingAt(pos)) { /* * why add 0.0001? * to indicate that we actually have a desired pitch diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 4bdd4f95..c9849cab 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -153,7 +153,7 @@ public abstract class Movement implements IMovement, MovementHelper { Rotation rotTowardsBlock = reachable.get(); MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, blockPos)); state.setTarget(new MovementState.MovementTarget(rotTowardsBlock, true)); - if (Objects.equals(ctx.getSelectedBlock().orElse(null), blockPos) || ctx.playerRotations().isReallyCloseTo(rotTowardsBlock)) { + if (ctx.isLookingAt(blockPos) || ctx.playerRotations().isReallyCloseTo(rotTowardsBlock)) { state.setInput(Input.CLICK_LEFT, true); } return false; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 881571bc..4f7ae713 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -313,7 +313,7 @@ public class MovementTraverse extends Movement { } else { state.setTarget(new MovementState.MovementTarget(backToFace, true)); } - if (Objects.equals(ctx.getSelectedBlock().orElse(null), goalLook)) { + if (ctx.isLookingAt(goalLook)) { return state.setInput(Input.CLICK_RIGHT, true); // wait to right click until we are able to place } // Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt()); From 9127ba2fcebcf05ba5685353a3339a2232dd5478 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 25 Apr 2019 12:18:25 -0700 Subject: [PATCH 370/682] make explore a little less dummy --- .../java/baritone/process/ExploreProcess.java | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 4abb2629..c8f0c18c 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -83,7 +83,7 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro return null; } IChunkFilter filter = calcFilter(); - if (!Baritone.settings().disableCompletionCheck.value && filter.finished()) { + if (!Baritone.settings().disableCompletionCheck.value && filter.countRemain() == 0) { logDirect("Explored all chunks"); onLostControl(); return null; @@ -99,6 +99,7 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro private Goal[] closestUncachedChunks(BlockPos center, IChunkFilter filter) { int chunkX = center.getX() >> 4; int chunkZ = center.getZ() >> 4; + int count = Math.min(filter.countRemain(), Baritone.settings().exploreChunkSetMinimumSize.value); for (int dist = 0; ; dist++) { List centers = new ArrayList<>(); for (int dx = -dist; dx <= dist; dx++) { @@ -131,7 +132,7 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro centers.add(new BlockPos(centerX, 0, centerZ)); } } - if (centers.size() > Baritone.settings().exploreChunkSetMinimumSize.value) { + if (centers.size() >= count) { return centers.stream().map(pos -> new GoalXZ(pos.getX(), pos.getZ())).toArray(Goal[]::new); } } @@ -144,7 +145,7 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro private interface IChunkFilter { Status isAlreadyExplored(int chunkX, int chunkZ); - boolean finished(); + int countRemain(); } private class BaritoneChunkCache implements IChunkFilter { @@ -168,8 +169,8 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro } @Override - public boolean finished() { - return false; + public int countRemain() { + return Integer.MAX_VALUE; } } @@ -203,21 +204,25 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro } @Override - public boolean finished() { + public int countRemain() { if (!invert) { // if invert is false, anything not on the list is uncached - return false; + return Integer.MAX_VALUE; } // but if invert is true, anything not on the list IS assumed cached // so we are done if everything on our list is cached! + int countRemain = 0; BaritoneChunkCache bcc = new BaritoneChunkCache(); for (MyChunkPos pos : positions) { if (bcc.isAlreadyExplored(pos.x, pos.z) != Status.EXPLORED) { // either waiting for it or dont have it at all - return false; + countRemain++; + if (countRemain >= Baritone.settings().exploreChunkSetMinimumSize.value) { + return countRemain; + } } } - return true; // we have everything cached + return countRemain; } } @@ -239,8 +244,8 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro } @Override - public boolean finished() { - return a.finished() || b.finished(); + public int countRemain() { + return Math.min(a.countRemain(), b.countRemain()); } } From c8419dc362f3675de778bc7a26648cabc52606d0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 25 Apr 2019 12:45:53 -0700 Subject: [PATCH 371/682] i am rarted --- src/main/java/baritone/process/ExploreProcess.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index c8f0c18c..cfcd6336 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -116,9 +116,9 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro case EXPLORED: continue; // note: this continues the for } - int centerX = (chunkX + dx) * 16 + 8; - int centerZ = (chunkZ + dz) * 18 + 8; - int offset = 16 * Baritone.settings().worldExploringChunkOffset.value; + int centerX = ((chunkX + dx) << 4) + 8; + int centerZ = ((chunkZ + dz) << 4) + 8; + int offset = Baritone.settings().worldExploringChunkOffset.value << 4; if (dx < 0) { centerX -= offset; } else { From 5a0ccac0a1ab5e6d87d5b4a80a75c602d6852d66 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 25 Apr 2019 13:40:33 -0700 Subject: [PATCH 372/682] maintain y while exploring --- src/api/java/baritone/api/Settings.java | 7 +++++++ .../java/baritone/process/ExploreProcess.java | 17 ++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index a4d35283..faf5413d 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -610,6 +610,13 @@ public final class Settings { */ public final Setting exploreChunkSetMinimumSize = new Setting<>(10); + /** + * Attempt to maintain Y coordinate while exploring + *

+ * -1 to disable + */ + public final Setting exploreMaintainY = new Setting<>(64); + /** * Replant nether wart */ diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index cfcd6336..d3625f21 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -22,6 +22,7 @@ import baritone.api.cache.ICachedWorld; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalXZ; +import baritone.api.pathing.goals.GoalYLevel; import baritone.api.process.IExploreProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; @@ -133,11 +134,25 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro } } if (centers.size() >= count) { - return centers.stream().map(pos -> new GoalXZ(pos.getX(), pos.getZ())).toArray(Goal[]::new); + return centers.stream().map(pos -> createGoal(pos.getX(), pos.getZ())).toArray(Goal[]::new); } } } + private static Goal createGoal(int x, int z) { + if (Baritone.settings().exploreMaintainY.value == -1) { + return new GoalXZ(x, z); + } + // don't use a goalblock because we still want isInGoal to return true if X and Z are correct + // we just want to try and maintain Y on the way there, not necessarily end at that specific Y + return new GoalXZ(x, z) { + @Override + public double heuristic(int x, int y, int z) { + return super.heuristic(x, y, z) + GoalYLevel.calculate(Baritone.settings().exploreMaintainY.value, y); + } + }; + } + private enum Status { EXPLORED, NOT_EXPLORED, UNKNOWN; } From 9118e0b36836dfec328fac31d55e4828fb73b5e0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 26 Apr 2019 23:17:18 -0700 Subject: [PATCH 373/682] one byte savings means faster load times --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e016fa94..93b11474 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ Here are some links to help to get started: - [Installation & setup](SETUP.md) -- [API Javadocs](https://baritone.leijurv.com/) +- [API Javadocs](https://baritone.leijurv.com) - [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#field.detail) From b1ee23ad501a6d9b166697a27e1f2040531d0a8f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 27 Apr 2019 16:01:58 -0700 Subject: [PATCH 374/682] taxicab only --- src/api/java/baritone/api/Settings.java | 7 ------- src/main/java/baritone/process/ExploreProcess.java | 2 +- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index faf5413d..afd6a0db 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -729,13 +729,6 @@ public final class Settings { */ public final Setting followRadius = new Setting<>(3); - /** - * true = exploration uses pythagorean distance to choose closest uncached chunk - *

- * false = exploration uses manhattan / taxicab distance to choose - */ - public final Setting exploreUsePythagorean = new Setting<>(false); - /** * Turn this on if your exploration filter is enormous, you don't want it to check if it's done, * and you are just fine with it just hanging on completion diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index d3625f21..4c366502 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -105,7 +105,7 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro List centers = new ArrayList<>(); for (int dx = -dist; dx <= dist; dx++) { for (int dz = -dist; dz <= dist; dz++) { - int trueDist = Baritone.settings().exploreUsePythagorean.value ? dx * dx + dz * dz : Math.abs(dx) + Math.abs(dz); + int trueDist = Math.abs(dx) + Math.abs(dz); if (trueDist != dist) { continue; // not considering this one just yet in our expanding search } From 783a7cedc34ddec5e65f9f89749c699f5c296248 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 27 Apr 2019 16:03:58 -0700 Subject: [PATCH 375/682] can combine distances --- src/main/java/baritone/process/ExploreProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 4c366502..3d7ede29 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -101,8 +101,8 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro int chunkX = center.getX() >> 4; int chunkZ = center.getZ() >> 4; int count = Math.min(filter.countRemain(), Baritone.settings().exploreChunkSetMinimumSize.value); + List centers = new ArrayList<>(); for (int dist = 0; ; dist++) { - List centers = new ArrayList<>(); for (int dx = -dist; dx <= dist; dx++) { for (int dz = -dist; dz <= dist; dz++) { int trueDist = Math.abs(dx) + Math.abs(dz); From 0927e0e017587cd2522fc0f18b14daa075053da3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 27 Apr 2019 16:16:36 -0700 Subject: [PATCH 376/682] fix performance issues with explore --- .../java/baritone/process/ExploreProcess.java | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 3d7ede29..35ddcb84 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -47,6 +47,8 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro private IChunkFilter filter; + private int distanceCompleted; + public ExploreProcess(Baritone baritone) { super(baritone); } @@ -59,6 +61,7 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro @Override public void explore(int centerX, int centerZ) { explorationOrigin = new BlockPos(centerX, 0, centerZ); + distanceCompleted = 0; } @Override @@ -102,12 +105,15 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro int chunkZ = center.getZ() >> 4; int count = Math.min(filter.countRemain(), Baritone.settings().exploreChunkSetMinimumSize.value); List centers = new ArrayList<>(); - for (int dist = 0; ; dist++) { + int renderDistance = Baritone.settings().worldExploringChunkOffset.value; + for (int dist = distanceCompleted; ; dist++) { for (int dx = -dist; dx <= dist; dx++) { - for (int dz = -dist; dz <= dist; dz++) { + int zval = dist - Math.abs(dx); + for (int mult = 0; mult < 2; mult++) { + int dz = (mult * 2 - 1) * zval; // dz can be either -zval or zval int trueDist = Math.abs(dx) + Math.abs(dz); if (trueDist != dist) { - continue; // not considering this one just yet in our expanding search + throw new IllegalStateException(); } switch (filter.isAlreadyExplored(chunkX + dx, chunkZ + dz)) { case UNKNOWN: @@ -119,7 +125,7 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro } int centerX = ((chunkX + dx) << 4) + 8; int centerZ = ((chunkZ + dz) << 4) + 8; - int offset = Baritone.settings().worldExploringChunkOffset.value << 4; + int offset = renderDistance << 4; if (dx < 0) { centerX -= offset; } else { @@ -136,6 +142,11 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro if (centers.size() >= count) { return centers.stream().map(pos -> createGoal(pos.getX(), pos.getZ())).toArray(Goal[]::new); } + if (centers.isEmpty()) { + // we have explored everything from 0 to dist inclusive + // next time we should start our check at dist+1 + distanceCompleted = dist + 1; + } } } @@ -271,6 +282,6 @@ public class ExploreProcess extends BaritoneProcessHelper implements IExplorePro @Override public String displayName0() { - return "Exploring around " + explorationOrigin + ", currently going to " + new GoalComposite(closestUncachedChunks(explorationOrigin, calcFilter())); + return "Exploring around " + explorationOrigin + ", distance completed " + distanceCompleted + ", currently going to " + new GoalComposite(closestUncachedChunks(explorationOrigin, calcFilter())); } } From 0f61aaafb82277aa731e8f547d811acbedcf4b84 Mon Sep 17 00:00:00 2001 From: Babbaj Date: Sun, 28 Apr 2019 21:27:11 -0400 Subject: [PATCH 377/682] use ImmutableSet --- src/main/java/baritone/cache/CachedChunk.java | 109 +++++++++--------- 1 file changed, 53 insertions(+), 56 deletions(-) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 631b7150..249daa5b 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -19,6 +19,7 @@ package baritone.cache; import baritone.api.utils.BlockUtils; import baritone.utils.pathing.PathingBlockType; +import com.google.common.collect.ImmutableSet; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -33,64 +34,60 @@ import java.util.*; */ public final class CachedChunk { - public static final Set BLOCKS_TO_KEEP_TRACK_OF; + public static final ImmutableSet BLOCKS_TO_KEEP_TRACK_OF = ImmutableSet.of( + Blocks.DIAMOND_BLOCK, + //Blocks.COAL_ORE, + Blocks.COAL_BLOCK, + //Blocks.IRON_ORE, + Blocks.IRON_BLOCK, + //Blocks.GOLD_ORE, + Blocks.GOLD_BLOCK, + Blocks.EMERALD_ORE, + Blocks.EMERALD_BLOCK, - static { - HashSet temp = new HashSet<>(); - //temp.add(Blocks.DIAMOND_ORE); - temp.add(Blocks.DIAMOND_BLOCK); - //temp.add(Blocks.COAL_ORE); - temp.add(Blocks.COAL_BLOCK); - //temp.add(Blocks.IRON_ORE); - temp.add(Blocks.IRON_BLOCK); - //temp.add(Blocks.GOLD_ORE); - temp.add(Blocks.GOLD_BLOCK); - temp.add(Blocks.EMERALD_ORE); - temp.add(Blocks.EMERALD_BLOCK); + Blocks.ENDER_CHEST, + Blocks.FURNACE, + Blocks.CHEST, + Blocks.TRAPPED_CHEST, + Blocks.END_PORTAL, + Blocks.END_PORTAL_FRAME, + Blocks.MOB_SPAWNER, + Blocks.BARRIER, + Blocks.OBSERVER, + Blocks.WHITE_SHULKER_BOX, + Blocks.ORANGE_SHULKER_BOX, + Blocks.MAGENTA_SHULKER_BOX, + Blocks.LIGHT_BLUE_SHULKER_BOX, + Blocks.YELLOW_SHULKER_BOX, + Blocks.LIME_SHULKER_BOX, + Blocks.PINK_SHULKER_BOX, + Blocks.GRAY_SHULKER_BOX, + Blocks.SILVER_SHULKER_BOX, + Blocks.CYAN_SHULKER_BOX, + Blocks.PURPLE_SHULKER_BOX, + Blocks.BLUE_SHULKER_BOX, + Blocks.BROWN_SHULKER_BOX, + Blocks.GREEN_SHULKER_BOX, + Blocks.RED_SHULKER_BOX, + Blocks.BLACK_SHULKER_BOX, + Blocks.PORTAL, + Blocks.HOPPER, + Blocks.BEACON, + Blocks.BREWING_STAND, + Blocks.SKULL, + Blocks.ENCHANTING_TABLE, + Blocks.ANVIL, + Blocks.LIT_FURNACE, + Blocks.BED, + Blocks.DRAGON_EGG, + Blocks.JUKEBOX, + Blocks.END_GATEWAY, + Blocks.WEB, + Blocks.NETHER_WART, + Blocks.LADDER, + Blocks.VINE + ); - temp.add(Blocks.ENDER_CHEST); - temp.add(Blocks.FURNACE); - temp.add(Blocks.CHEST); - temp.add(Blocks.TRAPPED_CHEST); - temp.add(Blocks.END_PORTAL); - temp.add(Blocks.END_PORTAL_FRAME); - temp.add(Blocks.MOB_SPAWNER); - temp.add(Blocks.BARRIER); - temp.add(Blocks.OBSERVER); - temp.add(Blocks.WHITE_SHULKER_BOX); - temp.add(Blocks.ORANGE_SHULKER_BOX); - temp.add(Blocks.MAGENTA_SHULKER_BOX); - temp.add(Blocks.LIGHT_BLUE_SHULKER_BOX); - temp.add(Blocks.YELLOW_SHULKER_BOX); - temp.add(Blocks.LIME_SHULKER_BOX); - temp.add(Blocks.PINK_SHULKER_BOX); - temp.add(Blocks.GRAY_SHULKER_BOX); - temp.add(Blocks.SILVER_SHULKER_BOX); - temp.add(Blocks.CYAN_SHULKER_BOX); - temp.add(Blocks.PURPLE_SHULKER_BOX); - temp.add(Blocks.BLUE_SHULKER_BOX); - temp.add(Blocks.BROWN_SHULKER_BOX); - temp.add(Blocks.GREEN_SHULKER_BOX); - temp.add(Blocks.RED_SHULKER_BOX); - temp.add(Blocks.BLACK_SHULKER_BOX); - temp.add(Blocks.PORTAL); - temp.add(Blocks.HOPPER); - temp.add(Blocks.BEACON); - temp.add(Blocks.BREWING_STAND); - temp.add(Blocks.SKULL); - temp.add(Blocks.ENCHANTING_TABLE); - temp.add(Blocks.ANVIL); - temp.add(Blocks.LIT_FURNACE); - temp.add(Blocks.BED); - temp.add(Blocks.DRAGON_EGG); - temp.add(Blocks.JUKEBOX); - temp.add(Blocks.END_GATEWAY); - temp.add(Blocks.WEB); - temp.add(Blocks.NETHER_WART); - temp.add(Blocks.LADDER); - temp.add(Blocks.VINE); - BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(temp); - } /** * The size of the chunk data in bits. Equal to 16 KiB. From 7d9b8ee4f3ef7138366270771f3e685ffba5c237 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 28 Apr 2019 21:38:10 -0700 Subject: [PATCH 378/682] that was too high tbh lol --- 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 afd6a0db..cfade96a 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -84,7 +84,7 @@ public final class Settings { /** * Walking on water uses up hunger really quick, so penalize it */ - public final Setting walkOnWaterOnePenalty = new Setting<>(5D); + public final Setting walkOnWaterOnePenalty = new Setting<>(3D); /** * Allow Baritone to fall arbitrary distances and place a water bucket beneath it. From b338dcc9de32f56e245420a86584ef799defa8d3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 29 Apr 2019 11:46:21 -0700 Subject: [PATCH 379/682] add path splice option --- src/api/java/baritone/api/Settings.java | 10 ++++++++++ src/main/java/baritone/behavior/PathingBehavior.java | 4 +++- src/main/java/baritone/pathing/path/PathExecutor.java | 2 +- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index cfade96a..53634e35 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -572,6 +572,16 @@ public final class Settings { */ public final Setting walkWhileBreaking = new Setting<>(true); + /** + * When a new segment is calculated that doesn't overlap with the current one, but simply begins where the current segment ends, + * splice it on and make a longer combined path. If this setting is off, any planned segment will not be spliced and will instead + * be the "next path" in PathingBehavior, and will only start after this one ends. Turning this off hurts planning ahead, + * because the next segment will exist even if it's very short. + * + * @see #planningTickLookahead + */ + public final Setting splicePath = new Setting<>(true); + /** * If we are more than 300 movements into the current path, discard the oldest segments, as they are no longer useful */ diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index e0031c8c..fbe48ad8 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -195,7 +195,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, current.onTick(); return; } - current = current.trySplice(next); + if (Baritone.settings().splicePath.value) { + current = current.trySplice(next); + } if (next != null && current.getPath().getDest().equals(next.getPath().getDest())) { next = null; } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index c848f42b..852ac44e 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -610,7 +610,7 @@ public class PathExecutor implements IPathExecutor, Helper { ret.costEstimateIndex = costEstimateIndex; ret.ticksOnCurrent = ticksOnCurrent; return ret; - }).orElse(cutIfTooLong()); + }).orElseGet(this::cutIfTooLong); // dont actually call cutIfTooLong every tick if we won't actually use it, use a method reference } private PathExecutor cutIfTooLong() { From 85eb7d804351b3873cb180026fc272fc78069631 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 29 Apr 2019 14:55:14 -0700 Subject: [PATCH 380/682] remember beyond render distance what is completed --- .../java/baritone/process/BuilderProcess.java | 34 ++++++++++++++++--- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 6185b300..7988ff15 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -35,6 +35,7 @@ import baritone.utils.BlockStateInterface; import baritone.utils.PathingCommandContext; import baritone.utils.schematic.AirSchematic; import baritone.utils.schematic.Schematic; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; @@ -56,6 +57,7 @@ import static baritone.api.pathing.movement.ActionCosts.COST_INF; public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { private HashSet incorrectPositions; + private LongOpenHashSet observedCompleted; // positions that are completed even if they're out of render distance and we can't make sure right now private String name; private ISchematic realSchematic; private ISchematic schematic; @@ -76,6 +78,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro this.origin = origin; this.paused = false; this.layer = 0; + this.observedCompleted = new LongOpenHashSet(); } public void resume() { @@ -447,10 +450,13 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro IBlockState desired = bcc.getSchematic(x, y, z); if (desired != null) { // we care about this position + BetterBlockPos pos = new BetterBlockPos(x, y, z); if (valid(bcc.bsi.get0(x, y, z), desired)) { - incorrectPositions.remove(new BetterBlockPos(x, y, z)); + incorrectPositions.remove(pos); + observedCompleted.add(BetterBlockPos.longHash(pos)); } else { - incorrectPositions.add(new BetterBlockPos(x, y, z)); + incorrectPositions.add(pos); + observedCompleted.rem(BetterBlockPos.longHash(pos)); } } } @@ -463,8 +469,27 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro for (int y = 0; y < schematic.heightY(); y++) { for (int z = 0; z < schematic.lengthZ(); z++) { for (int x = 0; x < schematic.widthX(); x++) { - if (schematic.inSchematic(x, y, z) && !valid(bcc.bsi.get0(x + origin.getX(), y + origin.getY(), z + origin.getZ()), schematic.desiredState(x, y, z))) { - incorrectPositions.add(new BetterBlockPos(x + origin.getX(), y + origin.getY(), z + origin.getZ())); + if (!schematic.inSchematic(x, y, z)) { + continue; + } + int blockX = x + origin.getX(); + int blockY = y + origin.getY(); + int blockZ = z + origin.getZ(); + if (bcc.bsi.worldContainsLoadedChunk(blockX, blockZ)) { // check if its in render distance, not if its in cache + // we can directly observe this block, it is in render distance + if (valid(bcc.bsi.get0(blockX, blockY, blockZ), schematic.desiredState(x, y, z))) { + observedCompleted.add(BetterBlockPos.longHash(blockX, blockY, blockZ)); + } else { + incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ)); + observedCompleted.rem(BetterBlockPos.longHash(blockX, blockY, blockZ)); + } + continue; + } + // this is not in render distance + if (!observedCompleted.contains(BetterBlockPos.longHash(blockX, blockY, blockZ))) { + // and we've never seen this position be correct + // therefore mark as incorrect + incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ)); } } } @@ -587,6 +612,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro realSchematic = null; layer = 0; paused = false; + observedCompleted = null; } @Override From 9bf3a041d47ab89578bc2ee0da3dc86c52d4637d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 29 Apr 2019 14:59:25 -0700 Subject: [PATCH 381/682] might as well privatize --- .../java/baritone/process/BuilderProcess.java | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 7988ff15..fa7c9912 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -135,9 +135,8 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } return state; } - - - public Optional> toBreakNearPlayer(BuilderCalculationContext bcc) { + + private Optional> toBreakNearPlayer(BuilderCalculationContext bcc) { BetterBlockPos center = ctx.playerFeet(); for (int dx = -5; dx <= 5; dx++) { for (int dy = 0; dy <= 5; dy++) { @@ -177,7 +176,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } - public Optional searchForPlacables(BuilderCalculationContext bcc, List desirableOnHotbar) { + private Optional searchForPlacables(BuilderCalculationContext bcc, List desirableOnHotbar) { BetterBlockPos center = ctx.playerFeet(); for (int dx = -5; dx <= 5; dx++) { for (int dy = -5; dy <= 1; dy++) { @@ -206,7 +205,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return Optional.empty(); } - public Optional possibleToPlace(IBlockState toPlace, int x, int y, int z, BlockStateInterface bsi) { + private Optional possibleToPlace(IBlockState toPlace, int x, int y, int z, BlockStateInterface bsi) { for (EnumFacing against : EnumFacing.values()) { BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against); IBlockState placeAgainstState = bsi.get0(placeAgainstPos); @@ -234,8 +233,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return Optional.empty(); } - - public OptionalInt hasAnyItemThatWouldPlace(IBlockState desired, RayTraceResult result, Rotation rot) { + private OptionalInt hasAnyItemThatWouldPlace(IBlockState desired, RayTraceResult result, Rotation rot) { for (int i = 0; i < 9; i++) { ItemStack stack = ctx.player().inventory.mainInventory.get(i); if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) { @@ -416,7 +414,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return new PathingCommandContext(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc); } - public boolean recalc(BuilderCalculationContext bcc) { + private boolean recalc(BuilderCalculationContext bcc) { if (incorrectPositions == null) { incorrectPositions = new HashSet<>(); fullRecalc(bcc); @@ -431,7 +429,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return !incorrectPositions.isEmpty(); } - public void trim(BuilderCalculationContext bcc) { + private void trim(BuilderCalculationContext bcc) { HashSet copy = new HashSet<>(incorrectPositions); copy.removeIf(pos -> pos.distanceSq(ctx.player().posX, ctx.player().posY, ctx.player().posZ) > 200); if (!copy.isEmpty()) { @@ -439,7 +437,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } - public void recalcNearby(BuilderCalculationContext bcc) { + private void recalcNearby(BuilderCalculationContext bcc) { BetterBlockPos center = ctx.playerFeet(); for (int dx = -5; dx <= 5; dx++) { for (int dy = -5; dy <= 5; dy++) { @@ -464,7 +462,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } - public void fullRecalc(BuilderCalculationContext bcc) { + private void fullRecalc(BuilderCalculationContext bcc) { incorrectPositions = new HashSet<>(); for (int y = 0; y < schematic.heightY(); y++) { for (int z = 0; z < schematic.lengthZ(); z++) { @@ -553,7 +551,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } - public Goal placementgoal(BlockPos pos, BuilderCalculationContext bcc) { + private Goal placementgoal(BlockPos pos, BuilderCalculationContext bcc) { if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) { return new GoalPlace(pos); } @@ -620,7 +618,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return paused ? "Builder Paused" : "Building " + name; } - public List placable(int size) { + private List placable(int size) { List result = new ArrayList<>(); for (int i = 0; i < size; i++) { ItemStack stack = ctx.player().inventory.mainInventory.get(i); @@ -635,7 +633,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return result; } - public boolean valid(IBlockState current, IBlockState desired) { + private boolean valid(IBlockState current, IBlockState desired) { // TODO more complicated comparison logic I guess return desired == null || current.equals(desired); } From f7a577e1632273942a42d977da65531695b0f987 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 29 Apr 2019 16:02:44 -0700 Subject: [PATCH 382/682] break from above --- src/api/java/baritone/api/Settings.java | 14 ++++++++ .../java/baritone/process/BuilderProcess.java | 32 +++++++++++++++---- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 53634e35..8f2b31b1 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -654,6 +654,20 @@ public final class Settings { */ public final Setting buildRepeatDirection = new Setting<>(EnumFacing.NORTH); + /** + * Allow standing above a block while mining it, in BuilderProcess + *

+ * Experimental + */ + public final Setting breakFromAbove = new Setting<>(false); + + /** + * As well as breaking from above, set a goal to up and to the side of all blocks to break. + *

+ * Never turn this on without also turning on breakFromAbove. + */ + public final Setting goalBreakFromAbove = new Setting<>(false); + /** * While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)? */ diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index fa7c9912..9f49c595 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -36,6 +36,7 @@ import baritone.utils.PathingCommandContext; import baritone.utils.schematic.AirSchematic; import baritone.utils.schematic.Schematic; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import net.minecraft.block.BlockAir; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; @@ -135,15 +136,19 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } return state; } - + private Optional> toBreakNearPlayer(BuilderCalculationContext bcc) { BetterBlockPos center = ctx.playerFeet(); + BetterBlockPos pathStart = baritone.getPathingBehavior().pathStart(); for (int dx = -5; dx <= 5; dx++) { - for (int dy = 0; dy <= 5; dy++) { + for (int dy = Baritone.settings().breakFromAbove.value ? -1 : 0; dy <= 5; dy++) { for (int dz = -5; dz <= 5; dz++) { int x = center.x + dx; int y = center.y + dy; int z = center.z + dz; + if (dy == -1 && x == pathStart.x && z == pathStart.z) { + continue; // dont mine what we're supported by, but not directly standing on + } IBlockState desired = bcc.getSchematic(x, y, z); if (desired == null) { continue; // irrelevant @@ -496,8 +501,8 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro private Goal assemble(BuilderCalculationContext bcc, List approxPlacable) { List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); - Goal[] toBreak = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); - Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(pos -> placementgoal(pos, bcc)).toArray(Goal[]::new); + Goal[] toBreak = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(pos -> breakGoal(pos, bcc)).toArray(Goal[]::new); + Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(pos -> placementGoal(pos, bcc)).toArray(Goal[]::new); if (toPlace.length != 0) { return new JankyGoalComposite(new GoalComposite(toPlace), new GoalComposite(toBreak)); @@ -551,8 +556,8 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } - private Goal placementgoal(BlockPos pos, BuilderCalculationContext bcc) { - if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) { + private Goal placementGoal(BlockPos pos, BuilderCalculationContext bcc) { + if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) { // TODO can this even happen? return new GoalPlace(pos); } boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR; @@ -564,6 +569,21 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return new GoalPlace(pos); } + private Goal breakGoal(BlockPos pos, BuilderCalculationContext bcc) { + if (Baritone.settings().goalBreakFromAbove.value && bcc.bsi.get0(pos.up()).getBlock() instanceof BlockAir && bcc.bsi.get0(pos.up(2)).getBlock() instanceof BlockAir) { // TODO maybe possible without the up(2) check? + return new JankyGoalComposite(new GoalBreak(pos), new GoalGetToBlock(pos.up()) { + @Override + public boolean isInGoal(int x, int y, int z) { + if (y > this.y || (x == this.x && y == this.y && z == this.z)) { + return false; + } + return super.isInGoal(x, y, z); + } + }); + } + return new GoalBreak(pos); + } + public static class GoalAdjacent extends GoalGetToBlock { private boolean allowSameLevel; From c931cde3ae66b3a45b025e47eecdfb746d5e8100 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 29 Apr 2019 16:43:47 -0700 Subject: [PATCH 383/682] fix error stacktrace on startup --- src/api/java/baritone/api/utils/SettingsUtil.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 8667f554..3f4de317 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -29,6 +29,7 @@ import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; @@ -80,6 +81,8 @@ public class SettingsUtil { ex.printStackTrace(); } }); + } catch (NoSuchFileException ignored) { + System.out.println("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!"); ex.printStackTrace(); From 920ce745c22aec543d573e5cf26ee1f8046cef44 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 29 Apr 2019 23:08:17 -0700 Subject: [PATCH 384/682] fix some scuff from minebot --- src/api/java/baritone/api/Settings.java | 9 ++++++--- .../java/baritone/pathing/movement/MovementHelper.java | 6 +++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 8f2b31b1..d292e868 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -160,9 +160,12 @@ public final class Settings { /** * Blocks that Baritone is not allowed to break */ - public final Setting> blocksToAvoidBreaking = new Setting<>(new ArrayList<>( - // e.g. crafting table, beds - )); + public final Setting> blocksToAvoidBreaking = new Setting<>(new ArrayList<>(Arrays.asList( + Blocks.CRAFTING_TABLE, + Blocks.FURNACE, + Blocks.LIT_FURNACE, + Blocks.CHEST + ))); /** * Enables some more advanced vine features. They're honestly just gimmicks and won't ever be needed in real diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index c0683d47..b7be8636 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -18,6 +18,7 @@ package baritone.pathing.movement; import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.MovementStatus; @@ -55,8 +56,7 @@ public interface MovementHelper extends ActionCosts, Helper { || bsi.get0(x + 1, y, z).getBlock() instanceof BlockLiquid || bsi.get0(x - 1, y, z).getBlock() instanceof BlockLiquid || bsi.get0(x, y, z + 1).getBlock() instanceof BlockLiquid - || bsi.get0(x, y, z - 1).getBlock() instanceof BlockLiquid - || Baritone.settings().blocksToAvoidBreaking.value.contains(b); + || bsi.get0(x, y, z - 1).getBlock() instanceof BlockLiquid; } static boolean canWalkThrough(IPlayerContext ctx, BetterBlockPos pos) { @@ -363,7 +363,7 @@ public interface MovementHelper extends ActionCosts, Helper { if (block instanceof BlockLiquid) { return COST_INF; } - double m = Blocks.CRAFTING_TABLE.equals(block) ? 10 : 1; // TODO see if this is still necessary. it's from MineBot when we wanted to penalize breaking its crafting table + double m = Baritone.settings().blocksToAvoidBreaking.value.contains(block) ? 10 : 1; double strVsBlock = context.toolSet.getStrVsBlock(state); if (strVsBlock <= 0) { return COST_INF; From 166eb97c3fd882fd25cc14702bff0482b983887f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 30 Apr 2019 16:52:27 -0700 Subject: [PATCH 385/682] make right click on arrival time out after 1 second --- src/main/java/baritone/process/GetToBlockProcess.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 0116df83..69703894 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -42,6 +42,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl private BlockPos start; private int tickCount = 0; + private int arrivalTickCount = 0; public GetToBlockProcess(Baritone baritone) { super(baritone); @@ -53,6 +54,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl gettingTo = block; start = ctx.playerFeet(); blacklist = new ArrayList<>(); + arrivalTickCount = 0; rescan(new ArrayList<>(), new CalculationContext(baritone)); } @@ -196,6 +198,10 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl return true; } } + if (arrivalTickCount++ > 20) { + logDirect("Right click timed out"); + return true; + } return false; // trying to right click, will do it next tick or so } } From a14166b1e28f552b035564a4f797ce0c4e041513 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 30 Apr 2019 16:56:29 -0700 Subject: [PATCH 386/682] overhaul to usage --- USAGE.md | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/USAGE.md b/USAGE.md index 085f49c2..652c093e 100644 --- a/USAGE.md +++ b/USAGE.md @@ -34,15 +34,18 @@ Some common examples: - `cancel` or `stop` to stop everything - `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part) - `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) -- `click` to click your destination on the screen. left click to path into it, right click to path on top of it. left click and drag to clear an area. +- `click` to click your destination on the screen. Right click path to on top of the block, left click to path into it (either at foot level or eye level), and left click and drag to clear all blocks from an area. - `follow playerName` to follow a player. `follow` to follow the entity you're looking at (only works if it hitting range). `followplayers` to follow any players in range (combine with Kill Aura for a fun time). - `save waypointName` to save a waypoint. `goto waypointName` to go to it. +- `build` to build a schematic. `build blah` will load `schematics/blah.schematic` and build it with the origin being your player feet. `build blah x y z` to set the origin. Any of those can be relative to your player (`~ 69 ~-420` would build at x=player x, y=69, z=player z-420). +- `tunnel` to dig just straight ahead and make a tunnel +- `farm` to automatically harvest, replant, or bone meal crops - `axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120). +- `explore x z` to explore the world from the origin of x,z. Leave out x and z to default to player feet. This will continually path towards the closest chunk to the origin that it's never seen before. `explorefilter filter.json` with optional invert can be used to load in a list of chunks to load. - `invert` to invert the current goal and path. This gets as far away from it as possible, instead of as close as possible. For example, do `goal` then `invert` to run as far as possible from where you're standing at the start. -- `render` to rerender the world in case `renderCachedChunks` is being glitchy - `version` to get the version of Baritone you're running - `damn` daniel -- `build` to build a schematic. `build blah` will load `schematics/blah.schematic` and build it with the origin being your player feet. `build blah x y z` to set the origin. Any of those can be relative to your player (`~ 69 ~-420` would build at x=player x, y=69, z=player z-420). + For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java). @@ -54,10 +57,18 @@ There are about a hundred settings, but here are some fun / interesting / import - `allowPlace` - `allowParkour` - `allowParkourPlace` +- `blockPlacementPenalty` - `renderCachedChunks` (and `cachedChunksOpacity`) <-- very fun but you need a beefy computer -- `avoidance` +- `avoidance` (avoidance of mobs / mob spawners) - `legitMine` - `followRadius` +- `backfill` (fill in tunnels behind you) +- `buildInLayers` +- `buildRepeatDistance` and `buildRepeatDirection` +- `worldExploringChunkOffset` +- `acceptableThrowawayItems` +- `blocksToAvoidBreaking` + From 7b7be32ca77d4289dc4d17501563aea18bb50783 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 30 Apr 2019 23:24:08 -0700 Subject: [PATCH 387/682] also break passable blocks at foot level like mushrooms, fixes #407 --- 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 6051fe4a..72abfe9d 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -111,7 +111,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } Optional shaft = curr.stream() .filter(pos -> pos.getX() == ctx.playerFeet().getX() && pos.getZ() == ctx.playerFeet().getZ()) - .filter(pos -> pos.getY() > ctx.playerFeet().getY()) + .filter(pos -> pos.getY() >= ctx.playerFeet().getY()) .filter(pos -> !(BlockStateInterface.get(ctx, pos).getBlock() instanceof BlockAir)) // after breaking a block, it takes mineGoalUpdateInterval ticks for it to actually update this list =( .min(Comparator.comparingDouble(ctx.player()::getDistanceSq)); baritone.getInputOverrideHandler().clearAllKeys(); From 5f12f04e873c6d63eb79bd30692178fbba69634f Mon Sep 17 00:00:00 2001 From: SuperOP535 <27556391+SuperOP535@users.noreply.github.com> Date: Wed, 1 May 2019 14:05:47 +0200 Subject: [PATCH 388/682] Automatic CRLF -> LF normalization --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..176a458f --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto From e9e26c981a47def0082835614f38083a86051506 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 1 May 2019 10:37:23 -0700 Subject: [PATCH 389/682] fine babj --- src/api/java/baritone/api/Settings.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index d292e868..bb6038b6 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -164,7 +164,8 @@ public final class Settings { Blocks.CRAFTING_TABLE, Blocks.FURNACE, Blocks.LIT_FURNACE, - Blocks.CHEST + Blocks.CHEST, + Blocks.TRAPPED_CHEST ))); /** From d60a0bee9eb45b081e1df9e0b2e34db2611b958d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 1 May 2019 10:48:17 -0700 Subject: [PATCH 390/682] move this behind the toolset cache for performance --- .../baritone/pathing/movement/MovementHelper.java | 11 ++++------- src/main/java/baritone/utils/ToolSet.java | 10 +++++++--- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index b7be8636..e6f54213 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -18,7 +18,6 @@ package baritone.pathing.movement; import baritone.Baritone; -import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.MovementStatus; @@ -353,6 +352,9 @@ public interface MovementHelper extends ActionCosts, Helper { static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) { Block block = state.getBlock(); if (!canWalkThrough(context.bsi, x, y, z, state)) { + if (block instanceof BlockLiquid) { + return COST_INF; + } double mult = context.breakCostMultiplierAt(x, y, z); if (mult >= COST_INF) { return COST_INF; @@ -360,16 +362,11 @@ public interface MovementHelper extends ActionCosts, Helper { if (avoidBreaking(context.bsi, x, y, z, state)) { return COST_INF; } - if (block instanceof BlockLiquid) { - return COST_INF; - } - double m = Baritone.settings().blocksToAvoidBreaking.value.contains(block) ? 10 : 1; double strVsBlock = context.toolSet.getStrVsBlock(state); if (strVsBlock <= 0) { return COST_INF; } - - double result = m / strVsBlock; + double result = 1 / strVsBlock; result += context.breakBlockAdditionalCost; result *= mult; if (includeFalling) { diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 31f23f20..69a5ae9a 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -65,10 +65,10 @@ public class ToolSet { } /** - * Using the best tool on the hotbar, how long would it take to mine this block + * Using the best tool on the hotbar, how fast we can mine this block * * @param state the blockstate to be mined - * @return how long it would take in ticks + * @return the speed of how fast we'll mine it. 1/(time in ticks) */ public double getStrVsBlock(IBlockState state) { return breakStrengthCache.computeIfAbsent(state.getBlock(), backendCalculation); @@ -128,7 +128,11 @@ public class ToolSet { */ private double getBestDestructionTime(Block b) { ItemStack stack = player.inventory.getStackInSlot(getBestSlot(b)); - return calculateSpeedVsBlock(stack, b.getDefaultState()); + return calculateSpeedVsBlock(stack, b.getDefaultState()) * avoidanceMultiplier(b); + } + + private double avoidanceMultiplier(Block b) { + return Baritone.settings().blocksToAvoidBreaking.value.contains(b) ? 0.1 : 1; } /** From 58ebd5f9a60401e9737e33ff77b99fdf12ed2285 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 1 May 2019 11:01:00 -0700 Subject: [PATCH 391/682] split this out into its own function --- .../pathing/movement/MovementHelper.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index e6f54213..6a0b07f0 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -51,11 +51,19 @@ public interface MovementHelper extends ActionCosts, Helper { return b == Blocks.ICE // ice becomes water, and water can mess up the path || b instanceof BlockSilverfish // obvious reasons // call context.get directly with x,y,z. no need to make 5 new BlockPos for no reason - || bsi.get0(x, y + 1, z).getBlock() instanceof BlockLiquid//don't break anything touching liquid on any side - || bsi.get0(x + 1, y, z).getBlock() instanceof BlockLiquid - || bsi.get0(x - 1, y, z).getBlock() instanceof BlockLiquid - || bsi.get0(x, y, z + 1).getBlock() instanceof BlockLiquid - || bsi.get0(x, y, z - 1).getBlock() instanceof BlockLiquid; + || avoidAdjacentBreaking(bsi, x, y + 1, z) + || avoidAdjacentBreaking(bsi, x + 1, y, z) + || avoidAdjacentBreaking(bsi, x - 1, y, z) + || avoidAdjacentBreaking(bsi, x, y, z + 1) + || avoidAdjacentBreaking(bsi, x, y, z - 1); + } + + static boolean avoidAdjacentBreaking(BlockStateInterface bsi, int x, int y, int z) { + // returns true if you should avoid breaking a block that's adjacent to this one (e.g. lava that will start flowing if you give it a path) + // this is only called for north, south, east, west, and up. this is NOT called for down. + // we assume that it's ALWAYS okay to break the block thats ABOVE liquid + IBlockState state = bsi.get0(x, y, z); + return state.getBlock() instanceof BlockLiquid; } static boolean canWalkThrough(IPlayerContext ctx, BetterBlockPos pos) { From 54da0d24a394ec2d89dc5a4b1820ea969d6fa055 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 1 May 2019 11:16:24 -0700 Subject: [PATCH 392/682] dont mine blocks that update falling blocks, fixes #395 --- src/api/java/baritone/api/Settings.java | 9 +++++++- .../pathing/movement/MovementHelper.java | 22 +++++++++++++------ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index bb6038b6..a2de8b40 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -160,7 +160,7 @@ public final class Settings { /** * Blocks that Baritone is not allowed to break */ - public final Setting> blocksToAvoidBreaking = new Setting<>(new ArrayList<>(Arrays.asList( + public final Setting> blocksToAvoidBreaking = new Setting<>(new ArrayList<>(Arrays.asList( // TODO can this be a HashSet or ImmutableSet? Blocks.CRAFTING_TABLE, Blocks.FURNACE, Blocks.LIT_FURNACE, @@ -168,6 +168,13 @@ public final class Settings { Blocks.TRAPPED_CHEST ))); + /** + * If this setting is true, Baritone will never break a block that is adjacent to an unsupported falling block. + *

+ * I.E. it will never trigger cascading sand / gravel falls + */ + public final Setting avoidUpdatingFallingBlocks = new Setting<>(true); + /** * Enables some more advanced vine features. They're honestly just gimmicks and won't ever be needed in real * pathing scenarios. And they can cause Baritone to get trapped indefinitely in a strange scenario. diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 6a0b07f0..d8f6a2f7 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -51,19 +51,27 @@ public interface MovementHelper extends ActionCosts, Helper { return b == Blocks.ICE // ice becomes water, and water can mess up the path || b instanceof BlockSilverfish // obvious reasons // call context.get directly with x,y,z. no need to make 5 new BlockPos for no reason - || avoidAdjacentBreaking(bsi, x, y + 1, z) - || avoidAdjacentBreaking(bsi, x + 1, y, z) - || avoidAdjacentBreaking(bsi, x - 1, y, z) - || avoidAdjacentBreaking(bsi, x, y, z + 1) - || avoidAdjacentBreaking(bsi, x, y, z - 1); + || avoidAdjacentBreaking(bsi, x, y + 1, z, true) + || avoidAdjacentBreaking(bsi, x + 1, y, z, false) + || avoidAdjacentBreaking(bsi, x - 1, y, z, false) + || avoidAdjacentBreaking(bsi, x, y, z + 1, false) + || avoidAdjacentBreaking(bsi, x, y, z - 1, false); } - static boolean avoidAdjacentBreaking(BlockStateInterface bsi, int x, int y, int z) { + static boolean avoidAdjacentBreaking(BlockStateInterface bsi, int x, int y, int z, boolean directlyAbove) { // returns true if you should avoid breaking a block that's adjacent to this one (e.g. lava that will start flowing if you give it a path) // this is only called for north, south, east, west, and up. this is NOT called for down. // we assume that it's ALWAYS okay to break the block thats ABOVE liquid IBlockState state = bsi.get0(x, y, z); - return state.getBlock() instanceof BlockLiquid; + Block block = state.getBlock(); + if (!directlyAbove // it is fine to mine a block that has a falling block directly above, this (the cost of breaking the stacked fallings) is included in cost calculations + // therefore if directlyAbove is true, we will actually ignore if this is falling + && block instanceof BlockFalling // obviously, this check is only valid for falling blocks + && Baritone.settings().avoidUpdatingFallingBlocks.value // and if the setting is enabled + && BlockFalling.canFallThrough(bsi.get0(x, y - 1, z))) { // and if it would fall (i.e. it's unsupported) + return true; // dont break a block that is adjacent to unsupported gravel because it can cause really weird stuff + } + return block instanceof BlockLiquid; } static boolean canWalkThrough(IPlayerContext ctx, BetterBlockPos pos) { From 4ea8f23fc7795e96ae68353b2c11064c9f59c5c4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 1 May 2019 12:22:47 -0700 Subject: [PATCH 393/682] fix typo crash, fixes #406 --- src/api/java/baritone/api/utils/SettingsUtil.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 3f4de317..b494c662 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -34,6 +34,7 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Objects; import java.util.function.Consumer; import java.util.function.Function; import java.util.regex.Matcher; @@ -237,7 +238,9 @@ public class SettingsUtil { @Override public Object parse(ParserContext context, String raw) { - return this.parser.apply(raw); + Object parsed = this.parser.apply(raw); + Objects.requireNonNull(parsed); + return parsed; } @Override From d0a1c241a41946f1ac77a4f84578c3976d003781 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 1 May 2019 14:03:36 -0700 Subject: [PATCH 394/682] replace liquid source blocks in builder --- .../java/baritone/process/BuilderProcess.java | 44 +++++++++++++++---- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 9f49c595..c08ca8c6 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -37,6 +37,7 @@ import baritone.utils.schematic.AirSchematic; import baritone.utils.schematic.Schematic; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import net.minecraft.block.BlockAir; +import net.minecraft.block.BlockLiquid; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; @@ -51,7 +52,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.*; -import java.util.stream.Collectors; import static baritone.api.pathing.movement.ActionCosts.COST_INF; @@ -500,17 +500,45 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } private Goal assemble(BuilderCalculationContext bcc, List approxPlacable) { - List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); - Goal[] toBreak = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(pos -> breakGoal(pos, bcc)).toArray(Goal[]::new); - Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(pos -> placementGoal(pos, bcc)).toArray(Goal[]::new); + List placable = new ArrayList<>(); + List breakable = new ArrayList<>(); + List sourceLiquids = new ArrayList<>(); + incorrectPositions.forEach(pos -> { + IBlockState state = bcc.bsi.get0(pos); + if (state.getBlock() instanceof BlockAir) { + if (approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))) { + placable.add(pos); + } + } else { + if (state.getBlock() instanceof BlockLiquid) { + // if the block itself is JUST a liquid (i.e. not just a waterlogged block), we CANNOT break it + // TODO for 1.13 make sure that this only matches pure water, not waterlogged blocks + if (!MovementHelper.possiblyFlowing(state)) { + // if it's a source block then we want to replace it with a throwaway + sourceLiquids.add(pos); + } + } else { + breakable.add(pos); + } + } + }); + List toBreak = new ArrayList<>(); + breakable.forEach(pos -> toBreak.add(breakGoal(pos, bcc))); + List toPlace = new ArrayList<>(); + placable.forEach(pos -> { + if (!placable.contains(pos.down()) && !placable.contains(pos.down(2))) { + toPlace.add(placementGoal(pos, bcc)); + } + }); + sourceLiquids.forEach(pos -> toPlace.add(new GoalBlock(pos.up()))); - if (toPlace.length != 0) { - return new JankyGoalComposite(new GoalComposite(toPlace), new GoalComposite(toBreak)); + if (!toPlace.isEmpty()) { + return new JankyGoalComposite(new GoalComposite(toPlace.toArray(new Goal[0])), new GoalComposite(toBreak.toArray(new Goal[0]))); } - if (toBreak.length == 0) { + if (toBreak.isEmpty()) { return null; } - return new GoalComposite(toBreak); + return new GoalComposite(toBreak.toArray(new Goal[0])); } public static class JankyGoalComposite implements Goal { From e05010c9d2454ca66137745f92cebcdb4a366119 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 1 May 2019 23:07:20 -0700 Subject: [PATCH 395/682] fix weird oscillation when mining large veins --- src/main/java/baritone/process/MineProcess.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 72abfe9d..e8368d87 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -206,9 +206,16 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro knownOreLocations = locs; } - private static boolean internalMiningGoal(BlockPos pos, IPlayerContext ctx, List locs) { + private boolean internalMiningGoal(BlockPos pos, IPlayerContext ctx, List locs) { // Here, BlockStateInterface is used because the position may be in a cached chunk (the targeted block is one that is kept track of) - return locs.contains(pos) || (Baritone.settings().internalMiningAirException.value && BlockStateInterface.getBlock(ctx, pos) instanceof BlockAir); + if (locs.contains(pos)) { + return true; + } + Block block = BlockStateInterface.getBlock(ctx, pos); + if (Baritone.settings().internalMiningAirException.value && block instanceof BlockAir) { + return true; + } + return mining.contains(block); } private Goal coalesce(BlockPos loc, List locs) { @@ -363,7 +370,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro .filter(pos -> !blacklist.contains(pos)) - .sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().playerFeet()::distanceSq)) + .sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().player()::getDistanceSq)) .collect(Collectors.toList()); if (locs.size() > max) { From 0ffbb0c15112e029534acad1e9dc92d0e90a2ebc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 2 May 2019 11:47:35 -0700 Subject: [PATCH 396/682] quiet --- src/main/java/baritone/cache/ContainerMemory.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/baritone/cache/ContainerMemory.java b/src/main/java/baritone/cache/ContainerMemory.java index c1cb7b34..e79435e3 100644 --- a/src/main/java/baritone/cache/ContainerMemory.java +++ b/src/main/java/baritone/cache/ContainerMemory.java @@ -29,6 +29,7 @@ import net.minecraft.util.math.BlockPos; import java.io.IOException; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.*; @@ -45,6 +46,8 @@ public class ContainerMemory implements IContainerMemory { this.saveTo = saveTo; try { read(Files.readAllBytes(saveTo)); + } catch (NoSuchFileException ignored) { + inventories.clear(); } catch (Exception ex) { ex.printStackTrace(); inventories.clear(); From 77303b4a629c467d79964ff5c6ac71df4dd14ff4 Mon Sep 17 00:00:00 2001 From: evilsourcerer Date: Fri, 3 May 2019 01:48:37 -0400 Subject: [PATCH 397/682] render boxes for goalYLevel --- .gitignore | 2 +- src/api/java/baritone/api/Settings.java | 4 +++- .../java/baritone/api/pathing/goals/GoalYLevel.java | 2 +- src/main/java/baritone/utils/PathRenderer.java | 12 +++++++++++- 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index de408ec0..0834b1e8 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,4 @@ classes/ # Copyright Files !/.idea/copyright/Baritone.xml -!/.idea/copyright/profiles_settings.xml \ No newline at end of file +!/.idea/copyright/profiles_settings.xml diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index a2de8b40..aa181a39 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -30,8 +30,8 @@ import java.awt.*; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.*; import java.util.List; +import java.util.*; import java.util.function.Consumer; /** @@ -81,6 +81,8 @@ public final class Settings { */ public final Setting jumpPenalty = new Setting<>(2D); + public final Setting yLevelBoxSize = new Setting<>(15D); + /** * Walking on water uses up hunger really quick, so penalize it */ diff --git a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java index ce54eebb..9add7176 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java +++ b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java @@ -29,7 +29,7 @@ public class GoalYLevel implements Goal, ActionCosts { /** * The target Y level */ - private final int level; + public final int level; public GoalYLevel(int level) { this.level = level; diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index d1afe34d..88a18147 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -276,13 +276,13 @@ public final class PathRenderer implements Helper { double maxY; double y1; double y2; + double y = MathHelper.cos((float) (((float) ((System.nanoTime() / 100000L) % 20000L)) / 20000F * Math.PI * 2)); if (goal instanceof IGoalRenderPos) { BlockPos goalPos = ((IGoalRenderPos) goal).getGoalPos(); minX = goalPos.getX() + 0.002 - renderPosX; maxX = goalPos.getX() + 1 - 0.002 - renderPosX; minZ = goalPos.getZ() + 0.002 - renderPosZ; maxZ = goalPos.getZ() + 1 - 0.002 - renderPosZ; - double y = MathHelper.cos((float) (((float) ((System.nanoTime() / 100000L) % 20000L)) / 20000F * Math.PI * 2)); if (goal instanceof GoalGetToBlock || goal instanceof GoalTwoBlocks) { y /= 2; } @@ -341,6 +341,16 @@ public final class PathRenderer implements Helper { drawDankLitGoalBox(player, g, partialTicks, color); } return; + } else if (goal instanceof GoalYLevel) { + GoalYLevel goalpos = (GoalYLevel) goal; + minX = player.posX - Baritone.settings().yLevelBoxSize.value - renderPosX; + minZ = player.posZ - Baritone.settings().yLevelBoxSize.value - renderPosZ; + maxX = player.posX + Baritone.settings().yLevelBoxSize.value - renderPosX; + maxZ = player.posZ + Baritone.settings().yLevelBoxSize.value - renderPosZ; + minY = ((GoalYLevel) goal).level - renderPosY; + maxY = minY + 2; + y1 = 1 + y + goalpos.level - renderPosY; + y2 = 1 - y + goalpos.level - renderPosY; } else { return; } From 0f09a4654058f2adb0583a9687027bc3ef26bc81 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 2 May 2019 23:03:10 -0700 Subject: [PATCH 398/682] javadoc --- src/api/java/baritone/api/Settings.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index aa181a39..7a63fef7 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -30,8 +30,8 @@ import java.awt.*; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.List; import java.util.*; +import java.util.List; import java.util.function.Consumer; /** @@ -81,6 +81,9 @@ public final class Settings { */ public final Setting jumpPenalty = new Setting<>(2D); + /** + * The size of the box that is rendered when the current goal is a GoalYLevel + */ public final Setting yLevelBoxSize = new Setting<>(15D); /** From 2a5ef35794e934306cfbd7a56bb7204d0d2b86a3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 3 May 2019 11:44:37 -0700 Subject: [PATCH 399/682] move this down to the other render settings --- src/api/java/baritone/api/Settings.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 7a63fef7..76ea0e9a 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -81,11 +81,6 @@ public final class Settings { */ public final Setting jumpPenalty = new Setting<>(2D); - /** - * The size of the box that is rendered when the current goal is a GoalYLevel - */ - public final Setting yLevelBoxSize = new Setting<>(15D); - /** * Walking on water uses up hunger really quick, so penalize it */ @@ -804,6 +799,11 @@ public final class Settings { */ public final Setting> logger = new Setting<>(Minecraft.getMinecraft().ingameGUI.getChatGUI()::printChatMessage); + /** + * The size of the box that is rendered when the current goal is a GoalYLevel + */ + public final Setting yLevelBoxSize = new Setting<>(15D); + /** * The color of the current path */ From 7dcd7384f14a6e8cf4ac7259a1754698b9219cfb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 4 May 2019 15:01:11 -0700 Subject: [PATCH 400/682] allow overshooting traverse --- src/api/java/baritone/api/Settings.java | 7 +++++++ .../pathing/movement/movements/MovementTraverse.java | 8 +++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 76ea0e9a..0c2c5d4b 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -215,6 +215,13 @@ public final class Settings { */ public final Setting sprintAscends = new Setting<>(true); + /** + * If we overshoot a traverse and end up one block beyond the destination, mark it as successful anyway. + *

+ * This helps with speed at >=20m/s + */ + public final Setting overshootTraverse = new Setting<>(true); + /** * When breaking blocks for a movement, wait until all falling blocks have settled before continuing */ diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 4f7ae713..a9266f14 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -36,8 +36,6 @@ import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; -import java.util.Objects; - public class MovementTraverse extends Movement { /** @@ -230,7 +228,11 @@ public class MovementTraverse extends Movement { } if (isTheBridgeBlockThere) { - if (ctx.playerFeet().equals(dest)) { + BetterBlockPos feet = ctx.playerFeet(); + if (feet.equals(dest)) { + return state.setStatus(MovementStatus.SUCCESS); + } + if (Baritone.settings().overshootTraverse.value && (feet.equals(dest.add(getDirection())) || feet.equals(dest.add(getDirection()).add(getDirection())))) { return state.setStatus(MovementStatus.SUCCESS); } Block low = BlockStateInterface.get(ctx, src).getBlock(); From 482d874af2206b63d14bad38ee774953d4d899c0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 5 May 2019 23:57:56 -0700 Subject: [PATCH 401/682] this counts as a commit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 93b11474..50d2acfd 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Here are some links to help to get started: # API -The API is heavily documented, you can find the Javadocs for the latest release [here](https://baritone.leijurv.com/). +The API is heavily documented, you can find the Javadocs for the latest release [here](https://baritone.leijurv.com). Please note that usage of anything located outside of the ``baritone.api`` package is not supported by the API release jar. From 1501d721e7a56bf4ebbe541698a94cd6dbcbded4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 6 May 2019 14:01:01 -0700 Subject: [PATCH 402/682] build repeat vector --- src/api/java/baritone/api/Settings.java | 11 +++-------- src/api/java/baritone/api/utils/SettingsUtil.java | 6 ++++++ src/main/java/baritone/process/BuilderProcess.java | 12 ++++-------- 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 0c2c5d4b..17bacf06 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -23,7 +23,7 @@ import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.item.Item; -import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.Vec3i; import net.minecraft.util.text.ITextComponent; import java.awt.*; @@ -663,14 +663,9 @@ public final class Settings { public final Setting buildInLayers = new Setting<>(false); /** - * How far to move before repeating the build. -1 for the size of the build in that axis. 0 to disable + * How far to move before repeating the build. 0 to disable repeating on a certain axis, 0,0,0 to disable entirely */ - public final Setting buildRepeatDistance = new Setting<>(0); - - /** - * What direction to repeat the build in - */ - public final Setting buildRepeatDirection = new Setting<>(EnumFacing.NORTH); + public final Setting buildRepeat = new Setting<>(new Vec3i(0, 0, 0)); /** * Allow standing above a block while mining it, in BuilderProcess diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index b494c662..5dee6e88 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -21,6 +21,7 @@ import baritone.api.Settings; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.Vec3i; import java.awt.*; import java.io.BufferedReader; @@ -179,6 +180,11 @@ public class SettingsUtil { str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])), color -> color.getRed() + "," + color.getGreen() + "," + color.getBlue() ), + VEC3I( + Vec3i.class, + str -> new Vec3i(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])), + vec -> vec.getX() + "," + vec.getY() + "," + vec.getZ() + ), BLOCK( Block.class, str -> BlockUtils.stringToBlockRequired(str.trim()), diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index c08ca8c6..230edf0d 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -330,20 +330,16 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro layer++; return onTick(calcFailed, isSafeToCancel); } - int distance = Baritone.settings().buildRepeatDistance.value; - EnumFacing direction = Baritone.settings().buildRepeatDirection.value; - if (distance == 0) { + Vec3i repeat = Baritone.settings().buildRepeat.value; + if (repeat.equals(new Vec3i(0, 0, 0))) { logDirect("Done building"); onLostControl(); return null; } // build repeat time - if (distance == -1) { - distance = schematic.size(direction.getAxis()); - } layer = 0; - origin = new BlockPos(origin).offset(direction, distance); - logDirect("Repeating build " + distance + " blocks to the " + direction + ", new origin is " + origin); + origin = new BlockPos(origin).add(repeat); + logDirect("Repeating build in vector " + repeat + ", new origin is " + origin); return onTick(calcFailed, isSafeToCancel); } trim(bcc); From da8bf6b1b3c8a3d0e428874de906fc4c2ff29f56 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 6 May 2019 14:07:46 -0700 Subject: [PATCH 403/682] fix a potential concurrency issue --- 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 230edf0d..81f790b6 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -301,6 +301,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro if (realSchematic == null) { realSchematic = schematic; } + ISchematic realSchematic = this.realSchematic; // wrap this properly, dont just have the inner class refer to the builderprocess.this schematic = new ISchematic() { @Override public IBlockState desiredState(int x, int y, int z) { From c738007538563921487ba75c4353f243cbd971e9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 7 May 2019 21:40:03 -0800 Subject: [PATCH 404/682] epic label --- src/main/java/baritone/process/MineProcess.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index e8368d87..59c2d370 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -88,14 +88,14 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return null; } } - boolean shouldCancel = calcFailed; - if (calcFailed && !knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) { - logDirect("Unable to find any path to " + mining + ", blacklisting presumably unreachable closest instance..."); - knownOreLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(blacklist::add); - knownOreLocations.removeIf(blacklist::contains); - shouldCancel = false; // 😎 - } - if (shouldCancel) { + CANCEL: + if (calcFailed) { + if (!knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) { + logDirect("Unable to find any path to " + mining + ", blacklisting presumably unreachable closest instance..."); + knownOreLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(blacklist::add); + knownOreLocations.removeIf(blacklist::contains); + break CANCEL; // 😎 + } logDirect("Unable to find any path to " + mining + ", canceling Mine"); cancel(); return null; From c9e81897a5d3105fbf1fdff78a43f147363f642f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 8 May 2019 11:51:48 -0700 Subject: [PATCH 405/682] im blind lol thanks babj --- src/main/java/baritone/process/MineProcess.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 59c2d370..ca1b3490 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -88,17 +88,16 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return null; } } - CANCEL: if (calcFailed) { if (!knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) { logDirect("Unable to find any path to " + mining + ", blacklisting presumably unreachable closest instance..."); knownOreLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(blacklist::add); knownOreLocations.removeIf(blacklist::contains); - break CANCEL; // 😎 + } else { + logDirect("Unable to find any path to " + mining + ", canceling Mine"); + cancel(); + return null; } - logDirect("Unable to find any path to " + mining + ", canceling Mine"); - cancel(); - return null; } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.value; List curr = new ArrayList<>(knownOreLocations); From 264b3db63c912857db528cce000e5170ddac4f06 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 9 May 2019 15:20:37 -0700 Subject: [PATCH 406/682] this counts as a commit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 50d2acfd..71e60aa4 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) [![Code of Conduct](https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg?style=flat)](https://github.com/cabaletta/baritone/blob/master/CODE_OF_CONDUCT.md) [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) -[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) +[![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) [![Issues](https://img.shields.io/github/issues/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues/) [![GitHub issues-closed](https://img.shields.io/github/issues-closed/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues?q=is%3Aissue+is%3Aclosed) [![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/) From 79d448e5f435aed0d51c6f1b15cd8cb13eb6bd8f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 10 May 2019 23:55:50 -0700 Subject: [PATCH 407/682] add crucial explanation --- 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 17bacf06..ab04d334 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -646,7 +646,7 @@ public final class Settings { public final Setting exploreMaintainY = new Setting<>(64); /** - * Replant nether wart + * Replant nether wart while farming */ public final Setting replantNetherWart = new Setting<>(false); From 6a13e94c4fd942e0d0696c2504680e580c30a1dd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 11 May 2019 21:13:46 -0700 Subject: [PATCH 408/682] warning --- src/api/java/baritone/api/Settings.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index ab04d334..56fb949e 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -545,6 +545,8 @@ public final class Settings { /** * Exclusively use cached chunks for pathing + *

+ * Never turn this on */ public final Setting pathThroughCachedOnly = new Setting<>(false); From 0293a767025ae8c9c838589b3b5936deaa852ba1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 12 May 2019 23:25:50 -0700 Subject: [PATCH 409/682] less yikes --- src/main/java/baritone/process/BuilderProcess.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 81f790b6..7fb1b0ae 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -456,7 +456,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro observedCompleted.add(BetterBlockPos.longHash(pos)); } else { incorrectPositions.add(pos); - observedCompleted.rem(BetterBlockPos.longHash(pos)); + observedCompleted.remove(BetterBlockPos.longHash(pos)); } } } @@ -481,7 +481,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro observedCompleted.add(BetterBlockPos.longHash(blockX, blockY, blockZ)); } else { incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ)); - observedCompleted.rem(BetterBlockPos.longHash(blockX, blockY, blockZ)); + observedCompleted.remove(BetterBlockPos.longHash(blockX, blockY, blockZ)); } continue; } From b2f38807225491224028fe6ca4477e5f5e431a21 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 13 May 2019 20:13:22 -0800 Subject: [PATCH 410/682] add todo --- src/api/java/baritone/api/utils/BetterBlockPos.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/api/java/baritone/api/utils/BetterBlockPos.java b/src/api/java/baritone/api/utils/BetterBlockPos.java index a1a3cb32..3b94a833 100644 --- a/src/api/java/baritone/api/utils/BetterBlockPos.java +++ b/src/api/java/baritone/api/utils/BetterBlockPos.java @@ -61,6 +61,8 @@ public final class BetterBlockPos extends BlockPos { } public static long longHash(int x, int y, int z) { + // TODO use the same thing as BlockPos.fromLong(); + // invertibility would be incredibly useful /* * This is the hashcode implementation of Vec3i (the superclass of the class which I shall not name) * From da58988f017e884faee4ab79f8749ace9d4f334a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 14 May 2019 16:03:11 -0700 Subject: [PATCH 411/682] build in layers order --- src/api/java/baritone/api/Settings.java | 7 +++++++ .../java/baritone/process/BuilderProcess.java | 18 +++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 56fb949e..ed17ce17 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -664,6 +664,13 @@ public final class Settings { */ public final Setting buildInLayers = new Setting<>(false); + /** + * false = build from bottom to top + *

+ * true = build from top to bottom + */ + public final Setting layerOrder = new Setting<>(false); + /** * How far to move before repeating the build. 0 to disable repeating on a certain axis, 0,0,0 to disable entirely */ diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 7fb1b0ae..17424345 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -302,12 +302,28 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro realSchematic = schematic; } ISchematic realSchematic = this.realSchematic; // wrap this properly, dont just have the inner class refer to the builderprocess.this + int minYInclusive; + int maxYInclusive; + // layer = 0 should be nothing + // layer = realSchematic.heightY() should be everything + if (Baritone.settings().layerOrder.value) { // top to bottom + maxYInclusive = realSchematic.heightY() - 1; + minYInclusive = realSchematic.heightY() - layer; + } else { + maxYInclusive = layer - 1; + minYInclusive = 0; + } schematic = new ISchematic() { @Override public IBlockState desiredState(int x, int y, int z) { return realSchematic.desiredState(x, y, z); } + @Override + public boolean inSchematic(int x, int y, int z) { + return ISchematic.super.inSchematic(x, y, z) && y >= minYInclusive && y <= maxYInclusive; + } + @Override public int widthX() { return realSchematic.widthX(); @@ -315,7 +331,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro @Override public int heightY() { - return layer; + return realSchematic.heightY(); } @Override From 0dd4834e18f472812adbe4c7540c5a0f174a0b9c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 15 May 2019 21:55:01 -0800 Subject: [PATCH 412/682] add explanation --- 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 ed17ce17..031443f4 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -577,7 +577,7 @@ public final class Settings { public final Setting renderCachedChunks = new Setting<>(false); /** - * 0.0f = not visible, fully transparent + * 0.0f = not visible, fully transparent (instead of setting this to 0, turn off renderCachedChunks) * 1.0f = fully opaque */ public final Setting cachedChunksOpacity = new Setting<>(0.5f); From 6861bfd4e667c9c23a8849e3efc42049fa6b6205 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 16 May 2019 11:50:48 -0700 Subject: [PATCH 413/682] relative goals --- .../baritone/api/utils/ExampleBaritoneControl.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 715d8edb..67cd5b47 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -688,18 +688,20 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener private Goal parseGoal(String[] params) { Goal goal; try { + BetterBlockPos playerFeet = ctx.playerFeet(); switch (params.length) { case 0: - goal = new GoalBlock(ctx.playerFeet()); + goal = new GoalBlock(playerFeet); break; case 1: - goal = new GoalYLevel(Integer.parseInt(params[0])); + + goal = new GoalYLevel(parseOrDefault(params[0], playerFeet.y)); break; case 2: - goal = new GoalXZ(Integer.parseInt(params[0]), Integer.parseInt(params[1])); + goal = new GoalXZ(parseOrDefault(params[0], playerFeet.x), parseOrDefault(params[1], playerFeet.z)); break; case 3: - goal = new GoalBlock(new BlockPos(Integer.parseInt(params[0]), Integer.parseInt(params[1]), Integer.parseInt(params[2]))); + goal = new GoalBlock(new BlockPos(parseOrDefault(params[0], playerFeet.x), parseOrDefault(params[1], playerFeet.y), parseOrDefault(params[2], playerFeet.z))); break; default: logDirect("unable to understand lol"); From 4679e1258832418aeac6b133d237a5aef2fa8876 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 16 May 2019 15:20:52 -0700 Subject: [PATCH 414/682] better usage --- USAGE.md | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/USAGE.md b/USAGE.md index 652c093e..ce8924a7 100644 --- a/USAGE.md +++ b/USAGE.md @@ -2,24 +2,17 @@ # Prefix -Baritone commands can by default be typed in the chatbox. However if you make a typo, like typing "gola 10000 10000" instead of goal it goes into public chat, which is bad. - -Therefore you can use a prefix before your messages. - -On Baritone v1.1.0 and newer: The prefix is `#` by default. Anything beginning with `#` isn't sent, and is only interpreted by Baritone. -For older than v1.1.0, `#` must be enabled by toggling on the `prefix` setting. - -**Only** in Impact is `.b` also a valid prefix. In 4.4, `#` does **not** work, neither does saying the commands directly in chat. `#` works by default in 4.5 (not 4.4). - -Other clients like Kami and Asuna have their own custom things (like `-path`), and can disable direct chat control entirely. +Baritone's chat control prefix is `#` by default. In Impact, you can also use `.b` as a prefix. (for example, `.b click` instead of `#click`) +Baritone commands can also by default be typed in the chatbox. However if you make a typo, like typing "gola 10000 10000" instead of "goal" it goes into public chat, which is bad, so using `#` is suggested. +To disable direct chat control (with no prefix), turn off the `chatControl` setting. To disable chat control with the `#` prefix, turn off the `prefixControl` setting. In Impact, `.b` cannot be disabled. Be careful that you don't leave yourself with all control methods disabled (if you do, reset your settings by deleting the file `minecraft/baritone/settings.txt` and relaunching). # Commands **All** of these commands may need a prefix before them, as above ^. -`help` for (rudimentary) help. You can see what it says [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java#L53). +`help` for (rudimentary) help. You can see what it says [here](https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/utils/ExampleBaritoneControl.java#L47). To toggle a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `primaryTimeoutMS 250`). It's case insensitive. To reset a setting to its default value, say `acceptableThrowawayItems reset`. To reset all settings, say `reset`. To see all settings that have been modified from their default values, say `modified`. @@ -47,7 +40,7 @@ Some common examples: - `damn` daniel -For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java). +For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/utils/ExampleBaritoneControl.java). All the settings and documentation are here. If you find HTML easier to read than Javadoc, you can look here. From 352e4288900b0c6020ced930be7debce9e330643 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 17 May 2019 22:21:40 -0800 Subject: [PATCH 415/682] explicitly set serialized name post obf --- src/api/java/baritone/api/utils/MyChunkPos.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/api/java/baritone/api/utils/MyChunkPos.java b/src/api/java/baritone/api/utils/MyChunkPos.java index 5748a13d..0533fb0c 100644 --- a/src/api/java/baritone/api/utils/MyChunkPos.java +++ b/src/api/java/baritone/api/utils/MyChunkPos.java @@ -17,11 +17,15 @@ package baritone.api.utils; +import com.google.gson.annotations.SerializedName; + /** * Need a non obfed chunkpos that we can load using GSON */ public class MyChunkPos { + @SerializedName("x") public int x; + @SerializedName("y") public int z; @Override From ccc1b04e815c2626bb930396c4fa71c4a50c0522 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 18 May 2019 17:11:16 -0700 Subject: [PATCH 416/682] crucial spacing --- src/api/java/baritone/api/utils/MyChunkPos.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/api/java/baritone/api/utils/MyChunkPos.java b/src/api/java/baritone/api/utils/MyChunkPos.java index 0533fb0c..b122cdba 100644 --- a/src/api/java/baritone/api/utils/MyChunkPos.java +++ b/src/api/java/baritone/api/utils/MyChunkPos.java @@ -23,8 +23,10 @@ import com.google.gson.annotations.SerializedName; * Need a non obfed chunkpos that we can load using GSON */ public class MyChunkPos { + @SerializedName("x") public int x; + @SerializedName("y") public int z; From d70da4f37da27a2e7b0e8855baff529657270b82 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 19 May 2019 21:53:09 -0800 Subject: [PATCH 417/682] finalize these --- src/api/java/baritone/api/utils/MyChunkPos.java | 2 +- src/main/java/baritone/process/BackfillProcess.java | 2 +- src/main/java/baritone/process/BuilderProcess.java | 2 +- src/main/java/baritone/process/CustomGoalProcess.java | 2 +- src/main/java/baritone/process/ExploreProcess.java | 2 +- src/main/java/baritone/process/FarmProcess.java | 2 +- src/main/java/baritone/process/GetToBlockProcess.java | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/api/java/baritone/api/utils/MyChunkPos.java b/src/api/java/baritone/api/utils/MyChunkPos.java index b122cdba..1df7481d 100644 --- a/src/api/java/baritone/api/utils/MyChunkPos.java +++ b/src/api/java/baritone/api/utils/MyChunkPos.java @@ -23,7 +23,7 @@ import com.google.gson.annotations.SerializedName; * Need a non obfed chunkpos that we can load using GSON */ public class MyChunkPos { - + @SerializedName("x") public int x; diff --git a/src/main/java/baritone/process/BackfillProcess.java b/src/main/java/baritone/process/BackfillProcess.java index 8567a049..65e5692e 100644 --- a/src/main/java/baritone/process/BackfillProcess.java +++ b/src/main/java/baritone/process/BackfillProcess.java @@ -35,7 +35,7 @@ import net.minecraft.world.chunk.EmptyChunk; import java.util.*; import java.util.stream.Collectors; -public class BackfillProcess extends BaritoneProcessHelper { +public final class BackfillProcess extends BaritoneProcessHelper { public HashMap blocksToReplace = new HashMap<>(); diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 17424345..27c1f885 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -55,7 +55,7 @@ import java.util.*; import static baritone.api.pathing.movement.ActionCosts.COST_INF; -public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { +public final class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { private HashSet incorrectPositions; private LongOpenHashSet observedCompleted; // positions that are completed even if they're out of render distance and we can't make sure right now diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index 4003b7a7..b45c7d6f 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -29,7 +29,7 @@ import baritone.utils.BaritoneProcessHelper; * * @author leijurv */ -public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomGoalProcess { +public final class CustomGoalProcess extends BaritoneProcessHelper implements ICustomGoalProcess { /** * The current goal diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 35ddcb84..aa7e2c2a 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -41,7 +41,7 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -public class ExploreProcess extends BaritoneProcessHelper implements IExploreProcess { +public final class ExploreProcess extends BaritoneProcessHelper implements IExploreProcess { private BlockPos explorationOrigin; diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index ac6d488f..9593a192 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -50,7 +50,7 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -public class FarmProcess extends BaritoneProcessHelper implements IFarmProcess { +public final class FarmProcess extends BaritoneProcessHelper implements IFarmProcess { private boolean active; diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 69703894..4fb4d540 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -34,7 +34,7 @@ import net.minecraft.util.math.BlockPos; import java.util.*; -public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess { +public final class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess { private Block gettingTo; private List knownLocations; From c7fe9c31719fbfbd6dc34e6312f85b8f4884b217 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 20 May 2019 22:37:51 -0700 Subject: [PATCH 418/682] finalize --- src/main/java/baritone/behavior/InventoryBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 03878ee5..684613af 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -33,7 +33,7 @@ import java.util.OptionalInt; import java.util.Random; import java.util.function.Predicate; -public class InventoryBehavior extends Behavior { +public final class InventoryBehavior extends Behavior { public InventoryBehavior(Baritone baritone) { super(baritone); } From 79da32cc60708ce64501118a8d3705e3e516b778 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 21 May 2019 15:07:05 -0700 Subject: [PATCH 419/682] unused --- src/main/java/baritone/pathing/movement/Movement.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index c9849cab..be29b988 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -32,7 +32,6 @@ import net.minecraft.util.math.BlockPos; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.Optional; public abstract class Movement implements IMovement, MovementHelper { From bb924ad83ff8d5754dd039de9f5718fe1e85cf1b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 22 May 2019 23:41:02 -0700 Subject: [PATCH 420/682] thank you intellij very cool --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 67cd5b47..467d4d95 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -332,7 +332,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener if (suffix.isEmpty()) { // clear the area from the current goal to here Goal goal = baritone.getPathingBehavior().getGoal(); - if (goal == null || !(goal instanceof GoalBlock)) { + if (!(goal instanceof GoalBlock)) { logDirect("Need to specify goal of opposite corner"); return true; } From b4d203ab99abf71f3f29e3841839fee57c010922 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 23 May 2019 20:47:22 -0800 Subject: [PATCH 421/682] bye --- .../baritone/api/utils/ExampleBaritoneControl.java | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 467d4d95..927ba794 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -385,17 +385,6 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener logDirect("farming"); return true; } - // this literally doesn't work, memory is disabled lol - /*if (msg.equals("echest")) { - Optional> contents = baritone.getMemoryBehavior().echest(); - if (contents.isPresent()) { - logDirect("echest contents:"); - log(contents.get()); - } else { - logDirect("echest contents unknown"); - } - return true; - }*/ if (msg.equals("chests")) { for (Map.Entry entry : baritone.getWorldProvider().getCurrentWorld().getContainerMemory().getRememberedInventories().entrySet()) { logDirect(entry.getKey() + ""); From a6954aa719ae519a4d17418b3f69665843d41db2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 24 May 2019 10:36:01 -0700 Subject: [PATCH 422/682] bye 2 --- .../api/utils/ExampleBaritoneControl.java | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 927ba794..29547281 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -638,24 +638,6 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } return true; } - // this is completely impossible from api - /*if (msg.equals("costs")) { - List moves = Stream.of(Moves.values()).map(x -> x.apply0(new CalculationContext(baritone), ctx.playerFeet())).collect(Collectors.toCollection(ArrayList::new)); - while (moves.contains(null)) { - moves.remove(null); - } - moves.sort(Comparator.comparingDouble(move -> move.getCost(new CalculationContext(baritone)))); - for (Movement move : moves) { - String[] parts = move.getClass().toString().split("\\."); - double cost = move.getCost(); - String strCost = cost + ""; - if (cost >= ActionCosts.COST_INF) { - strCost = "IMPOSSIBLE"; - } - logDirect(parts[parts.length - 1] + " " + move.getDest().getX() + "," + move.getDest().getY() + "," + move.getDest().getZ() + " " + strCost); - } - return true; - }*/ if (msg.equals("damn")) { logDirect("daniel"); } From bd0c7b9391a4d34ea9ada7d3142474ca91b14437 Mon Sep 17 00:00:00 2001 From: Babbaj Date: Sat, 25 May 2019 17:25:23 -0400 Subject: [PATCH 423/682] yet another meaningless commit --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 29547281..2b6186b5 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -415,7 +415,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return true; } Entity effectivelyFinal = toFollow.get(); - baritone.getFollowProcess().follow(x -> effectivelyFinal.equals(x)); + baritone.getFollowProcess().follow(effectivelyFinal::equals); logDirect("Following " + toFollow.get()); return true; } From de554655a54ab76d2dcc0bc16eb7c0c5fbac9895 Mon Sep 17 00:00:00 2001 From: Babbaj Date: Sat, 25 May 2019 17:27:06 -0400 Subject: [PATCH 424/682] yet another meaningless commit --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 29547281..2b6186b5 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -415,7 +415,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return true; } Entity effectivelyFinal = toFollow.get(); - baritone.getFollowProcess().follow(x -> effectivelyFinal.equals(x)); + baritone.getFollowProcess().follow(effectivelyFinal::equals); logDirect("Following " + toFollow.get()); return true; } From 18474d872c652a9d61c7ee1159811f2bcd1eebb3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 26 May 2019 12:14:08 -0700 Subject: [PATCH 425/682] unused --- src/main/java/baritone/process/BuilderProcess.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 27c1f885..6c921f8e 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -359,7 +359,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil logDirect("Repeating build in vector " + repeat + ", new origin is " + origin); return onTick(calcFailed, isSafeToCancel); } - trim(bcc); + trim(); Optional> toBreak = toBreakNearPlayer(bcc); if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) { @@ -447,7 +447,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil return !incorrectPositions.isEmpty(); } - private void trim(BuilderCalculationContext bcc) { + private void trim() { HashSet copy = new HashSet<>(incorrectPositions); copy.removeIf(pos -> pos.distanceSq(ctx.player().posX, ctx.player().posY, ctx.player().posZ) > 200); if (!copy.isEmpty()) { From 2e2f4aee1b261fade1c4b85d326e2f573fb4c1bf Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 27 May 2019 02:30:04 -0500 Subject: [PATCH 426/682] critical performance enhancement --- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index fbe48ad8..a5ffc598 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -65,7 +65,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private boolean lastAutoJump; - private BlockPos expectedSegmentStart; + private BetterBlockPos expectedSegmentStart; private final LinkedBlockingQueue toDispatch = new LinkedBlockingQueue<>(); From aa0f664cda65647a62eb384abe16f46550af5ebb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 27 May 2019 21:20:00 -0700 Subject: [PATCH 427/682] =?UTF-8?q?just=20for=20debugging=20purposes=20?= =?UTF-8?q?=F0=9F=98=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../baritone/api/utils/ExampleBaritoneControl.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 2b6186b5..8369d5f9 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -33,9 +33,11 @@ import baritone.api.process.IGetToBlockProcess; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ChunkProviderClient; +import net.minecraft.crash.CrashReport; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; +import net.minecraft.util.ReportedException; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.Chunk; @@ -195,6 +197,17 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener logDirect("Goal: " + goal); return true; } + if (msg.equals("crash")) { + StringBuilder meme = new StringBuilder(); + CrashReport rep = (new CrashReport("Manually triggered debug crash", new Throwable())); + mc.addGraphicsAndWorldToCrashReport(rep); + new ReportedException(rep).printStackTrace(); + rep.getSectionsInStringBuilder(meme); + System.out.println(meme); + logDirect(meme.toString()); + logDirect("ok"); + return true; + } if (msg.equals("path")) { if (pathingBehavior.getGoal() == null) { logDirect("No goal."); From a1e2b018a281053b0b863e732674d646e56de933 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 28 May 2019 14:17:54 -0700 Subject: [PATCH 428/682] very good suggestion --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 8369d5f9..29b42d69 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -199,7 +199,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } if (msg.equals("crash")) { StringBuilder meme = new StringBuilder(); - CrashReport rep = (new CrashReport("Manually triggered debug crash", new Throwable())); + CrashReport rep = new CrashReport("Manually triggered debug crash", new Throwable()); mc.addGraphicsAndWorldToCrashReport(rep); new ReportedException(rep).printStackTrace(); rep.getSectionsInStringBuilder(meme); From 479b4e334940d9207c299eb9621b0f036ce08772 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 29 May 2019 10:45:59 -0700 Subject: [PATCH 429/682] releases download count --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 71e60aa4..1cfa84d4 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ [![License](https://img.shields.io/badge/license-LGPL--3.0%20with%20anime%20exception-green.svg)](LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) [![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) +[![GitHub All Releases](https://img.shields.io/github/downloads/cabaletta/baritone/total.svg)](https://github.com/cabaletta/baritone/releases) [![Code of Conduct](https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg?style=flat)](https://github.com/cabaletta/baritone/blob/master/CODE_OF_CONDUCT.md) [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) [![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) From 1a52537d0c0aff32a9d466fe2464b8081fb1b149 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 30 May 2019 20:49:04 -0800 Subject: [PATCH 430/682] badges --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1cfa84d4..3b321ff4 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) -[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.5%20/%20v1.3.0-brightgreen.svg)](https://impactdevelopment.github.io/) +[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.6%20/%20v1.3.2-brightgreen.svg)](https://impactdevelopment.github.io/) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-red.svg)](https://github.com/zeroeightysix/KAMI/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) From aca6922be0495660d5a3999aa6dbc9347db0f44b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 31 May 2019 23:01:16 -0700 Subject: [PATCH 431/682] there is no actual integration --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 3b321ff4..af30ced0 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,6 @@ [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.6%20/%20v1.3.2-brightgreen.svg)](https://impactdevelopment.github.io/) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) -[![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-red.svg)](https://github.com/zeroeightysix/KAMI/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soon™-red.svg)](https://github.com/fr1kin/ForgeHax) [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com) From 39a231eae0ac8389a54bab541699322115c77293 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 1 Jun 2019 10:56:24 -0700 Subject: [PATCH 432/682] crucial performance optimization --- 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 ca1b3490..1e138290 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -281,7 +281,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro public static List droppedItemsScan(List mining, World world) { if (!Baritone.settings().mineScanDroppedItems.value) { - return new ArrayList<>(); + return Collections.emptyList(); } Set searchingFor = new HashSet<>(); for (Block block : mining) { From 023aa78d8be4fc7c0bbc6f5eb77e117d7ea5c072 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 1 Jun 2019 15:36:52 -0700 Subject: [PATCH 433/682] yay --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index af30ced0..9d782372 100644 --- a/README.md +++ b/README.md @@ -18,9 +18,9 @@ [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.6%20/%20v1.3.2-brightgreen.svg)](https://impactdevelopment.github.io/) +[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-v1.2.*-green.svg)](https://github.com/fr1kin/ForgeHax) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) -[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soon™-red.svg)](https://github.com/fr1kin/ForgeHax) [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com) [![forthebadge](https://forthebadge.com/images/badges/mom-made-pizza-rolls.svg)](http://forthebadge.com) From 9611cb9057ae00ed31fd0443374df64be68127ed Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 1 Jun 2019 17:54:16 -0700 Subject: [PATCH 434/682] 1.13.2 is supported --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 9d782372..6ac396c3 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ ![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg) ![](https://tokei.rs/b1/github/cabaletta/baritone?category=code) [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) +[![Minecraft](https://img.shields.io/badge/MC-1.13.2-brightgreen.svg)](https://minecraft.gamepedia.com/1.13.2) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.6%20/%20v1.3.2-brightgreen.svg)](https://impactdevelopment.github.io/) From 130873d91d0cdfdd16e0552b369e5a9ca1f740fb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 2 Jun 2019 21:33:10 -0700 Subject: [PATCH 435/682] 1.13.2 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6ac396c3..048f8a56 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ A Minecraft pathfinder bot. Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), -the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2. 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). +the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2 and 1.13.2. 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). Have committed at least once a day for the last 8 months =D 🦀 From f19e63d6e9778ef0908ccac78590d9690936e3c7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 3 Jun 2019 13:43:32 -0700 Subject: [PATCH 436/682] mc version support is important --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 048f8a56..5eb0c920 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,8 @@ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) [![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) [![GitHub All Releases](https://img.shields.io/github/downloads/cabaletta/baritone/total.svg)](https://github.com/cabaletta/baritone/releases) +[![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) +[![Minecraft](https://img.shields.io/badge/MC-1.13.2-brightgreen.svg)](https://minecraft.gamepedia.com/1.13.2) [![Code of Conduct](https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg?style=flat)](https://github.com/cabaletta/baritone/blob/master/CODE_OF_CONDUCT.md) [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) [![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) @@ -14,8 +16,6 @@ ![Code size](https://img.shields.io/github/languages/code-size/cabaletta/baritone.svg) ![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg) ![](https://tokei.rs/b1/github/cabaletta/baritone?category=code) -[![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) -[![Minecraft](https://img.shields.io/badge/MC-1.13.2-brightgreen.svg)](https://minecraft.gamepedia.com/1.13.2) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.6%20/%20v1.3.2-brightgreen.svg)](https://impactdevelopment.github.io/) From e1dd580df8943cd1db6e532160cf84b82f031d91 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 3 Jun 2019 15:26:57 -0700 Subject: [PATCH 437/682] fix improper singleplayer check after quitting singleplayer --- .../baritone/launch/mixins/MixinChunkRenderContainer.java | 2 +- .../java/baritone/launch/mixins/MixinChunkRenderWorker.java | 2 +- src/launch/java/baritone/launch/mixins/MixinRenderChunk.java | 4 ++-- src/launch/java/baritone/launch/mixins/MixinRenderList.java | 2 +- .../java/baritone/launch/mixins/MixinVboRenderList.java | 2 +- src/main/java/baritone/cache/WorldProvider.java | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java index 78bd1607..0d228db9 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderContainer.java @@ -41,7 +41,7 @@ public class MixinChunkRenderContainer { ) ) private BlockPos getPosition(RenderChunk renderChunkIn) { - if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { + if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer() && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { GlStateManager.enableAlpha(); GlStateManager.enableBlend(); GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.value); diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java index 81e39382..d72fdd41 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java +++ b/src/launch/java/baritone/launch/mixins/MixinChunkRenderWorker.java @@ -43,7 +43,7 @@ public abstract class MixinChunkRenderWorker { ) ) private boolean isChunkExisting(ChunkRenderWorker worker, BlockPos pos, World world) { - if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) { + if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer()) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { diff --git a/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java b/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java index 22ab0bdd..f67d5d22 100644 --- a/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java +++ b/src/launch/java/baritone/launch/mixins/MixinRenderChunk.java @@ -47,7 +47,7 @@ public class MixinRenderChunk { if (!chunkCache.isEmpty()) { return false; } - if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) { + if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer()) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { @@ -76,7 +76,7 @@ public class MixinRenderChunk { ) ) private IBlockState getBlockState(ChunkCache chunkCache, BlockPos pos) { - if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) { + if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer()) { Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); IPlayerContext ctx = baritone.getPlayerContext(); if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { diff --git a/src/launch/java/baritone/launch/mixins/MixinRenderList.java b/src/launch/java/baritone/launch/mixins/MixinRenderList.java index 98ae5bf5..3efb3a10 100644 --- a/src/launch/java/baritone/launch/mixins/MixinRenderList.java +++ b/src/launch/java/baritone/launch/mixins/MixinRenderList.java @@ -38,7 +38,7 @@ public class MixinRenderList { ) ) private void popMatrix() { - if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) { + if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer()) { // reset the blend func to normal (not dependent on constant alpha) GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } diff --git a/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java b/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java index bab98b3c..cec62336 100644 --- a/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java +++ b/src/launch/java/baritone/launch/mixins/MixinVboRenderList.java @@ -38,7 +38,7 @@ public class MixinVboRenderList { ) ) private void popMatrix() { - if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) { + if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer()) { // reset the blend func to normal (not dependent on constant alpha) GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index 63d0b219..c277a0d0 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -62,7 +62,7 @@ public class WorldProvider implements IWorldProvider, Helper { IntegratedServer integratedServer = mc.getIntegratedServer(); // If there is an integrated server running (Aka Singleplayer) then do magic to find the world save file - if (integratedServer != null) { + if (mc.isSingleplayer()) { WorldServer localServerWorld = integratedServer.getWorld(dimension); IChunkProviderServer provider = (IChunkProviderServer) localServerWorld.getChunkProvider(); IAnvilChunkLoader loader = (IAnvilChunkLoader) provider.getChunkLoader(); From 7fa6593bdc38a54424b97dca108cc3c48e86fe03 Mon Sep 17 00:00:00 2001 From: 0x22 <0x22@futureclient.net> Date: Tue, 4 Jun 2019 01:02:54 -0400 Subject: [PATCH 438/682] Added the command delete. Allows you to remove a user defined waypoint. Fixes #334 --- .../baritone/api/utils/ExampleBaritoneControl.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 29b42d69..2445f634 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -68,6 +68,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener "get - Same as list\n" + "show - Same as list\n" + "save - Saves a waypoint (works but don't try to make sense of it)\n" + + "delete - Deletes a waypoint\n" + "goto - Paths towards specified block or waypoint\n" + "spawn - Paths towards world spawn or your most recent bed right-click\n" + "sethome - Sets \"home\"\n" + @@ -583,6 +584,17 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto " + name + "' to set goal, say 'list user' to list custom waypoints."); return true; } + if (msg.startsWith("delete")) { + String name = msg.substring(6).trim(); + IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getTag() == IWaypoint.Tag.USER && w.getName().equalsIgnoreCase(name)).findFirst().orElse(null); + if (waypoint == null) { + logDirect("No user defined position under the name '" + name + "' found."); + return true; + } + baritone.getWorldProvider().getCurrentWorld().getWaypoints().removeWaypoint(waypoint); + logDirect("Deleted user defined position under name '" + name + "'."); + return true; + } if (msg.startsWith("goto")) { String waypointType = msg.substring(4).trim(); if (waypointType.endsWith("s") && IWaypoint.Tag.fromString(waypointType.substring(0, waypointType.length() - 1)) != null) { From 1e43563cc36e9066c6ccdd3ec00c737d1113ce8b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 4 Jun 2019 20:55:31 -0700 Subject: [PATCH 439/682] fix weird backfill behavior --- src/main/java/baritone/pathing/movement/Movement.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index be29b988..5cb4fef9 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -147,10 +147,10 @@ public abstract class Movement implements IMovement, MovementHelper { } 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()); if (reachable.isPresent()) { Rotation rotTowardsBlock = reachable.get(); - MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, blockPos)); state.setTarget(new MovementState.MovementTarget(rotTowardsBlock, true)); if (ctx.isLookingAt(blockPos) || ctx.playerRotations().isReallyCloseTo(rotTowardsBlock)) { state.setInput(Input.CLICK_LEFT, true); From a1c03eb6016d2649f5f5b4b786c3e9745a5facf3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 5 Jun 2019 12:04:09 -0700 Subject: [PATCH 440/682] another tool selection fix --- src/main/java/baritone/pathing/movement/Movement.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 5cb4fef9..2ddcdc55 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -114,6 +114,7 @@ public abstract class Movement implements IMovement, MovementHelper { currentState.setInput(Input.JUMP, true); } if (ctx.player().isEntityInsideOpaqueBlock()) { + ctx.getSelectedBlock().ifPresent(pos -> MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, pos))); currentState.setInput(Input.CLICK_LEFT, true); } From 0815e3c1951e78e505bfa69f41e84e6a56204f27 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 5 Jun 2019 12:08:19 -0700 Subject: [PATCH 441/682] thank u intellij very cool suggestion --- .../baritone/pathing/movement/movements/MovementPillar.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 1d849353..4b8f18cf 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -37,7 +37,6 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import java.util.Objects; -import java.util.Optional; public class MovementPillar extends Movement { @@ -240,10 +239,7 @@ public class MovementPillar extends Movement { Block fr = frState.getBlock(); // TODO: Evaluate usage of getMaterial().isReplaceable() if (!(fr instanceof BlockAir || frState.getMaterial().isReplaceable())) { - Optional reachable = RotationUtils.reachable(ctx.player(), src, ctx.playerController().getBlockReachDistance()); - if (reachable.isPresent()) { - state.setTarget(new MovementState.MovementTarget(reachable.get(), true)); - } + RotationUtils.reachable(ctx.player(), 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 state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; From a6ea9ed3a624eb6fa4e92ebc120802a287132b2c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 5 Jun 2019 12:47:18 -0700 Subject: [PATCH 442/682] =?UTF-8?q?=F0=9F=91=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../baritone/pathing/movement/movements/MovementPillar.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 4b8f18cf..5e4a409f 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -239,7 +239,9 @@ public class MovementPillar extends Movement { 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()).map(rot -> new MovementState.MovementTarget(rot, true)).ifPresent(state::setTarget); + RotationUtils.reachable(ctx.player(), 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 state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; From aef84eceb8e5e3c581a6774feff0fa27fd307d3d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 5 Jun 2019 14:26:26 -0700 Subject: [PATCH 443/682] fix a rare crash when the view is occluded by falling sand, fixes #443 --- .../baritone/pathing/movement/movements/MovementTraverse.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index a9266f14..07eb20b7 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -169,6 +169,10 @@ public class MovementTraverse extends Movement { if (dist < 0.83) { return state; } + if (!state.getTarget().getRotation().isPresent()) { + // this can happen rarely when the server lags and doesn't send the falling sand entity until you've already walked through the block and are now mining the next one + return state; + } // combine the yaw to the center of the destination, and the pitch to the specific block we're trying to break // it's safe to do this since the two blocks we break (in a traverse) are right on top of each other and so will have the same yaw From f0210f7c5f4c134e1ca64d4cd0a2438e42e95333 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 5 Jun 2019 22:12:28 -0700 Subject: [PATCH 444/682] add an additional underscore --- src/main/java/baritone/pathing/movement/Movement.java | 2 +- src/main/java/baritone/pathing/movement/MovementHelper.java | 4 ++-- .../baritone/pathing/movement/movements/MovementAscend.java | 6 +++--- .../pathing/movement/movements/MovementParkour.java | 6 +++--- .../pathing/movement/movements/MovementTraverse.java | 6 +++--- src/main/java/baritone/process/BuilderProcess.java | 2 +- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 2ddcdc55..75c93dca 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -36,7 +36,7 @@ import java.util.Optional; public abstract class Movement implements IMovement, MovementHelper { - public static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN}; + public static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN}; protected final IBaritone baritone; protected final IPlayerContext ctx; diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index d8f6a2f7..60b36119 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -37,7 +37,7 @@ import net.minecraft.util.math.Vec3d; import java.util.Optional; -import static baritone.pathing.movement.Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP; +import static baritone.pathing.movement.Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP; /** * Static helpers for cost calculation @@ -499,7 +499,7 @@ public interface MovementHelper extends ActionCosts, Helper { found = true; } for (int i = 0; i < 5; i++) { - BlockPos against1 = placeAt.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); + BlockPos against1 = placeAt.offset(HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i]); if (MovementHelper.canPlaceAgainst(ctx, against1)) { if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(false, placeAt.getX(), placeAt.getY(), placeAt.getZ())) { // get ready to place a throwaway block Helper.HELPER.logDebug("bb pls get me some blocks. dirt, netherrack, cobble"); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index b37fd4d0..6d5ecd85 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -64,9 +64,9 @@ public class MovementAscend extends Movement { } boolean foundPlaceOption = false; for (int i = 0; i < 5; i++) { - int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); - int againstY = y + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getYOffset(); - int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getZOffset(); + int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); + int againstY = y + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getYOffset(); + int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getZOffset(); if (againstX == x && againstZ == z) { // we might be able to backplace now, but it doesn't matter because it will have been broken by the time we'd need to use it continue; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index fbf57e6c..dfa43a05 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -134,9 +134,9 @@ public class MovementParkour extends Movement { return; } for (int i = 0; i < 5; i++) { - int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); - int againstY = y - 1 + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getYOffset(); - int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getZOffset(); + int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); + int againstY = y - 1 + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getYOffset(); + int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getZOffset(); if (againstX == x + xDiff * 3 && againstZ == z + zDiff * 3) { // we can't turn around that fast continue; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 07eb20b7..d6137027 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -119,9 +119,9 @@ public class MovementTraverse extends Movement { double hardness2 = MovementHelper.getMiningDurationTicks(context, destX, y + 1, destZ, pb0, true); // only include falling on the upper block to break double WC = throughWater ? context.waterWalkSpeed : WALK_ONE_BLOCK_COST; for (int i = 0; i < 5; i++) { - int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); - int againstY = y - 1 + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getYOffset(); - int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getZOffset(); + int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); + int againstY = y - 1 + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getYOffset(); + int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getZOffset(); if (againstX == x && againstZ == z) { // this would be a backplace continue; } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 6c921f8e..29f61a7d 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -602,7 +602,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil return new GoalPlace(pos); } boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR; - for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP) { + for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) { if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ()).getBlock(), pos, false, facing, null)) { return new GoalAdjacent(pos, allowSameLevel); } From 4c4bc8058b26add8fbc0c264a283077997a8ccbc Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 6 Jun 2019 04:15:43 -0500 Subject: [PATCH 445/682] Some clean ups --- .../java/baritone/pathing/calc/AStarPathFinder.java | 3 +-- src/main/java/baritone/pathing/calc/Path.java | 2 +- src/main/java/baritone/utils/pathing/Avoidance.java | 7 +++++-- .../baritone/utils/pathing/SegmentedCalculator.java | 12 ++++++------ .../baritone/pathing/calc/openset/OpenSetsTest.java | 10 +++++----- 5 files changed, 18 insertions(+), 16 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index 57e9200d..fc964d0f 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -86,8 +86,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch { if (slowPath) { try { Thread.sleep(Baritone.settings().slowPathTimeDelayMS.value); - } catch (InterruptedException ex) { - } + } catch (InterruptedException ignored) {} } PathNode currentNode = openSet.removeLowest(); mostRecentConsidered = currentNode; diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index a3f9dd22..76cd8396 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -96,7 +96,7 @@ class Path extends PathBase { } PathNode current = end; LinkedList tempPath = new LinkedList<>(); - LinkedList tempNodes = new LinkedList(); + LinkedList tempNodes = new LinkedList<>(); // Repeatedly inserting to the beginning of an arraylist is O(n^2) // Instead, do it into a linked list, then convert at the end while (current != null) { diff --git a/src/main/java/baritone/utils/pathing/Avoidance.java b/src/main/java/baritone/utils/pathing/Avoidance.java index 9b32b1df..c4b12336 100644 --- a/src/main/java/baritone/utils/pathing/Avoidance.java +++ b/src/main/java/baritone/utils/pathing/Avoidance.java @@ -64,10 +64,13 @@ public class Avoidance { double mobSpawnerCoeff = Baritone.settings().mobSpawnerAvoidanceCoefficient.value; double mobCoeff = Baritone.settings().mobAvoidanceCoefficient.value; if (mobSpawnerCoeff != 1.0D) { - ctx.worldData().getCachedWorld().getLocationsOf("mob_spawner", 1, ctx.playerFeet().x, ctx.playerFeet().z, 2).forEach(mobspawner -> res.add(new Avoidance(mobspawner, mobSpawnerCoeff, Baritone.settings().mobSpawnerAvoidanceRadius.value))); + ctx.worldData().getCachedWorld().getLocationsOf("mob_spawner", 1, ctx.playerFeet().x, ctx.playerFeet().z, 2) + .forEach(mobspawner -> res.add(new Avoidance(mobspawner, mobSpawnerCoeff, Baritone.settings().mobSpawnerAvoidanceRadius.value))); } if (mobCoeff != 1.0D) { - ctx.world().loadedEntityList.stream().filter(entity -> entity instanceof EntityMob).forEach(entity -> res.add(new Avoidance(new BlockPos(entity), mobCoeff, Baritone.settings().mobAvoidanceRadius.value))); + ctx.world().loadedEntityList.stream() + .filter(entity -> entity instanceof EntityMob) + .forEach(entity -> res.add(new Avoidance(new BlockPos(entity), mobCoeff, Baritone.settings().mobAvoidanceRadius.value))); } return res; } diff --git a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java index 757ea015..c1753a8b 100644 --- a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java +++ b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java @@ -51,7 +51,7 @@ public class SegmentedCalculator { private Optional doCalc() { Optional soFar = Optional.empty(); while (true) { - PathCalculationResult result = segment(soFar); + PathCalculationResult result = segment(soFar.orElse(null)); switch (result.getType()) { case SUCCESS_SEGMENT: case SUCCESS_TO_GOAL: @@ -62,8 +62,8 @@ public class SegmentedCalculator { default: // CANCELLATION and null should not be possible, nothing else has access to this, so it can't have been canceled throw new IllegalStateException(); } - IPath segment = result.getPath().get(); // path calculation result type is SUCCESS_SEGMENT, so the path must be present - IPath combined = soFar.map(previous -> (IPath) SplicedPath.trySplice(previous, segment, true).get()).orElse(segment); + IPath segment = result.getPath().orElseThrow(IllegalStateException::new); // path calculation result type is SUCCESS_SEGMENT, so the path must be present + IPath combined = soFar.map(previous -> (IPath) SplicedPath.trySplice(previous, segment, true).orElseThrow(IllegalStateException::new)).orElse(segment); loadAdjacent(combined.getDest().getX(), combined.getDest().getZ()); soFar = Optional.of(combined); if (result.getType() == PathCalculationResult.Type.SUCCESS_TO_GOAL) { @@ -85,9 +85,9 @@ public class SegmentedCalculator { } } - private PathCalculationResult segment(Optional previous) { - BetterBlockPos segmentStart = previous.map(IPath::getDest).orElse(start); // <-- e p i c - AbstractNodeCostSearch search = new AStarPathFinder(segmentStart.x, segmentStart.y, segmentStart.z, goal, new Favoring(previous.orElse(null), context), context); // this is on another thread, so cannot include mob avoidances. + private PathCalculationResult segment(IPath previous) { + BetterBlockPos segmentStart = previous != null ? previous.getDest() : start; + AbstractNodeCostSearch search = new AStarPathFinder(segmentStart.x, segmentStart.y, segmentStart.z, goal, new Favoring(previous, context), context); // this is on another thread, so cannot include mob avoidances. return search.calculate(Baritone.settings().primaryTimeoutMS.value, Baritone.settings().failureTimeoutMS.value); // use normal time settings, not the plan ahead settings, so as to not overwhelm the computer } diff --git a/src/test/java/baritone/pathing/calc/openset/OpenSetsTest.java b/src/test/java/baritone/pathing/calc/openset/OpenSetsTest.java index a12e0b7a..33a1f4dc 100644 --- a/src/test/java/baritone/pathing/calc/openset/OpenSetsTest.java +++ b/src/test/java/baritone/pathing/calc/openset/OpenSetsTest.java @@ -50,14 +50,14 @@ public class OpenSetsTest { return testSizes; } - private static void removeAndTest(int amount, IOpenSet[] test, Optional> mustContain) { + private static void removeAndTest(int amount, IOpenSet[] test, Collection mustContain) { double[][] results = new double[test.length][amount]; for (int i = 0; i < test.length; i++) { long before = System.nanoTime() / 1000000L; for (int j = 0; j < amount; j++) { PathNode pn = test[i].removeLowest(); - if (mustContain.isPresent() && !mustContain.get().contains(pn)) { - throw new IllegalStateException(mustContain.get() + " " + pn); + if (mustContain != null && !mustContain.contains(pn)) { + throw new IllegalStateException(mustContain + " " + pn); } results[i][j] = pn.combinedCost; } @@ -131,7 +131,7 @@ public class OpenSetsTest { System.out.println("Removal round 1"); // remove a quarter of the nodes and verify that they are indeed the size/4 lowest ones - removeAndTest(size / 4, test, Optional.of(lowestQuarter)); + removeAndTest(size / 4, test, lowestQuarter); // none of them should be empty (sanity check) for (IOpenSet set : test) { @@ -160,7 +160,7 @@ public class OpenSetsTest { System.out.println("Removal round 2"); // remove the remaining 3/4 - removeAndTest(size - size / 4, test, Optional.empty()); + removeAndTest(size - size / 4, test, null); // every set should now be empty for (IOpenSet set : test) { From ce606f826b1ea3939c9a228d159de6c4b56799ed Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 6 Jun 2019 19:05:13 -0500 Subject: [PATCH 446/682] consistency --- .../pathing/movement/movements/MovementTraverse.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index d6137027..1b19ae57 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -195,13 +195,13 @@ public class MovementTraverse extends Movement { boolean door = pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor; if (door) { - boolean isDoorActuallyBlockingUs = false; + boolean blocked = false; if (pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, src, dest)) { - isDoorActuallyBlockingUs = true; + blocked = true; } else if (pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, dest, src)) { - isDoorActuallyBlockingUs = true; + blocked = true; } - if (isDoorActuallyBlockingUs && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { + if (blocked && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0]), ctx.playerRotations()), true)) .setInput(Input.CLICK_RIGHT, true); } From 9822962d9802b1b0a5319c573e0bb0c34bfbec95 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 6 Jun 2019 23:54:52 -0700 Subject: [PATCH 447/682] it is tbh --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5eb0c920..35ed316e 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.6%20/%20v1.3.2-brightgreen.svg)](https://impactdevelopment.github.io/) -[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-v1.2.*-green.svg)](https://github.com/fr1kin/ForgeHax) +[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com) From 81d7f3c31926cdb883354bf25fe1b23f77a038eb Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 7 Jun 2019 03:18:58 -0500 Subject: [PATCH 448/682] crucial performance optimization --- .../movement/movements/MovementTraverse.java | 30 +++++++------------ 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 1b19ae57..39fbab75 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -183,8 +183,9 @@ public class MovementTraverse extends Movement { pitchToBreak = 26; } - state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true)); - return state.setInput(Input.MOVE_FORWARD, true).setInput(Input.SPRINT, true); + return state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true)) + .setInput(Input.MOVE_FORWARD, true) + .setInput(Input.SPRINT, true); } //sneak may have been set to true in the PREPPING state while mining an adjacent block @@ -193,28 +194,19 @@ public class MovementTraverse extends Movement { Block fd = BlockStateInterface.get(ctx, src.down()).getBlock(); boolean ladder = fd == Blocks.LADDER || fd == Blocks.VINE; - boolean door = pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor; - if (door) { - boolean blocked = false; - if (pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, src, dest)) { - blocked = true; - } else if (pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, dest, src)) { - blocked = true; - } - if (blocked && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { + if (pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor) { + if ((pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, src, dest) + || pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, dest, src)) + && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0]), ctx.playerRotations()), true)) .setInput(Input.CLICK_RIGHT, true); } } if (pb0.getBlock() instanceof BlockFenceGate || pb1.getBlock() instanceof BlockFenceGate) { - BlockPos blocked = null; - if (!MovementHelper.isGatePassable(ctx, positionsToBreak[0], src.up())) { - blocked = positionsToBreak[0]; - } else if (!MovementHelper.isGatePassable(ctx, positionsToBreak[1], src)) { - blocked = positionsToBreak[1]; - } - + BlockPos blocked = !MovementHelper.isGatePassable(ctx, positionsToBreak[0], src.up()) ? positionsToBreak[0] + : !MovementHelper.isGatePassable(ctx, positionsToBreak[1], src) ? positionsToBreak[1] + : null; if (blocked != null) { return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), blocked), ctx.playerRotations()), true)) .setInput(Input.CLICK_RIGHT, true); @@ -226,7 +218,7 @@ public class MovementTraverse extends Movement { if (whereAmI.getY() != dest.getY() && !ladder) { logDebug("Wrong Y coordinate"); if (whereAmI.getY() < dest.getY()) { - state.setInput(Input.JUMP, true); + return state.setInput(Input.JUMP, true); } return state; } From ee6796d5e28338a3020549131922c8db0b7e6ae7 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 7 Jun 2019 03:52:46 -0500 Subject: [PATCH 449/682] crucial performance optimization (pt. 2) --- .../movement/movements/MovementTraverse.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 39fbab75..b621632c 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -214,17 +214,16 @@ public class MovementTraverse extends Movement { } boolean isTheBridgeBlockThere = MovementHelper.canWalkOn(ctx, positionToPlace) || ladder; - BlockPos whereAmI = ctx.playerFeet(); - if (whereAmI.getY() != dest.getY() && !ladder) { + BlockPos feet = ctx.playerFeet(); + if (feet.getY() != dest.getY() && !ladder) { logDebug("Wrong Y coordinate"); - if (whereAmI.getY() < dest.getY()) { + if (feet.getY() < dest.getY()) { return state.setInput(Input.JUMP, true); } return state; } if (isTheBridgeBlockThere) { - BetterBlockPos feet = ctx.playerFeet(); if (feet.equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } @@ -241,20 +240,20 @@ public class MovementTraverse extends Movement { BlockPos into = dest.subtract(src).add(dest); Block intoBelow = BlockStateInterface.get(ctx, into).getBlock(); Block intoAbove = BlockStateInterface.get(ctx, into.up()).getBlock(); - if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, ctx.playerFeet()) || Baritone.settings().sprintInWater.value) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) { + if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, feet) || Baritone.settings().sprintInWater.value) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) { state.setInput(Input.SPRINT, true); } IBlockState destDown = BlockStateInterface.get(ctx, dest.down()); BlockPos against = positionsToBreak[0]; - if (whereAmI.getY() != dest.getY() && ladder && (destDown.getBlock() == Blocks.VINE || destDown.getBlock() == Blocks.LADDER)) { + if (feet.getY() != dest.getY() && ladder && (destDown.getBlock() == Blocks.VINE || destDown.getBlock() == Blocks.LADDER)) { against = destDown.getBlock() == Blocks.VINE ? MovementPillar.getAgainst(new CalculationContext(baritone), dest.down()) : dest.offset(destDown.getValue(BlockLadder.FACING).getOpposite()); } MovementHelper.moveTowards(ctx, state, against); return state; } else { wasTheBridgeBlockAlwaysThere = false; - Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock(); + Block standingOn = BlockStateInterface.get(ctx, feet.down()).getBlock(); if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); if (dist < 0.85) { // 0.5 + 0.3 + epsilon @@ -292,7 +291,7 @@ public class MovementTraverse extends Movement { default: break; } - if (whereAmI.equals(dest)) { + if (feet.equals(dest)) { // If we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of // Out.log(from + " " + to + " " + faceX + "," + faceY + "," + faceZ + " " + whereAmI); double faceX = (dest.getX() + src.getX() + 1.0D) * 0.5D; From 1ee6e04f00abad1be946a9dd362075d2dbf4617e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 7 Jun 2019 20:20:49 -0700 Subject: [PATCH 450/682] this counts as a commit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35ed316e..999e1040 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Baritone is the pathfinding system used in [Impact](https://impactdevelopment.gi 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 and 1.13.2. 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). -Have committed at least once a day for the last 8 months =D 🦀 +Have committed at least once a day for the last 10 months =D 🦀 1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2 From 14bb0a0a80c034af819e16df1edaf59d67187560 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 8 Jun 2019 23:13:27 -0700 Subject: [PATCH 451/682] alt text --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 999e1040..fab6ced9 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ [![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/) ![Code size](https://img.shields.io/github/languages/code-size/cabaletta/baritone.svg) ![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg) -![](https://tokei.rs/b1/github/cabaletta/baritone?category=code) +![Lines of Code](https://tokei.rs/b1/github/cabaletta/baritone?category=code) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.6%20/%20v1.3.2-brightgreen.svg)](https://impactdevelopment.github.io/) From 94bf703dde237159d0dc082cb5550a80fbb91c70 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 9 Jun 2019 23:56:54 -0700 Subject: [PATCH 452/682] this counts as a commit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fab6ced9..ff6b83ef 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAnd ## Can I use Baritone as a library in my custom utility client? -That's what it's for, sure! (As long as usage is in compliance with the LGPL 3 License) +That's what it's for, sure! (As long as usage is in compliance with the LGPL 3.0 License) ## How is it so fast? From 86525f98ec9dfdf4531fb115c8e8cd33a5d912b1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 10 Jun 2019 23:12:37 -0700 Subject: [PATCH 453/682] fix scuffed jumping, fixes #426 --- 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 1e138290..01a460d4 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -114,7 +114,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro .filter(pos -> !(BlockStateInterface.get(ctx, pos).getBlock() instanceof BlockAir)) // after breaking a block, it takes mineGoalUpdateInterval ticks for it to actually update this list =( .min(Comparator.comparingDouble(ctx.player()::getDistanceSq)); baritone.getInputOverrideHandler().clearAllKeys(); - if (shaft.isPresent()) { + if (shaft.isPresent() && ctx.player().onGround) { BlockPos pos = shaft.get(); IBlockState state = baritone.bsi.get0(pos); if (!MovementHelper.avoidBreaking(baritone.bsi, pos.getX(), pos.getY(), pos.getZ(), state)) { From eb6c0a39ea9756b3f26a41f74db14988b51769a0 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 11 Jun 2019 23:46:04 -0700 Subject: [PATCH 454/682] codacy wants this --- src/main/java/baritone/process/ExploreProcess.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index aa7e2c2a..54c2a698 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -122,6 +122,7 @@ public final class ExploreProcess extends BaritoneProcessHelper implements IExpl break; // note: this breaks the switch not the for case EXPLORED: continue; // note: this continues the for + default: } int centerX = ((chunkX + dx) << 4) + 8; int centerZ = ((chunkZ + dz) << 4) + 8; From e785bd13f5624402a25eea5e900581ba41a29696 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 12 Jun 2019 16:41:05 -0700 Subject: [PATCH 455/682] sanity check --- src/main/java/baritone/cache/CachedWorld.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 7c8e4291..f07c1148 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -303,6 +303,8 @@ public final class CachedWorld implements ICachedWorld, Helper { } catch (InterruptedException e) { e.printStackTrace(); break; + } catch (Throwable th) { + th.printStackTrace(); } } } From cc015846d27e4388a195df533c686af2de5a2814 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 13 Jun 2019 23:13:40 -0700 Subject: [PATCH 456/682] explain --- src/main/java/baritone/cache/CachedWorld.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index f07c1148..237c460b 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -304,6 +304,7 @@ public final class CachedWorld implements ICachedWorld, Helper { e.printStackTrace(); break; } catch (Throwable th) { + // in the case of an exception, keep consuming from the queue so as not to leak memory th.printStackTrace(); } } From 7b192f17e85a11a2d0d301ae53d9846f77efa21e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 14 Jun 2019 21:42:11 -0700 Subject: [PATCH 457/682] privatize --- src/main/java/baritone/utils/GuiClick.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index 0b412b92..480da707 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -121,7 +121,7 @@ public class GuiClick extends GuiScreen { } } - public Vec3d toWorld(double x, double y, double z) { + private Vec3d toWorld(double x, double y, double z) { boolean result = GLU.gluUnProject((float) x, (float) y, (float) z, MODELVIEW, PROJECTION, VIEWPORT, (FloatBuffer) TO_WORLD_BUFFER.clear()); if (result) { return new Vec3d(TO_WORLD_BUFFER.get(0), TO_WORLD_BUFFER.get(1), TO_WORLD_BUFFER.get(2)); From 0fd241a9ba23e48171d70dedd768532b8b607a31 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 15 Jun 2019 11:04:05 -0700 Subject: [PATCH 458/682] crucial performance optimization --- src/main/java/baritone/BaritoneProvider.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index 73e5e6e5..44715f4c 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -32,6 +32,7 @@ import java.util.List; public final class BaritoneProvider implements IBaritoneProvider { private final Baritone primary = new Baritone(); + private final List all = Collections.singletonList(primary); @Override public IBaritone getPrimaryBaritone() { @@ -40,8 +41,7 @@ public final class BaritoneProvider implements IBaritoneProvider { @Override public List getAllBaritones() { - // TODO return a CopyOnWriteArrayList - return Collections.singletonList(primary); + return all; } @Override From be142d79bce195e9ce2daafea3e55b6e30196994 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 16 Jun 2019 23:06:57 -0700 Subject: [PATCH 459/682] link to the code --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ff6b83ef..bc1fc94c 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,8 @@ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) [![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) [![GitHub All Releases](https://img.shields.io/github/downloads/cabaletta/baritone/total.svg)](https://github.com/cabaletta/baritone/releases) -[![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) -[![Minecraft](https://img.shields.io/badge/MC-1.13.2-brightgreen.svg)](https://minecraft.gamepedia.com/1.13.2) +[![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://github.com/cabaletta/baritone/tree/master/) +[![Minecraft](https://img.shields.io/badge/MC-1.13.2-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.13.2/) [![Code of Conduct](https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg?style=flat)](https://github.com/cabaletta/baritone/blob/master/CODE_OF_CONDUCT.md) [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) [![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) From 96097ab7265f3219efef4231c4ce36b8251ac8ac Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 17 Jun 2019 22:44:38 -0700 Subject: [PATCH 460/682] this counts as a commit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc1fc94c..42dba624 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.6%20/%20v1.3.2-brightgreen.svg)](https://impactdevelopment.github.io/) -[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax) +[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com) From b3605546ac913072fe7700f83761810732eb60ef Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 18 Jun 2019 23:15:47 -0700 Subject: [PATCH 461/682] golly another missing slash wow --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 42dba624..9c080826 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) -[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com) +[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com/) [![forthebadge](https://forthebadge.com/images/badges/mom-made-pizza-rolls.svg)](http://forthebadge.com) A Minecraft pathfinder bot. From 2b9084d2f3ce140c5783a3c869422347aa33c926 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 19 Jun 2019 20:41:21 -0700 Subject: [PATCH 462/682] wow --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c080826..0a8c713f 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com/) -[![forthebadge](https://forthebadge.com/images/badges/mom-made-pizza-rolls.svg)](http://forthebadge.com) +[![forthebadge](https://forthebadge.com/images/badges/mom-made-pizza-rolls.svg)](http://forthebadge.com/) A Minecraft pathfinder bot. From f998dce61496002b1810390823511a247f823276 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 20 Jun 2019 23:48:02 -0700 Subject: [PATCH 463/682] wow wow --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0a8c713f..ad14e174 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Here are some links to help to get started: # API -The API is heavily documented, you can find the Javadocs for the latest release [here](https://baritone.leijurv.com). +The API is heavily documented, you can find the Javadocs for the latest release [here](https://baritone.leijurv.com/). Please note that usage of anything located outside of the ``baritone.api`` package is not supported by the API release jar. From 4ff61f96dff505e554625a6b2bdcefd0ef066640 Mon Sep 17 00:00:00 2001 From: SylveonBottle Date: Fri, 21 Jun 2019 03:59:10 -0500 Subject: [PATCH 464/682] wow times infinity --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ad14e174..9a25789a 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,15 @@ # Baritone -[![Build Status](https://travis-ci.com/cabaletta/baritone.svg?branch=master)](https://travis-ci.com/cabaletta/baritone) -[![Release](https://img.shields.io/github/release/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/releases) +[![Build Status](https://travis-ci.com/cabaletta/baritone.svg?branch=master)](https://travis-ci.com/cabaletta/baritone/) +[![Release](https://img.shields.io/github/release/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/releases/) [![License](https://img.shields.io/badge/license-LGPL--3.0%20with%20anime%20exception-green.svg)](LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) -[![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone) -[![GitHub All Releases](https://img.shields.io/github/downloads/cabaletta/baritone/total.svg)](https://github.com/cabaletta/baritone/releases) +[![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone/) +[![GitHub All Releases](https://img.shields.io/github/downloads/cabaletta/baritone/total.svg)](https://github.com/cabaletta/baritone/releases/) [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://github.com/cabaletta/baritone/tree/master/) [![Minecraft](https://img.shields.io/badge/MC-1.13.2-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.13.2/) [![Code of Conduct](https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg?style=flat)](https://github.com/cabaletta/baritone/blob/master/CODE_OF_CONDUCT.md) [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) -[![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues) +[![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues/) [![Issues](https://img.shields.io/github/issues/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues/) [![GitHub issues-closed](https://img.shields.io/github/issues-closed/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues?q=is%3Aissue+is%3Aclosed) [![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/) @@ -44,7 +44,7 @@ Here are some links to help to get started: - [Installation & setup](SETUP.md) -- [API Javadocs](https://baritone.leijurv.com) +- [API Javadocs](https://baritone.leijurv.com/) - [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#field.detail) @@ -73,7 +73,7 @@ That's what it's for, sure! (As long as usage is in compliance with the LGPL 3.0 ## How is it so fast? -Magic. (Hours of [leijurv](https://github.com/leijurv) enduring excruciating pain) +Magic. (Hours of [leijurv](https://github.com/leijurv/) enduring excruciating pain) ## Why is it called Baritone? From 3902b2db3b3cd25029d00b18cc57b703265681dd Mon Sep 17 00:00:00 2001 From: Babbaj Date: Fri, 21 Jun 2019 23:01:37 -0400 Subject: [PATCH 465/682] increase line count and improve readability --- src/main/java/baritone/process/FollowProcess.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 12188729..4defff5d 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -82,7 +82,12 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo } private void scanWorld() { - cache = Stream.of(ctx.world().loadedEntityList, ctx.world().playerEntities).flatMap(List::stream).filter(this::followable).filter(this.filter).distinct().collect(Collectors.toCollection(ArrayList::new)); + cache = Stream.of(ctx.world().loadedEntityList, ctx.world().playerEntities) + .flatMap(List::stream) + .filter(this::followable) + .filter(this.filter) + .distinct() + .collect(Collectors.toCollection(ArrayList::new)); } @Override From fa71e7d84fb1c59ea18eb48062cae995edb4c9c9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 22 Jun 2019 21:11:09 -0700 Subject: [PATCH 466/682] reduce stupidity --- src/main/java/baritone/process/BuilderProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 29f61a7d..52f21b76 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -154,7 +154,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil continue; // irrelevant } IBlockState curr = bcc.bsi.get0(x, y, z); - if (curr.getBlock() != Blocks.AIR && !valid(curr, desired)) { + if (curr.getBlock() != Blocks.AIR && !(curr.getBlock() instanceof BlockLiquid) && !valid(curr, desired)) { BetterBlockPos pos = new BetterBlockPos(x, y, z); Optional rot = RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()); if (rot.isPresent()) { From ce3d3bb244b37646a7fc85540e3a08d2100ad6f1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 23 Jun 2019 22:49:33 -0700 Subject: [PATCH 467/682] literally no reason to have this --- .../baritone/pathing/path/PathExecutor.java | 32 ------------------- 1 file changed, 32 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 852ac44e..d219dfc2 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -147,38 +147,6 @@ public class PathExecutor implements IPathExecutor, Helper { cancel(); return false; } - //this commented block is literally cursed. - /*Out.log(actions.get(pathPosition)); - if (pathPosition < actions.size() - 1) {//if there are two ActionBridges in a row and they are at right angles, walk diagonally. This makes it so you walk at 45 degrees along a zigzag path instead of doing inefficient zigging and zagging - if ((actions.get(pathPosition) instanceof ActionBridge) && (actions.get(pathPosition + 1) instanceof ActionBridge)) { - ActionBridge curr = (ActionBridge) actions.get(pathPosition); - ActionBridge next = (ActionBridge) actions.get(pathPosition + 1); - if (curr.dx() != next.dx() || curr.dz() != next.dz()) {//two movement are not parallel, so this is a right angle - if (curr.amIGood() && next.amIGood()) {//nothing in the way - BlockPos cornerToCut1 = new BlockPos(next.to.getX() - next.from.getX() + curr.from.getX(), next.to.getY(), next.to.getZ() - next.from.getZ() + curr.from.getZ()); - BlockPos cornerToCut2 = cornerToCut1.up(); - //Block corner1 = Baritone.get(cornerToCut1).getBlock(); - //Block corner2 = Baritone.get(cornerToCut2).getBlock(); - //Out.gui("Cutting conner " + cornerToCut1 + " " + corner1, Out.Mode.Debug); - if (!Action.avoidWalkingInto(cornerToCut1) && !Action.avoidWalkingInto(cornerToCut2)) { - double x = (next.from.getX() + next.to.getX() + 1.0D) * 0.5D; - double z = (next.from.getZ() + next.to.getZ() + 1.0D) * 0.5D; - MovementManager.clearMovement(); - if (!MovementManager.forward && curr.oneInTen != null && curr.oneInTen) { - MovementManager.clearMovement(); - MovementManager.forward = LookManager.lookAtCoords(x, 0, z, false); - } else { - MovementManager.moveTowardsCoords(x, 0, z); - } - if (MovementManager.forward && !MovementManager.backward) { - thePlayer.setSprinting(true); - } - return false; - } - } - } - } - }*/ //long start = System.nanoTime() / 1000000L; BlockStateInterface bsi = new BlockStateInterface(ctx); for (int i = pathPosition - 10; i < pathPosition + 10; i++) { From f4d2ea7923b0422943040d30066860af1dc25f6f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 24 Jun 2019 10:43:49 -0700 Subject: [PATCH 468/682] fix path canceling at edge of loaded chunks hopefully --- src/main/java/baritone/pathing/path/PathExecutor.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index d219dfc2..7b9ba9ee 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -188,6 +188,11 @@ public class PathExecutor implements IPathExecutor, Helper { System.out.println("Recalculating break and place took " + (end - start) + "ms"); }*/ IMovement movement = path.movements().get(pathPosition); + if (!behavior.baritone.bsi.worldContainsLoadedChunk(movement.getDest().x, movement.getDest().z)) { + logDebug("Pausing since destination is at edge of loaded chunks"); + clearKeys(); + return true; + } boolean canCancel = movement.safeToCancel(); if (costEstimateIndex == null || costEstimateIndex != pathPosition) { costEstimateIndex = pathPosition; From 9c64067d492e3fdd7d255bdf39092524046f7121 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 24 Jun 2019 17:53:25 -0700 Subject: [PATCH 469/682] vastly improve resilience to lagbacks, fixes #446 --- .../baritone/pathing/movement/Movement.java | 16 +++++-- .../movement/movements/MovementAscend.java | 22 +++++++-- .../movement/movements/MovementDescend.java | 8 ++++ .../movement/movements/MovementDiagonal.java | 19 ++++++-- .../movement/movements/MovementDownward.java | 10 ++++ .../movement/movements/MovementFall.java | 12 +++++ .../movement/movements/MovementParkour.java | 14 ++++++ .../movement/movements/MovementPillar.java | 7 +++ .../movement/movements/MovementTraverse.java | 12 ++++- .../baritone/pathing/path/PathExecutor.java | 46 ++++++++++--------- 10 files changed, 132 insertions(+), 34 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 75c93dca..6907c426 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -30,9 +30,7 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; +import java.util.*; public abstract class Movement implements IMovement, MovementHelper { @@ -63,6 +61,8 @@ public abstract class Movement implements IMovement, MovementHelper { public List toPlaceCached = null; public List toWalkIntoCached = null; + private Set validPositionsCached = null; + private Boolean calculatedWhileLoaded; protected Movement(IBaritone baritone, BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak, BetterBlockPos toPlace) { @@ -100,6 +100,16 @@ public abstract class Movement implements IMovement, MovementHelper { this.cost = cost; } + protected abstract Set calculateValidPositions(); + + public Set getValidPositions() { + if (validPositionsCached == null) { + validPositionsCached = calculateValidPositions(); + Objects.requireNonNull(validPositionsCached); + } + return validPositionsCached; + } + /** * Handles the execution of the latest Movement * State, and offers a Status to the calling class. diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 6d5ecd85..24fe2285 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -27,11 +27,14 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; +import com.google.common.collect.ImmutableSet; import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; +import java.util.Set; + public class MovementAscend extends Movement { private int ticksWithoutPlacement = 0; @@ -51,6 +54,17 @@ public class MovementAscend extends Movement { return cost(context, src.x, src.y, src.z, dest.x, dest.z); } + @Override + protected Set calculateValidPositions() { + BetterBlockPos prior = new BetterBlockPos(src.subtract(getDirection()).up()); // sometimes we back up to place the block, also sprint ascends, also skip descend to straight ascend + return ImmutableSet.of(src, + src.up(), + dest, + prior, + prior.up() + ); + } + public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) { IBlockState toPlace = context.get(destX, y, destZ); double additionalPlacementCost = 0; @@ -143,6 +157,10 @@ public class MovementAscend extends Movement { @Override public MovementState updateState(MovementState state) { + if (ctx.playerFeet().y < src.y) { + // this check should run even when in preparing state (breaking blocks) + return state.setStatus(MovementStatus.UNREACHABLE); + } super.updateState(state); // TODO incorporate some behavior from ActionClimb (specifically how it waited until it was at most 1.2 blocks away before starting to jump // for efficiency in ascending minimal height staircases, which is just repeated MovementAscend, so that it doesn't bonk its head on the ceiling repeatedly) @@ -154,10 +172,6 @@ public class MovementAscend extends Movement { return state.setStatus(MovementStatus.SUCCESS); } - if (ctx.playerFeet().y < src.y) { - return state.setStatus(MovementStatus.UNREACHABLE); - } - IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace); if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) { ticksWithoutPlacement++; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index a73ed4fb..67b7cd95 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -29,6 +29,7 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; import baritone.utils.pathing.MutableMoveResult; +import com.google.common.collect.ImmutableSet; import net.minecraft.block.Block; import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; @@ -37,6 +38,8 @@ import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; +import java.util.Set; + public class MovementDescend extends Movement { private int numTicks = 0; @@ -61,6 +64,11 @@ public class MovementDescend extends Movement { return result.cost; } + @Override + protected Set calculateValidPositions() { + return ImmutableSet.of(src, dest.up(), dest); + } + public static void cost(CalculationContext context, int x, int y, int z, int destX, int destZ, MutableMoveResult res) { double totalCost = 0; IBlockState destDown = context.get(destX, y - 1, destZ); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 9761f617..878c9cff 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -28,6 +28,7 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; import baritone.utils.pathing.MutableMoveResult; +import com.google.common.collect.ImmutableSet; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -36,6 +37,7 @@ import net.minecraft.util.math.BlockPos; import java.util.ArrayList; import java.util.List; +import java.util.Set; public class MovementDiagonal extends Movement { @@ -64,6 +66,16 @@ public class MovementDiagonal extends Movement { return result.cost; } + @Override + protected Set calculateValidPositions() { + BetterBlockPos diagA = new BetterBlockPos(src.x, src.y, dest.z); + BetterBlockPos diagB = new BetterBlockPos(dest.x, src.y, src.z); + if (dest.y != src.y) { // only if allowDiagonalDescend + return ImmutableSet.of(src, dest.up(), diagA, diagB, dest, diagA.down(), diagB.down()); + } + return ImmutableSet.of(src, dest, diagA, diagB); + } + public static void cost(CalculationContext context, int x, int y, int z, int destX, int destZ, MutableMoveResult res) { IBlockState destInto = context.get(destX, y, destZ); if (!MovementHelper.canWalkThrough(context.bsi, destX, y, destZ, destInto) || !MovementHelper.canWalkThrough(context.bsi, destX, y + 1, destZ)) { @@ -171,8 +183,9 @@ public class MovementDiagonal extends Movement { } if (ctx.playerFeet().equals(dest)) { - state.setStatus(MovementStatus.SUCCESS); - return state; + return state.setStatus(MovementStatus.SUCCESS); + } else if (!getValidPositions().contains(ctx.playerFeet())) { + return state.setStatus(MovementStatus.UNREACHABLE); } if (sprint()) { state.setInput(Input.SPRINT, true); @@ -181,7 +194,7 @@ public class MovementDiagonal extends Movement { return state; } - public boolean sprint() { + private boolean sprint() { if (MovementHelper.isLiquid(ctx, ctx.playerFeet()) && !Baritone.settings().sprintInWater.value) { return false; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java index 47ed9580..250f3471 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java @@ -24,10 +24,13 @@ import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; +import com.google.common.collect.ImmutableSet; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; +import java.util.Set; + public class MovementDownward extends Movement { private int numTicks = 0; @@ -47,6 +50,11 @@ public class MovementDownward extends Movement { return cost(context, src.x, src.y, src.z); } + @Override + protected Set calculateValidPositions() { + return ImmutableSet.of(src, dest); + } + public static double cost(CalculationContext context, int x, int y, int z) { if (!context.allowDownward) { return COST_INF; @@ -73,6 +81,8 @@ public class MovementDownward extends Movement { if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); + } else if (!getValidPositions().contains(ctx.playerFeet())) { + return state.setStatus(MovementStatus.UNREACHABLE); } double diffX = ctx.player().posX - (dest.getX() + 0.5); double diffZ = ctx.player().posZ - (dest.getZ() + 0.5); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 0a4c38c7..b777b0a6 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -42,7 +42,9 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3i; +import java.util.HashSet; import java.util.Optional; +import java.util.Set; public class MovementFall extends Movement { @@ -63,6 +65,16 @@ public class MovementFall extends Movement { return result.cost; } + @Override + protected Set calculateValidPositions() { + Set set = new HashSet<>(); + set.add(src); + for (int y = src.y - dest.y; y >= 0; y--) { + set.add(dest.up(y)); + } + return set; + } + private boolean willPlaceBucket() { CalculationContext context = new CalculationContext(baritone); MutableMoveResult result = new MutableMoveResult(); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index dfa43a05..b9f02c1a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -34,6 +34,9 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; +import java.util.HashSet; +import java.util.Set; + public class MovementParkour extends Movement { private static final BetterBlockPos[] EMPTY = new BetterBlockPos[]{}; @@ -174,6 +177,17 @@ public class MovementParkour extends Movement { return res.cost; } + @Override + protected Set calculateValidPositions() { + Set set = new HashSet<>(); + for (int i = 0; i <= dist; i++) { + for (int y = 0; y < 2; y++) { + set.add(src.offset(direction, i).up(y)); + } + } + return set; + } + @Override public boolean safeToCancel(MovementState state) { // once this movement is instantiated, the state is default to PREPPING diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 5e4a409f..c444422e 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -30,6 +30,7 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; +import com.google.common.collect.ImmutableSet; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -37,6 +38,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import java.util.Objects; +import java.util.Set; public class MovementPillar extends Movement { @@ -49,6 +51,11 @@ public class MovementPillar extends Movement { return cost(context, src.x, src.y, src.z); } + @Override + protected Set calculateValidPositions() { + return ImmutableSet.of(src, dest); + } + public static double cost(CalculationContext context, int x, int y, int z) { Block from = context.get(x, y, z).getBlock(); boolean ladder = from == Blocks.LADDER || from == Blocks.VINE; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index b621632c..03f81e76 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -30,12 +30,15 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; +import com.google.common.collect.ImmutableSet; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; +import java.util.Set; + public class MovementTraverse extends Movement { /** @@ -58,6 +61,11 @@ public class MovementTraverse extends Movement { return cost(context, src.x, src.y, src.z, dest.x, dest.z); } + @Override + protected Set calculateValidPositions() { + return ImmutableSet.of(src, dest); + } + public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) { IBlockState pb0 = context.get(destX, y + 1, destZ); IBlockState pb1 = context.get(destX, y, destZ); @@ -205,8 +213,8 @@ public class MovementTraverse extends Movement { if (pb0.getBlock() instanceof BlockFenceGate || pb1.getBlock() instanceof BlockFenceGate) { BlockPos blocked = !MovementHelper.isGatePassable(ctx, positionsToBreak[0], src.up()) ? positionsToBreak[0] - : !MovementHelper.isGatePassable(ctx, positionsToBreak[1], src) ? positionsToBreak[1] - : null; + : !MovementHelper.isGatePassable(ctx, positionsToBreak[1], src) ? positionsToBreak[1] + : null; if (blocked != null) { return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), blocked), ctx.playerRotations()), true)) .setInput(Input.CLICK_RIGHT, true); diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 7b9ba9ee..e92d3273 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -33,7 +33,6 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.movements.*; import baritone.utils.BlockStateInterface; import net.minecraft.block.BlockLiquid; -import net.minecraft.init.Blocks; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; @@ -100,14 +99,13 @@ public class PathExecutor implements IPathExecutor, Helper { if (pathPosition >= path.length()) { return true; // stop bugging me, I'm done } - BetterBlockPos whereShouldIBe = path.positions().get(pathPosition); + Movement movement = (Movement) path.movements().get(pathPosition); BetterBlockPos whereAmI = ctx.playerFeet(); - if (!whereShouldIBe.equals(whereAmI) && !Blocks.AIR.equals(BlockStateInterface.getBlock(ctx, whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip - for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks - if (whereAmI.equals(path.positions().get(i))) { - logDebug("Skipping back " + (pathPosition - i) + " steps, to " + i); + if (!movement.getValidPositions().contains(whereAmI)) { + for (int i = 0; i < pathPosition && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks + if (((Movement) path.movements().get(i)).getValidPositions().contains(whereAmI)) { int previousPos = pathPosition; - pathPosition = Math.max(i - 1, 0); // previous step might not actually be done + pathPosition = i; for (int j = pathPosition; j <= previousPos; j++) { path.movements().get(j).reset(); } @@ -173,10 +171,10 @@ public class PathExecutor implements IPathExecutor, Helper { HashSet newPlace = new HashSet<>(); HashSet newWalkInto = new HashSet<>(); for (int i = pathPosition; i < path.movements().size(); i++) { - Movement movement = (Movement) path.movements().get(i); - newBreak.addAll(movement.toBreak(bsi)); - newPlace.addAll(movement.toPlace(bsi)); - newWalkInto.addAll(movement.toWalkInto(bsi)); + Movement m = (Movement) path.movements().get(i); + newBreak.addAll(m.toBreak(bsi)); + newPlace.addAll(m.toPlace(bsi)); + newWalkInto.addAll(m.toWalkInto(bsi)); } toBreak = newBreak; toPlace = newPlace; @@ -187,11 +185,13 @@ public class PathExecutor implements IPathExecutor, Helper { if (end - start > 0) { System.out.println("Recalculating break and place took " + (end - start) + "ms"); }*/ - IMovement movement = path.movements().get(pathPosition); - if (!behavior.baritone.bsi.worldContainsLoadedChunk(movement.getDest().x, movement.getDest().z)) { - logDebug("Pausing since destination is at edge of loaded chunks"); - clearKeys(); - return true; + if (pathPosition < path.movements().size() - 1) { + IMovement next = path.movements().get(pathPosition + 1); + if (!behavior.baritone.bsi.worldContainsLoadedChunk(next.getDest().x, next.getDest().z)) { + logDebug("Pausing since destination is at edge of loaded chunks"); + clearKeys(); + return true; + } } boolean canCancel = movement.safeToCancel(); if (costEstimateIndex == null || costEstimateIndex != pathPosition) { @@ -206,7 +206,7 @@ public class PathExecutor implements IPathExecutor, Helper { } } } - double currentCost = ((Movement) movement).recalculateCost(behavior.secretInternalGetCalculationContext()); + double currentCost = movement.recalculateCost(behavior.secretInternalGetCalculationContext()); if (currentCost >= ActionCosts.COST_INF && canCancel) { logDebug("Something has changed in the world and this movement has become impossible. Cancelling."); cancel(); @@ -258,11 +258,13 @@ public class PathExecutor implements IPathExecutor, Helper { private Tuple closestPathPos(IPath path) { double best = -1; BlockPos bestPos = null; - for (BlockPos pos : path.positions()) { - double dist = VecUtils.entityDistanceToCenter(ctx.player(), pos); - if (dist < best || best == -1) { - best = dist; - bestPos = pos; + for (IMovement movement : path.movements()) { + for (BlockPos pos : ((Movement) movement).getValidPositions()) { + double dist = VecUtils.entityDistanceToCenter(ctx.player(), pos); + if (dist < best || best == -1) { + best = dist; + bestPos = pos; + } } } return new Tuple<>(best, bestPos); From fd6923dd2841a90d6fe8d3e7f686e274a5f5ee7c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 24 Jun 2019 20:38:17 -0700 Subject: [PATCH 470/682] ok i forgot falling into water --- .../baritone/pathing/movement/movements/MovementDiagonal.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 878c9cff..f17fc18d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -184,7 +184,7 @@ public class MovementDiagonal extends Movement { if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); - } else if (!getValidPositions().contains(ctx.playerFeet())) { + } else if (!getValidPositions().contains(ctx.playerFeet()) && !(MovementHelper.isLiquid(ctx, src) && getValidPositions().contains(ctx.playerFeet().up()))) { return state.setStatus(MovementStatus.UNREACHABLE); } if (sprint()) { From 36290e4e535a94bbe1542fed71e2c914c926b682 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 25 Jun 2019 22:54:24 -0700 Subject: [PATCH 471/682] crucial encapsulation improvement --- src/main/java/baritone/utils/PlayerMovementInput.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/PlayerMovementInput.java b/src/main/java/baritone/utils/PlayerMovementInput.java index c2e2db2a..4873d288 100644 --- a/src/main/java/baritone/utils/PlayerMovementInput.java +++ b/src/main/java/baritone/utils/PlayerMovementInput.java @@ -23,7 +23,7 @@ import net.minecraft.util.MovementInput; public class PlayerMovementInput extends MovementInput { private final InputOverrideHandler handler; - public PlayerMovementInput(InputOverrideHandler handler) { + PlayerMovementInput(InputOverrideHandler handler) { this.handler = handler; } From 4d3d48e96286be148cfd2b439cc57a2a3a60c519 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 26 Jun 2019 23:58:22 -0700 Subject: [PATCH 472/682] crucial documentation oversight --- src/main/java/baritone/utils/PlayerMovementInput.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/PlayerMovementInput.java b/src/main/java/baritone/utils/PlayerMovementInput.java index 4873d288..f41e0f62 100644 --- a/src/main/java/baritone/utils/PlayerMovementInput.java +++ b/src/main/java/baritone/utils/PlayerMovementInput.java @@ -31,7 +31,7 @@ public class PlayerMovementInput extends MovementInput { this.moveStrafe = 0.0F; this.moveForward = 0.0F; - jump = handler.isInputForcedDown(Input.JUMP); // oppa gangnam + jump = handler.isInputForcedDown(Input.JUMP); // oppa gangnam style if (this.forwardKeyDown = handler.isInputForcedDown(Input.MOVE_FORWARD)) { this.moveForward++; From afff6395d1f50e52f0a4806acb7e670de1d0b740 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 27 Jun 2019 21:02:44 -0700 Subject: [PATCH 473/682] codcacy wants a default --- src/main/java/baritone/process/BackfillProcess.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/baritone/process/BackfillProcess.java b/src/main/java/baritone/process/BackfillProcess.java index 65e5692e..62ae9640 100644 --- a/src/main/java/baritone/process/BackfillProcess.java +++ b/src/main/java/baritone/process/BackfillProcess.java @@ -85,6 +85,8 @@ public final class BackfillProcess extends BaritoneProcessHelper { // patience baritone.getLookBehavior().updateTarget(fake.getTarget().getRotation().get(), true); return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + default: + throw new IllegalStateException(); } } return new PathingCommand(null, PathingCommandType.DEFER); // cede to other process From fdd78cf110fbb1fb7101ea0965b8c5fbc69e8a3a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 28 Jun 2019 22:17:31 -0700 Subject: [PATCH 474/682] codcacy wants these to be combined --- .../movement/movements/MovementTraverse.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 03f81e76..d32573c0 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -202,13 +202,12 @@ public class MovementTraverse extends Movement { Block fd = BlockStateInterface.get(ctx, src.down()).getBlock(); boolean ladder = fd == Blocks.LADDER || fd == Blocks.VINE; - if (pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor) { - if ((pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, src, dest) - || pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, dest, src)) - && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { - return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0]), ctx.playerRotations()), true)) - .setInput(Input.CLICK_RIGHT, true); - } + if ((pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor) + && (pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, src, dest) + || pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, dest, src)) + && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0]), ctx.playerRotations()), true)) + .setInput(Input.CLICK_RIGHT, true); } if (pb0.getBlock() instanceof BlockFenceGate || pb1.getBlock() instanceof BlockFenceGate) { From a8155b4b0b7eeee7ab935a0c47936298f8ff7c53 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 29 Jun 2019 11:56:02 -0700 Subject: [PATCH 475/682] privatize --- src/api/java/baritone/api/utils/SettingsUtil.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 5dee6e88..9c21dcf3 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -158,11 +158,11 @@ public class SettingsUtil { private final Settings.Setting setting; - public ParserContext(Settings.Setting setting) { + private ParserContext(Settings.Setting setting) { this.setting = setting; } - final Settings.Setting getSetting() { + private Settings.Setting getSetting() { return this.setting; } } From 199e0e5ed31ff015077845126d6121aebd5ecdc9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 30 Jun 2019 21:55:32 -0700 Subject: [PATCH 476/682] better comparison --- src/main/java/baritone/utils/PathingControlManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 92b66c49..ccded35c 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -92,7 +92,7 @@ public class PathingControlManager implements IPathingControlManager { p.secretInternalSetGoal(null); return; } - if (inControlThisTick != inControlLastTick && command.commandType != PathingCommandType.REQUEST_PAUSE && inControlLastTick != null && !inControlLastTick.isTemporary()) { + if (!Objects.equals(inControlThisTick, inControlLastTick) && command.commandType != PathingCommandType.REQUEST_PAUSE && inControlLastTick != null && !inControlLastTick.isTemporary()) { // if control has changed from a real process to another real process, and the new process wants to do something p.cancelSegmentIfSafe(); // get rid of the in progress stuff from the last process From c2f35ae46f8d5059695db2a61e946768c6ad4230 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 1 Jul 2019 10:21:58 -0700 Subject: [PATCH 477/682] dawn of the final month --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ad14e174..2932de26 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Baritone is the pathfinding system used in [Impact](https://impactdevelopment.gi 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 and 1.13.2. 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). -Have committed at least once a day for the last 10 months =D 🦀 +Have committed at least once a day for the last 11 months =D 🦀 1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2 From ab779dc850ac987b2c300110767b8e242bdafb29 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 2 Jul 2019 22:13:17 -0700 Subject: [PATCH 478/682] increase shilling --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 2932de26..b2bb3164 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ A Minecraft pathfinder bot. Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. +The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the forge jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). + 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 and 1.13.2. 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 63ee687cee42f03d23b46ae2b56547b58f564765 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 3 Jul 2019 23:47:47 -0700 Subject: [PATCH 479/682] shill EVEN harder --- SETUP.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SETUP.md b/SETUP.md index 1767e2c5..65b51ec1 100644 --- a/SETUP.md +++ b/SETUP.md @@ -1,5 +1,7 @@ # Installation +The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. + ## Prebuilt official releases These releases are not always completely up to date with latest features, and are only released from `master`. (so if you want `backfill-2` branch for example, you'll have to build it yourself) From 6d8914e6c9107291eaa5b9c434fc7e01bb2a68ac Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 4 Jul 2019 15:52:09 -0700 Subject: [PATCH 480/682] spell it out even more --- README.md | 4 ++-- SETUP.md | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b2bb3164..55ef2717 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ A Minecraft pathfinder bot. Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. -The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the forge jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). +The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the forge jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). 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 and 1.13.2. 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). @@ -50,7 +50,7 @@ Here are some links to help to get started: - [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#field.detail) -- [Baritone chat control usage](USAGE.md) +- [Usage (chat control)](USAGE.md) # API diff --git a/SETUP.md b/SETUP.md index 65b51ec1..aca5f6c5 100644 --- a/SETUP.md +++ b/SETUP.md @@ -2,6 +2,8 @@ The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. +Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. + ## Prebuilt official releases These releases are not always completely up to date with latest features, and are only released from `master`. (so if you want `backfill-2` branch for example, you'll have to build it yourself) From 94131fd7056a530274e87625f659b2860b15a32f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 5 Jul 2019 21:19:18 -0700 Subject: [PATCH 481/682] too many newlines --- USAGE.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/USAGE.md b/USAGE.md index ce8924a7..f628d542 100644 --- a/USAGE.md +++ b/USAGE.md @@ -16,9 +16,6 @@ To disable direct chat control (with no prefix), turn off the `chatControl` sett To toggle a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `primaryTimeoutMS 250`). It's case insensitive. To reset a setting to its default value, say `acceptableThrowawayItems reset`. To reset all settings, say `reset`. To see all settings that have been modified from their default values, say `modified`. - - - Some common examples: - `thisway 1000` then `path` to go in the direction you're facing for a thousand blocks - `goal x y z` or `goal x z` or `goal y`, then `path` to go to a certain coordinate From dd9b84646ae13403d0badd03980952eba9550782 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 6 Jul 2019 17:07:16 -0700 Subject: [PATCH 482/682] disgraceful --- src/main/java/baritone/utils/GuiClick.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index 480da707..3e6d0eaf 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -69,7 +69,6 @@ public class GuiClick extends GuiScreen { currentMouseOver = result.getBlockPos(); } } - } @Override From cbbaf2aa2fbf52ed7d0bb63aedc0671b86450e46 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 6 Jul 2019 20:38:59 -0700 Subject: [PATCH 483/682] unscuff --- src/main/java/baritone/utils/GuiClick.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index 3e6d0eaf..ce5c28a0 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -102,7 +102,7 @@ public class GuiClick extends GuiScreen { PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(currentMouseOver), Color.CYAN); if (clickStart != null && !clickStart.equals(currentMouseOver)) { GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); + 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); GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); GlStateManager.disableTexture2D(); From 8f761f7dff95589818c36600c7c78d8cf1282eaa Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Jul 2019 11:03:43 -0700 Subject: [PATCH 484/682] better skip ahead --- src/main/java/baritone/pathing/path/PathExecutor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index e92d3273..6fbe5063 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -116,7 +116,7 @@ public class PathExecutor implements IPathExecutor, Helper { } for (int i = pathPosition + 3; i < path.length(); i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing) // also don't check pathPosition+2 because reasons - if (whereAmI.equals(path.positions().get(i))) { + if (((Movement) path.movements().get(i)).getValidPositions().contains(whereAmI)) { if (i - pathPosition > 2) { logDebug("Skipping forward " + (i - pathPosition) + " steps, to " + i); } From 4259764b70bb90d1dd1779e4e4ad37c646acb2e1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Jul 2019 11:12:32 -0700 Subject: [PATCH 485/682] thank you off by one errors very cool --- src/main/java/baritone/pathing/path/PathExecutor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 6fbe5063..9202b163 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -114,7 +114,7 @@ public class PathExecutor implements IPathExecutor, Helper { return false; } } - for (int i = pathPosition + 3; i < path.length(); i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing) + for (int i = pathPosition + 3; i < path.length() - 1; i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing) // also don't check pathPosition+2 because reasons if (((Movement) path.movements().get(i)).getValidPositions().contains(whereAmI)) { if (i - pathPosition > 2) { From b81bcf8c6de90eaa89c7c9d1bac626e529cfa178 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Jul 2019 11:44:56 -0700 Subject: [PATCH 486/682] fix path start in diagonal and downward --- src/main/java/baritone/pathing/movement/Movement.java | 5 +++++ .../pathing/movement/movements/MovementDiagonal.java | 2 +- .../pathing/movement/movements/MovementDownward.java | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 6907c426..ca4abe9e 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -23,6 +23,7 @@ import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.*; import baritone.api.utils.input.Input; +import baritone.behavior.PathingBehavior; import baritone.utils.BlockStateInterface; import net.minecraft.block.BlockLiquid; import net.minecraft.entity.item.EntityFallingBlock; @@ -110,6 +111,10 @@ public abstract class Movement implements IMovement, MovementHelper { return validPositionsCached; } + protected boolean playerInValidPosition() { + return getValidPositions().contains(ctx.playerFeet()) || getValidPositions().contains(((PathingBehavior) baritone.getPathingBehavior()).pathStart()); + } + /** * Handles the execution of the latest Movement * State, and offers a Status to the calling class. diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index f17fc18d..c036a459 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -184,7 +184,7 @@ public class MovementDiagonal extends Movement { if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); - } else if (!getValidPositions().contains(ctx.playerFeet()) && !(MovementHelper.isLiquid(ctx, src) && getValidPositions().contains(ctx.playerFeet().up()))) { + } else if (!playerInValidPosition() && !(MovementHelper.isLiquid(ctx, src) && getValidPositions().contains(ctx.playerFeet().up()))) { return state.setStatus(MovementStatus.UNREACHABLE); } if (sprint()) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java index 250f3471..da5e3f89 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java @@ -81,7 +81,7 @@ public class MovementDownward extends Movement { if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); - } else if (!getValidPositions().contains(ctx.playerFeet())) { + } else if (!playerInValidPosition()) { return state.setStatus(MovementStatus.UNREACHABLE); } double diffX = ctx.player().posX - (dest.getX() + 0.5); From cd4205c3610e59d82e99e8931a1f199f1021c171 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 7 Jul 2019 12:07:00 -0700 Subject: [PATCH 487/682] v1.2.7 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 27b0d7a3..00e35617 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.2.6' +version '1.2.7' buildscript { repositories { From f4dd1003455892a0a4cbaa7178ea32b7a29f9340 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 8 Jul 2019 23:16:26 -0700 Subject: [PATCH 488/682] fix indexof --- src/main/java/baritone/pathing/path/PathExecutor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 9202b163..e03a20cc 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -427,7 +427,7 @@ public class PathExecutor implements IPathExecutor, Helper { if (current instanceof MovementFall) { Tuple data = overrideFall((MovementFall) current); if (data != null) { - BlockPos fallDest = data.getSecond(); + BetterBlockPos fallDest = new BetterBlockPos(data.getSecond()); if (!path.positions().contains(fallDest)) { throw new IllegalStateException(); } From eba1011fd6f05b4f86b736f256035688c2b20e78 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 9 Jul 2019 23:47:42 -0700 Subject: [PATCH 489/682] remove scuff --- src/main/java/baritone/utils/PathRenderer.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 88a18147..b0924cc1 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -97,8 +97,6 @@ public final class PathRenderer implements Helper { } //drawManySelectionBoxes(player, Collections.singletonList(behavior.pathStart()), partialTicks, Color.WHITE); - //long start = System.nanoTime(); - // Render the current path, if there is one if (current != null && current.getPath() != null) { @@ -109,8 +107,6 @@ public final class PathRenderer implements Helper { drawPath(next.getPath(), 0, renderView, partialTicks, Baritone.settings().colorNextPath.value, Baritone.settings().fadePath.value, 10, 20); } - //long split = System.nanoTime(); - // If there is a path calculation currently running, render the path calculation process behavior.getInProgress().ifPresent(currentlyRunning -> { currentlyRunning.bestPathSoFar().ifPresent(p -> { @@ -122,11 +118,6 @@ public final class PathRenderer implements Helper { drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), Baritone.settings().colorMostRecentConsidered.value); }); }); - //long end = System.nanoTime(); - //System.out.println((end - split) + " " + (split - start)); - // if (end - start > 0) { - // System.out.println("Frame took " + (split - start) + " " + (end - split)); - //} } public static void drawPath(IPath path, int startIndex, Entity player, float partialTicks, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) { From aa90c8b7cd591b1a47bc523dbcfec1c040a96894 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 10 Jul 2019 22:18:11 -0700 Subject: [PATCH 490/682] address encapsulation conccerns --- src/main/java/baritone/process/BackfillProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/BackfillProcess.java b/src/main/java/baritone/process/BackfillProcess.java index 62ae9640..f025c393 100644 --- a/src/main/java/baritone/process/BackfillProcess.java +++ b/src/main/java/baritone/process/BackfillProcess.java @@ -92,7 +92,7 @@ public final class BackfillProcess extends BaritoneProcessHelper { return new PathingCommand(null, PathingCommandType.DEFER); // cede to other process } - public void amIBreakingABlockHMMMMMMM() { + private void amIBreakingABlockHMMMMMMM() { if (!ctx.getSelectedBlock().isPresent()) { return; } From 01658286af37b9bb5a7f93019fa0d5d09b574373 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Jul 2019 10:41:24 -0700 Subject: [PATCH 491/682] detect allowbreak false --- src/main/java/baritone/process/MineProcess.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 01a460d4..f3b1d20b 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -99,6 +99,11 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return null; } } + if (!Baritone.settings().allowBreak.value) { + logDirect("Unable to mine when allowBreak is false!"); + cancel(); + return null; + } int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.value; List curr = new ArrayList<>(knownOreLocations); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain @@ -395,6 +400,10 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro @Override public void mine(int quantity, Block... blocks) { this.mining = blocks == null || blocks.length == 0 ? null : Arrays.asList(blocks); + if (mining != null && !Baritone.settings().allowBreak.value) { + logDirect("Unable to mine when allowBreak is false!"); + mining = null; + } this.desiredQuantity = quantity; this.knownOreLocations = new ArrayList<>(); this.blacklist = new ArrayList<>(); From ce4b1e09edf44f08107b405bf8dd121c8fa38550 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 11 Jul 2019 12:46:24 -0700 Subject: [PATCH 492/682] fix parkour and multithread farm --- .../pathing/movement/movements/MovementParkour.java | 2 +- src/main/java/baritone/process/FarmProcess.java | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index b9f02c1a..88ffb1d9 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -226,7 +226,7 @@ public class MovementParkour extends Movement { state.setStatus(MovementStatus.SUCCESS); } } else if (!ctx.playerFeet().equals(src)) { - if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - ctx.playerFeet().getY() > 0.0001) { + if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - src.y > 0.0001) { if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), true) == PlaceResult.READY_TO_PLACE) { // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory state.setInput(Input.CLICK_RIGHT, true); diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index 9593a192..a2d32f78 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -54,6 +54,9 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro private boolean active; + private List locations; + private int tickCount; + private static final List FARMLAND_PLANTABLE = Arrays.asList( Items.BEETROOT_SEEDS, Items.MELON_SEEDS, @@ -93,6 +96,7 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro @Override public void farm() { active = true; + locations = null; } private enum Harvest { @@ -164,9 +168,12 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro if (Baritone.settings().replantNetherWart.value) { scan.add(Blocks.SOUL_SAND); } - - List locations = WorldScanner.INSTANCE.scanChunkRadius(ctx, scan, 256, 10, 4); - + if (Baritone.settings().mineGoalUpdateInterval.value != 0 && tickCount++ % Baritone.settings().mineGoalUpdateInterval.value == 0) { + Baritone.getExecutor().execute(() -> locations = WorldScanner.INSTANCE.scanChunkRadius(ctx, scan, 256, 10, 10)); + } + if (locations == null) { + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } List toBreak = new ArrayList<>(); List openFarmland = new ArrayList<>(); List bonemealable = new ArrayList<>(); From b16f9edd2c8d950e8ce7ec4e1cad81201288c921 Mon Sep 17 00:00:00 2001 From: Baddeveloper Date: Fri, 12 Jul 2019 19:12:00 +0200 Subject: [PATCH 493/682] Added EntitySpider and EntityPigZombie conditions --- src/main/java/baritone/utils/pathing/Avoidance.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/baritone/utils/pathing/Avoidance.java b/src/main/java/baritone/utils/pathing/Avoidance.java index c4b12336..c7b6a854 100644 --- a/src/main/java/baritone/utils/pathing/Avoidance.java +++ b/src/main/java/baritone/utils/pathing/Avoidance.java @@ -22,6 +22,8 @@ import baritone.api.utils.BetterBlockPos; import baritone.api.utils.IPlayerContext; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; import net.minecraft.entity.monster.EntityMob; +import net.minecraft.entity.monster.EntityPigZombie; +import net.minecraft.entity.monster.EntitySpider; import net.minecraft.util.math.BlockPos; import java.util.ArrayList; @@ -70,6 +72,8 @@ public class Avoidance { if (mobCoeff != 1.0D) { ctx.world().loadedEntityList.stream() .filter(entity -> entity instanceof EntityMob) + .filter(entity -> (!(entity instanceof EntitySpider)) || ctx.player().getBrightness() < 0.5) + .filter(entity -> !(entity instanceof EntityPigZombie) || ((EntityPigZombie) entity).isAngry()) .forEach(entity -> res.add(new Avoidance(new BlockPos(entity), mobCoeff, Baritone.settings().mobAvoidanceRadius.value))); } return res; From 6bb87d0a64d77435f6e26433e22cf3daa851c41b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 12 Jul 2019 23:27:02 -0700 Subject: [PATCH 494/682] address an absolutely critical gap in documentation --- src/api/java/baritone/api/IBaritone.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index a356922c..2c892d98 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -128,5 +128,8 @@ public interface IBaritone { */ IEventBus getGameEventHandler(); + /** + * Open click + */ void openClick(); } From 2b41012c5ba4ff8fe3374467fbb2214e3f5665c8 Mon Sep 17 00:00:00 2001 From: StijnSimons Date: Sat, 13 Jul 2019 17:17:10 +0200 Subject: [PATCH 495/682] Enderman angry condition --- src/main/java/baritone/utils/pathing/Avoidance.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/baritone/utils/pathing/Avoidance.java b/src/main/java/baritone/utils/pathing/Avoidance.java index c7b6a854..11b4a73f 100644 --- a/src/main/java/baritone/utils/pathing/Avoidance.java +++ b/src/main/java/baritone/utils/pathing/Avoidance.java @@ -21,6 +21,7 @@ import baritone.Baritone; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.IPlayerContext; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; +import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.monster.EntityPigZombie; import net.minecraft.entity.monster.EntitySpider; @@ -74,6 +75,7 @@ public class Avoidance { .filter(entity -> entity instanceof EntityMob) .filter(entity -> (!(entity instanceof EntitySpider)) || ctx.player().getBrightness() < 0.5) .filter(entity -> !(entity instanceof EntityPigZombie) || ((EntityPigZombie) entity).isAngry()) + .filter(entity -> !(entity instanceof EntityEnderman) || ((EntityEnderman) entity).isScreaming()) .forEach(entity -> res.add(new Avoidance(new BlockPos(entity), mobCoeff, Baritone.settings().mobAvoidanceRadius.value))); } return res; From 38602dd141512fbd04f3eee30ceebad15609d741 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 14 Jul 2019 11:13:51 -0700 Subject: [PATCH 496/682] verify top side of block, fixes #541 --- src/main/java/baritone/process/FarmProcess.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index a2d32f78..2702442b 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -24,6 +24,7 @@ import baritone.api.pathing.goals.GoalComposite; import baritone.api.process.IFarmProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; +import baritone.api.utils.RayTraceUtils; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; @@ -40,7 +41,9 @@ import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; @@ -223,11 +226,14 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro 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()); if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, soulsand ? this::isNetherWart : this::isPlantable)) { - baritone.getLookBehavior().updateTarget(rot.get(), true); - if (ctx.isLookingAt(pos)) { - baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); + RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance()); + if (result.typeOfHit == RayTraceResult.Type.BLOCK && result.sideHit == EnumFacing.UP) { + baritone.getLookBehavior().updateTarget(rot.get(), true); + if (ctx.isLookingAt(pos)) { + baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); + } + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } - return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } } for (BlockPos pos : bonemealable) { From b51a261bd10483a0ec10527f92db2171f4b7f9fc Mon Sep 17 00:00:00 2001 From: StijnSimons Date: Mon, 15 Jul 2019 22:31:55 +0200 Subject: [PATCH 497/682] Added entityfollow Hey look i can cntrl + c v --- .../api/utils/ExampleBaritoneControl.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 2445f634..29e2e9d1 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -411,6 +411,24 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener logDirect("Following any players"); return true; } + if (msg.startsWith("followentity")) { + String name = msg.substring(12).trim(); + Optional toFollow = Optional.empty(); + for (Entity entity : ctx.world().loadedEntityList) { + String entityName = entity.getName().trim().toLowerCase(); + if (entityName.contains(name) || name.contains(entityName)) { + toFollow = Optional.of(entity); + } + } + if (!toFollow.isPresent()) { + logDirect("Entity not found"); + return true; + } + Entity effectivelyFinal = toFollow.get(); + baritone.getFollowProcess().follow(effectivelyFinal::equals); + logDirect("Following entity " + toFollow.get()); + return true; + } if (msg.startsWith("follow")) { String name = msg.substring(6).trim(); Optional toFollow = Optional.empty(); From 3ba8824eb003aedec9edc334f2ec59c991ecad3b Mon Sep 17 00:00:00 2001 From: StijnSimons Date: Mon, 15 Jul 2019 22:34:52 +0200 Subject: [PATCH 498/682] More copy paste --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 29e2e9d1..1b47c8a5 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -406,6 +406,11 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } return true; } + if (msg.startsWith("followentities")) { + baritone.getFollowProcess().follow(Entity.class::isInstance); + logDirect("Following any entities"); + return true; + } if (msg.startsWith("followplayers")) { baritone.getFollowProcess().follow(EntityPlayer.class::isInstance); // O P P A logDirect("Following any players"); From 72be046f34d703bb05497ab38177405a57385816 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 15 Jul 2019 14:44:16 -0700 Subject: [PATCH 499/682] Update ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index e9a3c7cc..877b6260 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1 +1,28 @@ - +# Bug report + +## Some information +Operating system: +Java version: +Minecraft version: +Baritone version: +Forge mods (if used): + +## Exception, error or logs +You can find your logs in `%appdata%/.minecraft/logs/` (Windows) or `/Library/Application\ Support/minecraft/logs` (Mac). + +## How to reproduce +Add your steps to reproduce here. + +## Final checklist +- [ ] I have included the version of Minecraft I'm running, baritone's version and forge mods (if used). +- [ ] I have included logs, exceptions and / or steps to reproduce the issue. +- [ ] I have not used any OwO's or UwU's in this issue. + +# Suggestion +Give some information about your suggestion. + +## New features +Add feature ideas here. + +## New options +Add option ideas here. From e034437c633584c9d0893dc5a4201dfd02ac09bf Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 15 Jul 2019 17:55:15 -0500 Subject: [PATCH 500/682] Separate templates --- .../bug.md} | 21 ++++++++----------- .github/ISSUE_TEMPLATE/suggestion.md | 19 +++++++++++++++++ 2 files changed, 28 insertions(+), 12 deletions(-) rename .github/{ISSUE_TEMPLATE.md => ISSUE_TEMPLATE/bug.md} (64%) create mode 100644 .github/ISSUE_TEMPLATE/suggestion.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE/bug.md similarity index 64% rename from .github/ISSUE_TEMPLATE.md rename to .github/ISSUE_TEMPLATE/bug.md index 877b6260..55e5ad06 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -1,4 +1,10 @@ -# Bug report +--- +name: Bug report +about: Please file a separate report for each issue +title: Please add a brief but descriptive title +labels: bug +assignees: '' +--- ## Some information Operating system: @@ -11,18 +17,9 @@ Forge mods (if used): You can find your logs in `%appdata%/.minecraft/logs/` (Windows) or `/Library/Application\ Support/minecraft/logs` (Mac). ## How to reproduce -Add your steps to reproduce here. +Add your steps to reproduce the issue/bug experienced here. ## Final checklist - [ ] I have included the version of Minecraft I'm running, baritone's version and forge mods (if used). - [ ] I have included logs, exceptions and / or steps to reproduce the issue. -- [ ] I have not used any OwO's or UwU's in this issue. - -# Suggestion -Give some information about your suggestion. - -## New features -Add feature ideas here. - -## New options -Add option ideas here. +- [ ] I have not used any OwO's or UwU's in this issue. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/suggestion.md b/.github/ISSUE_TEMPLATE/suggestion.md new file mode 100644 index 00000000..da61c638 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/suggestion.md @@ -0,0 +1,19 @@ +--- +name: Suggestion +about: Please file a separate report for each suggestion +title: Please add a brief but descriptive title +labels: enhancement +assignees: '' +--- + +## Describe your suggestion +With as much detail as possible, describe what your suggestion would do for Baritone. + +## Settings +If applicable, what settings/customizability should be offered to tweak the functionality of your suggestion. + +## Context +Describe how your suggestion would improve Baritone, or the reason behind it being added. + +## Final checklist +- [ ] I have not used any OwO's or UwU's in this issue. \ No newline at end of file From 0d9f233e33a8951df0e023d9879cfe21e4ee93bb Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 15 Jul 2019 18:00:51 -0500 Subject: [PATCH 501/682] Add question template --- .github/ISSUE_TEMPLATE/question.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/question.md diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 00000000..2482fd4c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,13 @@ +--- +name: Question +about: Please file a separate report for each question +title: Please add a brief but descriptive title +labels: question +assignees: '' +--- + +## What do you need help with? +With as much detail as possible, describe your question and what you may need help with. + +## Final checklist +- [ ] I have not used any OwO's or UwU's in this issue. \ No newline at end of file From 09239f8180c725d21d5167bc24014c479b885eea Mon Sep 17 00:00:00 2001 From: ZakME <35682140+ZakME@users.noreply.github.com> Date: Tue, 16 Jul 2019 23:50:03 -0600 Subject: [PATCH 502/682] PICKUP_DROPPED - Remove 2nd Items.WHEAT PICKUP_DROPPED: Remove 2nd Items.WHEAT Re-order a few items for neatness --- src/main/java/baritone/process/FarmProcess.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index 2702442b..350b1ac8 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -71,17 +71,16 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro private static final List PICKUP_DROPPED = Arrays.asList( Items.BEETROOT_SEEDS, - Items.WHEAT, + Items.BEETROOT, Items.MELON_SEEDS, Items.MELON, + Item.getItemFromBlock(Blocks.MELON_BLOCK), Items.WHEAT_SEEDS, Items.WHEAT, Items.PUMPKIN_SEEDS, + Item.getItemFromBlock(Blocks.PUMPKIN), Items.POTATO, Items.CARROT, - Items.BEETROOT, - Item.getItemFromBlock(Blocks.PUMPKIN), - Item.getItemFromBlock(Blocks.MELON_BLOCK), Items.NETHER_WART, Items.REEDS, Item.getItemFromBlock(Blocks.CACTUS) From f32147d9d521ce3db1175463dd28fa44f160353c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 17 Jul 2019 22:41:09 -0700 Subject: [PATCH 503/682] privatize --- src/main/java/baritone/utils/BlockBreakHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index 36e2dfea..95d021c2 100644 --- a/src/main/java/baritone/utils/BlockBreakHelper.java +++ b/src/main/java/baritone/utils/BlockBreakHelper.java @@ -38,7 +38,7 @@ public final class BlockBreakHelper implements Helper { this.playerContext = playerContext; } - public void tryBreakBlock(BlockPos pos, EnumFacing side) { + private void tryBreakBlock(BlockPos pos, EnumFacing side) { if (playerContext.playerController().onPlayerDamageBlock(pos, side)) { playerContext.player().swingArm(EnumHand.MAIN_HAND); } From 81514446713e22faf85ee76e917e0120c05ea355 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 18 Jul 2019 14:15:53 -0700 Subject: [PATCH 504/682] privatize this too --- src/main/java/baritone/utils/PathingControlManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index ccded35c..14d921d0 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -126,7 +126,7 @@ public class PathingControlManager implements IPathingControlManager { } } - public void postTick() { + private void postTick() { // if we did this in pretick, it would suck // we use the time between ticks as calculation time // therefore, we only cancel and recalculate after the tick for the current path has executed From af943a8253f538761b6421bb7a8bb2f2cbe19938 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 18 Jul 2019 21:18:02 -0500 Subject: [PATCH 505/682] Fix issue opening fence gates in some scenarios If there are 2 fence gates at the player height, and they are approached diagonally, there is a slight chance that Baritone will be caught in an infinite loop of opening and closing the upper fence gate, being unable to interact with the bottom one. --- .../movement/movements/MovementTraverse.java | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index d32573c0..4eab7144 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -37,6 +37,7 @@ import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; +import java.util.Optional; import java.util.Set; public class MovementTraverse extends Movement { @@ -202,12 +203,15 @@ public class MovementTraverse extends Movement { Block fd = BlockStateInterface.get(ctx, src.down()).getBlock(); boolean ladder = fd == Blocks.LADDER || fd == Blocks.VINE; - if ((pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor) - && (pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, src, dest) - || pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, dest, src)) - && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { - return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0]), ctx.playerRotations()), true)) - .setInput(Input.CLICK_RIGHT, true); + if (pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor) { + + boolean notPassable = pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, src, dest) || pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, dest, src); + boolean canOpen = !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock())); + + if (notPassable && canOpen) { + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0]), ctx.playerRotations()), true)) + .setInput(Input.CLICK_RIGHT, true); + } } if (pb0.getBlock() instanceof BlockFenceGate || pb1.getBlock() instanceof BlockFenceGate) { @@ -215,8 +219,10 @@ public class MovementTraverse extends Movement { : !MovementHelper.isGatePassable(ctx, positionsToBreak[1], src) ? positionsToBreak[1] : null; if (blocked != null) { - return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), blocked), ctx.playerRotations()), true)) - .setInput(Input.CLICK_RIGHT, true); + Optional rotation = RotationUtils.reachable(ctx, blocked); + if (rotation.isPresent()) { + return state.setTarget(new MovementState.MovementTarget(rotation.get(), true)).setInput(Input.CLICK_RIGHT, true); + } } } From 8b43d9325916d78e5ccdb5800eed97d7eaf24437 Mon Sep 17 00:00:00 2001 From: StijnSimons Date: Sat, 20 Jul 2019 01:37:43 +0200 Subject: [PATCH 506/682] i forgot players and items were entities too --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 1b47c8a5..0f2e0815 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -35,6 +35,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ChunkProviderClient; import net.minecraft.crash.CrashReport; import net.minecraft.entity.Entity; +import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ReportedException; @@ -421,7 +422,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener Optional toFollow = Optional.empty(); for (Entity entity : ctx.world().loadedEntityList) { String entityName = entity.getName().trim().toLowerCase(); - if (entityName.contains(name) || name.contains(entityName)) { + if ((entityName.contains(name) || name.contains(entityName)) && !(entity instanceof EntityItem || entity instanceof EntityPlayer)) { // We dont want it following players while `#follow` exists. toFollow = Optional.of(entity); } } From df900c9e64d80492391cef5860952ef7a3bebb79 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 19 Jul 2019 18:55:32 -0700 Subject: [PATCH 507/682] use origin --- src/main/java/baritone/pathing/movement/MovementHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 60b36119..97a768ab 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -134,7 +134,7 @@ public interface MovementHelper extends ActionCosts, Helper { // every block that overrides isPassable with anything more complicated than a "return true;" or "return false;" // has already been accounted for above // therefore it's safe to not construct a blockpos from our x, y, z ints and instead just pass null - return block.isPassable(null, null); + return block.isPassable(null, BlockPos.ORIGIN); } /** From 4d127acb9aae88ea17e34f0ef0b272a4138489eb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 20 Jul 2019 23:47:51 -0700 Subject: [PATCH 508/682] reformat --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 0f2e0815..96d6ad2f 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -610,7 +610,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } if (msg.startsWith("delete")) { String name = msg.substring(6).trim(); - IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getTag() == IWaypoint.Tag.USER && w.getName().equalsIgnoreCase(name)).findFirst().orElse(null); + IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getTag() == IWaypoint.Tag.USER && w.getName().equalsIgnoreCase(name)).findFirst().orElse(null); if (waypoint == null) { logDirect("No user defined position under the name '" + name + "' found."); return true; @@ -714,7 +714,6 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener goal = new GoalBlock(playerFeet); break; case 1: - goal = new GoalYLevel(parseOrDefault(params[0], playerFeet.y)); break; case 2: From d505ec4f9f031a982d2c93ef40d675e396be75d9 Mon Sep 17 00:00:00 2001 From: Babbaj Date: Sun, 21 Jul 2019 20:54:02 -0400 Subject: [PATCH 509/682] build the schematic schematica has open --- build.gradle | 8 +++ scripts/proguard.pro | 5 ++ .../baritone/api/process/IBuilderProcess.java | 2 + .../api/utils/ExampleBaritoneControl.java | 4 ++ .../java/baritone/process/BuilderProcess.java | 15 ++++++ .../schematica/SchematicAdapter.java | 54 +++++++++++++++++++ .../schematica/SchematicaHelper.java | 50 +++++++++++++++++ .../lunatrius/core/util/math/MBlockPos.java | 30 +++++++++++ .../lunatrius/schematica/Schematica.java | 24 +++++++++ .../lunatrius/schematica/api/ISchematic.java | 31 +++++++++++ .../client/world/SchematicWorld.java | 32 +++++++++++ .../schematica/proxy/ClientProxy.java | 29 ++++++++++ .../schematica/proxy/CommonProxy.java | 20 +++++++ 13 files changed, 304 insertions(+) create mode 100644 src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java create mode 100644 src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java create mode 100644 src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java create mode 100644 src/schematica_api/java/com/github/lunatrius/schematica/Schematica.java create mode 100644 src/schematica_api/java/com/github/lunatrius/schematica/api/ISchematic.java create mode 100644 src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java create mode 100644 src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java create mode 100644 src/schematica_api/java/com/github/lunatrius/schematica/proxy/CommonProxy.java diff --git a/build.gradle b/build.gradle index 00e35617..1264f0fe 100755 --- a/build.gradle +++ b/build.gradle @@ -55,6 +55,14 @@ sourceSets { launch { compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output } + + schematica_api { + compileClasspath += main.compileClasspath + } + + main { + compileClasspath += schematica_api.output + } } minecraft { diff --git a/scripts/proguard.pro b/scripts/proguard.pro index bb8df2ae..2e10986d 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -31,6 +31,11 @@ # need to keep mixin names -keep class baritone.launch.** { *; } +#try to keep usage of schematica in separate classes +-keep class baritone.utils.schematic.schematica.* +#proguard doesnt like it when it cant find our fake schematica classes +-dontwarn baritone.utils.schematic.schematica.* + # copy all necessary libraries into tempLibraries to build # The correct jar will be copied from the forgegradle cache based on the mapping type being compiled with diff --git a/src/api/java/baritone/api/process/IBuilderProcess.java b/src/api/java/baritone/api/process/IBuilderProcess.java index d9397786..f73f0e74 100644 --- a/src/api/java/baritone/api/process/IBuilderProcess.java +++ b/src/api/java/baritone/api/process/IBuilderProcess.java @@ -54,6 +54,8 @@ public interface IBuilderProcess extends IBaritoneProcess { return build(schematicFile, file, origin); } + void buildOpenSchematic(); + void pause(); void resume(); diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 96d6ad2f..46300150 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -295,6 +295,10 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener logDirect(success ? "Loaded" : "Unable to load"); return true; } + if (msg.startsWith("schematica")) { + baritone.getBuilderProcess().buildOpenSchematic(); + return true; + } if (msg.equals("come")) { customGoalProcess.setGoalAndPath(new GoalBlock(new BlockPos(Helper.mc.getRenderViewEntity()))); logDirect("Coming"); diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 52f21b76..5317c39a 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -35,6 +35,7 @@ import baritone.utils.BlockStateInterface; import baritone.utils.PathingCommandContext; import baritone.utils.schematic.AirSchematic; import baritone.utils.schematic.Schematic; +import baritone.utils.schematic.schematica.SchematicaHelper; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import net.minecraft.block.BlockAir; import net.minecraft.block.BlockLiquid; @@ -106,6 +107,20 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil return true; } + @Override + public void buildOpenSchematic() { + if (SchematicaHelper.isSchematicaPresent()) { + Optional> schematic = SchematicaHelper.getOpenSchematic(); + if (schematic.isPresent()) { + this.build(schematic.get().getFirst().toString(), schematic.get().getFirst(), schematic.get().getSecond()); + } else { + logDirect("No schematic currently open"); + } + } else { + logDirect("Schematica is not present"); + } + } + public void clearArea(BlockPos corner1, BlockPos corner2) { BlockPos origin = new BlockPos(Math.min(corner1.getX(), corner2.getX()), Math.min(corner1.getY(), corner2.getY()), Math.min(corner1.getZ(), corner2.getZ())); int widthX = Math.abs(corner1.getX() - corner2.getX()) + 1; diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java new file mode 100644 index 00000000..4e399348 --- /dev/null +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.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.utils.schematic.schematica; + +import baritone.api.utils.ISchematic; + +import com.github.lunatrius.schematica.client.world.SchematicWorld; +import net.minecraft.block.state.IBlockState; +import net.minecraft.util.math.BlockPos; + +// TODO: this only works for the default rotation +public final class SchematicAdapter implements ISchematic { + private final SchematicWorld schematic; + + + public SchematicAdapter(SchematicWorld schematicWorld) { + this.schematic = schematicWorld; + } + + @Override + public IBlockState desiredState(int x, int y, int z) { + return schematic.getSchematic().getBlockState(new BlockPos(x, y, z)); + } + + @Override + public int widthX() { + return schematic.getSchematic().getWidth(); + } + + @Override + public int heightY() { + return schematic.getSchematic().getHeight(); + } + + @Override + public int lengthZ() { + return schematic.getSchematic().getLength(); + } +} diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java new file mode 100644 index 00000000..bf5d4678 --- /dev/null +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.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.utils.schematic.schematica; + +import baritone.api.utils.ISchematic; +import com.github.lunatrius.core.util.math.MBlockPos; +import com.github.lunatrius.schematica.Schematica; +import com.github.lunatrius.schematica.proxy.ClientProxy; +import net.minecraft.util.Tuple; +import net.minecraft.util.math.BlockPos; + +import java.util.Optional; + +public enum SchematicaHelper { + ; + + public static boolean isSchematicaPresent() { + try { + Class.forName(Schematica.class.getName()); + return true; + } catch (ClassNotFoundException ex) { + return false; + } + } + + public static Optional> getOpenSchematic() { + return Optional.ofNullable(ClientProxy.schematic) + .map(world -> { + MBlockPos poz = world.position; + return new Tuple<>(new SchematicAdapter(world), new BlockPos(poz.field_177962_a, poz.field_177960_b, poz.field_177961_c)); + }); + } + + private static void meme(Class clazz) throws ClassNotFoundException {} +} diff --git a/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java b/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java new file mode 100644 index 00000000..60cf6fae --- /dev/null +++ b/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java @@ -0,0 +1,30 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package com.github.lunatrius.core.util.math; + +import net.minecraft.util.math.BlockPos; + +public class MBlockPos extends BlockPos { + public int field_177962_a; // x + public int field_177960_b; // y + public int field_177961_c; // z + + private MBlockPos() { + super(6, 6, 6); + } +} diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/Schematica.java b/src/schematica_api/java/com/github/lunatrius/schematica/Schematica.java new file mode 100644 index 00000000..7d786dbd --- /dev/null +++ b/src/schematica_api/java/com/github/lunatrius/schematica/Schematica.java @@ -0,0 +1,24 @@ +/* + * 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 com.github.lunatrius.schematica; + +import com.github.lunatrius.schematica.proxy.CommonProxy; + +public class Schematica { + public static CommonProxy proxy; +} diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/api/ISchematic.java b/src/schematica_api/java/com/github/lunatrius/schematica/api/ISchematic.java new file mode 100644 index 00000000..6430dbfc --- /dev/null +++ b/src/schematica_api/java/com/github/lunatrius/schematica/api/ISchematic.java @@ -0,0 +1,31 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package com.github.lunatrius.schematica.api; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.util.math.BlockPos; + +public interface ISchematic { + IBlockState getBlockState(BlockPos var1); + + int getWidth(); + + int getHeight(); + + int getLength(); +} diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java b/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java new file mode 100644 index 00000000..fc4b89f9 --- /dev/null +++ b/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java @@ -0,0 +1,32 @@ +/* + * 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 com.github.lunatrius.schematica.client.world; + +import com.github.lunatrius.core.util.math.MBlockPos; +import com.github.lunatrius.schematica.api.ISchematic; +import net.minecraft.block.state.IBlockState; +import net.minecraft.util.math.BlockPos; + +public class SchematicWorld { + private ISchematic schematic; + public final MBlockPos position = (MBlockPos)(Object)"cringe"; + + public ISchematic getSchematic() { + throw new LinkageError("LOL"); + } +} diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java b/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java new file mode 100644 index 00000000..e58e76b5 --- /dev/null +++ b/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java @@ -0,0 +1,29 @@ +/* + * 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 com.github.lunatrius.schematica.proxy; + +import com.github.lunatrius.schematica.client.world.SchematicWorld; +import net.minecraft.util.EnumFacing; + +public class ClientProxy extends CommonProxy { + public static SchematicWorld schematic; + + public static EnumFacing orientation; + public static EnumFacing axisFlip; + public static EnumFacing axisRotation; +} diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/proxy/CommonProxy.java b/src/schematica_api/java/com/github/lunatrius/schematica/proxy/CommonProxy.java new file mode 100644 index 00000000..eb3c034e --- /dev/null +++ b/src/schematica_api/java/com/github/lunatrius/schematica/proxy/CommonProxy.java @@ -0,0 +1,20 @@ +/* + * 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 com.github.lunatrius.schematica.proxy; + +public abstract class CommonProxy {} From 074ec333cf49a9382e7e8141aeb8717abc18243d Mon Sep 17 00:00:00 2001 From: Babbaj Date: Sun, 21 Jul 2019 21:57:59 -0400 Subject: [PATCH 510/682] clean up a bit --- scripts/proguard.pro | 4 ++-- .../baritone/utils/schematic/schematica/SchematicAdapter.java | 2 -- .../baritone/utils/schematic/schematica/SchematicaHelper.java | 1 - .../lunatrius/schematica/client/world/SchematicWorld.java | 3 --- 4 files changed, 2 insertions(+), 8 deletions(-) diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 2e10986d..4ac0f723 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -32,9 +32,9 @@ -keep class baritone.launch.** { *; } #try to keep usage of schematica in separate classes --keep class baritone.utils.schematic.schematica.* +-keep class baritone.utils.schematic.schematica.** #proguard doesnt like it when it cant find our fake schematica classes --dontwarn baritone.utils.schematic.schematica.* +-dontwarn baritone.utils.schematic.schematica.** # copy all necessary libraries into tempLibraries to build diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java index 4e399348..fd0ace8c 100644 --- a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java @@ -23,11 +23,9 @@ import com.github.lunatrius.schematica.client.world.SchematicWorld; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; -// TODO: this only works for the default rotation public final class SchematicAdapter implements ISchematic { private final SchematicWorld schematic; - public SchematicAdapter(SchematicWorld schematicWorld) { this.schematic = schematicWorld; } diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java index bf5d4678..e929d081 100644 --- a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java @@ -46,5 +46,4 @@ public enum SchematicaHelper { }); } - private static void meme(Class clazz) throws ClassNotFoundException {} } diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java b/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java index fc4b89f9..80c1b2a2 100644 --- a/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java +++ b/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java @@ -19,11 +19,8 @@ package com.github.lunatrius.schematica.client.world; import com.github.lunatrius.core.util.math.MBlockPos; import com.github.lunatrius.schematica.api.ISchematic; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.math.BlockPos; public class SchematicWorld { - private ISchematic schematic; public final MBlockPos position = (MBlockPos)(Object)"cringe"; public ISchematic getSchematic() { From 8bf977060e1c379b130d02e08b59f5d6bf4147bf Mon Sep 17 00:00:00 2001 From: Babbaj Date: Sun, 21 Jul 2019 22:06:36 -0400 Subject: [PATCH 511/682] dont need the fields --- .../baritone/utils/schematic/schematica/SchematicaHelper.java | 2 +- .../java/com/github/lunatrius/core/util/math/MBlockPos.java | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java index e929d081..9120c5ac 100644 --- a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java @@ -42,7 +42,7 @@ public enum SchematicaHelper { return Optional.ofNullable(ClientProxy.schematic) .map(world -> { MBlockPos poz = world.position; - return new Tuple<>(new SchematicAdapter(world), new BlockPos(poz.field_177962_a, poz.field_177960_b, poz.field_177961_c)); + return new Tuple<>(new SchematicAdapter(world), new BlockPos(poz.getX(), poz.getY(), poz.getZ())); }); } diff --git a/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java b/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java index 60cf6fae..338e3be4 100644 --- a/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java +++ b/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java @@ -20,10 +20,6 @@ package com.github.lunatrius.core.util.math; import net.minecraft.util.math.BlockPos; public class MBlockPos extends BlockPos { - public int field_177962_a; // x - public int field_177960_b; // y - public int field_177961_c; // z - private MBlockPos() { super(6, 6, 6); } From 21e9c0b7c11f158e4f47d474defd7f939a9110af Mon Sep 17 00:00:00 2001 From: Babbaj Date: Sun, 21 Jul 2019 22:17:21 -0400 Subject: [PATCH 512/682] add get functions --- .../lunatrius/core/util/math/MBlockPos.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java b/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java index 338e3be4..80c296cc 100644 --- a/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java +++ b/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java @@ -23,4 +23,19 @@ public class MBlockPos extends BlockPos { private MBlockPos() { super(6, 6, 6); } + + @Override + public int getX() { + throw new LinkageError("LOL"); + } + + @Override + public int getY() { + throw new LinkageError("LOL"); + } + + @Override + public int getZ() { + throw new LinkageError("LOL"); + } } From fe54372a5362a351155a3ad3193573aac37804a0 Mon Sep 17 00:00:00 2001 From: Babbaj Date: Sun, 21 Jul 2019 22:33:22 -0400 Subject: [PATCH 513/682] resolve the issue --- .../java/com/github/lunatrius/core/util/math/MBlockPos.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java b/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java index 80c296cc..280b38a6 100644 --- a/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java +++ b/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java @@ -20,7 +20,7 @@ package com.github.lunatrius.core.util.math; import net.minecraft.util.math.BlockPos; public class MBlockPos extends BlockPos { - private MBlockPos() { + MBlockPos() { super(6, 6, 6); } From 6b9737eb3fcfa4f2adc0e12b16f75324aac0af14 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 21 Jul 2019 22:04:15 -0700 Subject: [PATCH 514/682] fix double jump on paused overshot sprint ascend --- .../baritone/pathing/movement/movements/MovementAscend.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 24fe2285..cbc8cdd8 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -168,7 +168,7 @@ public class MovementAscend extends Movement { return state; } - if (ctx.playerFeet().equals(dest)) { + if (ctx.playerFeet().equals(dest) || ctx.playerFeet().equals(dest.add(getDirection().down()))) { return state.setStatus(MovementStatus.SUCCESS); } From 61147536e59f6689e3e159b7c0bbcc5d7d1add15 Mon Sep 17 00:00:00 2001 From: Babbaj Date: Mon, 22 Jul 2019 16:51:09 -0400 Subject: [PATCH 515/682] ok --- .../utils/schematic/schematica/SchematicaHelper.java | 6 +----- .../com/github/lunatrius/schematica/proxy/ClientProxy.java | 5 ----- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java index 9120c5ac..f7df0a4f 100644 --- a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java @@ -18,7 +18,6 @@ package baritone.utils.schematic.schematica; import baritone.api.utils.ISchematic; -import com.github.lunatrius.core.util.math.MBlockPos; import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.proxy.ClientProxy; import net.minecraft.util.Tuple; @@ -40,10 +39,7 @@ public enum SchematicaHelper { public static Optional> getOpenSchematic() { return Optional.ofNullable(ClientProxy.schematic) - .map(world -> { - MBlockPos poz = world.position; - return new Tuple<>(new SchematicAdapter(world), new BlockPos(poz.getX(), poz.getY(), poz.getZ())); - }); + .map(world -> new Tuple<>(new SchematicAdapter(world), world.position)); } } diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java b/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java index e58e76b5..191d0110 100644 --- a/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java +++ b/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java @@ -18,12 +18,7 @@ package com.github.lunatrius.schematica.proxy; import com.github.lunatrius.schematica.client.world.SchematicWorld; -import net.minecraft.util.EnumFacing; public class ClientProxy extends CommonProxy { public static SchematicWorld schematic; - - public static EnumFacing orientation; - public static EnumFacing axisFlip; - public static EnumFacing axisRotation; } From 4338e34734323d203bba13cd0f5edcede350f87d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 22 Jul 2019 23:37:43 -0700 Subject: [PATCH 516/682] while this is cool, nothing will ever conceivably use it --- .../utils/pathing/SegmentedCalculator.java | 110 ------------------ 1 file changed, 110 deletions(-) delete mode 100644 src/main/java/baritone/utils/pathing/SegmentedCalculator.java diff --git a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java deleted file mode 100644 index c1753a8b..00000000 --- a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.utils.pathing; - -import baritone.Baritone; -import baritone.api.pathing.calc.IPath; -import baritone.api.pathing.goals.Goal; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.PathCalculationResult; -import baritone.cache.CachedWorld; -import baritone.pathing.calc.AStarPathFinder; -import baritone.pathing.calc.AbstractNodeCostSearch; -import baritone.pathing.movement.CalculationContext; -import baritone.pathing.path.SplicedPath; -import net.minecraft.util.EnumFacing; - -import java.util.Optional; -import java.util.function.Consumer; - -/** - * Calculate and splice many path segments to reach a goal - * - * @author leijurv - */ -public class SegmentedCalculator { - private final BetterBlockPos start; - private final Goal goal; - private final CalculationContext context; - - private SegmentedCalculator(BetterBlockPos start, Goal goal, CalculationContext context) { - this.start = start; - this.goal = goal; - this.context = context; - } - - private Optional doCalc() { - Optional soFar = Optional.empty(); - while (true) { - PathCalculationResult result = segment(soFar.orElse(null)); - switch (result.getType()) { - case SUCCESS_SEGMENT: - case SUCCESS_TO_GOAL: - break; - case FAILURE: // if path calculation failed, we're done - case EXCEPTION: // if path calculation threw an exception, we're done - return soFar; - default: // CANCELLATION and null should not be possible, nothing else has access to this, so it can't have been canceled - throw new IllegalStateException(); - } - IPath segment = result.getPath().orElseThrow(IllegalStateException::new); // path calculation result type is SUCCESS_SEGMENT, so the path must be present - IPath combined = soFar.map(previous -> (IPath) SplicedPath.trySplice(previous, segment, true).orElseThrow(IllegalStateException::new)).orElse(segment); - loadAdjacent(combined.getDest().getX(), combined.getDest().getZ()); - soFar = Optional.of(combined); - if (result.getType() == PathCalculationResult.Type.SUCCESS_TO_GOAL) { - return soFar; - } - } - } - - private void loadAdjacent(int blockX, int blockZ) { - BetterBlockPos bp = new BetterBlockPos(blockX, 64, blockZ); - CachedWorld cached = (CachedWorld) context.getBaritone().getPlayerContext().worldData().getCachedWorld(); - for (int i = 0; i < 4; i++) { - // pathing thread is not allowed to load new cached regions from disk - // it checks if every chunk is loaded before getting blocks from it - // so you see path segments ending at multiples of 512 (plus or minus one) on either x or z axis - // this loads every adjacent chunk to the segment end, so it can continue into the next cached region - BetterBlockPos toLoad = bp.offset(EnumFacing.byHorizontalIndex(i), 16); - cached.tryLoadFromDisk(toLoad.x >> 9, toLoad.z >> 9); - } - } - - private PathCalculationResult segment(IPath previous) { - BetterBlockPos segmentStart = previous != null ? previous.getDest() : start; - AbstractNodeCostSearch search = new AStarPathFinder(segmentStart.x, segmentStart.y, segmentStart.z, goal, new Favoring(previous, context), context); // this is on another thread, so cannot include mob avoidances. - return search.calculate(Baritone.settings().primaryTimeoutMS.value, Baritone.settings().failureTimeoutMS.value); // use normal time settings, not the plan ahead settings, so as to not overwhelm the computer - } - - public static void calculateSegmentsThreaded(BetterBlockPos start, Goal goal, CalculationContext context, Consumer onCompletion, Runnable onFailure) { - Baritone.getExecutor().execute(() -> { - Optional result; - try { - result = new SegmentedCalculator(start, goal, context).doCalc(); - } catch (Exception ex) { - ex.printStackTrace(); - result = Optional.empty(); - } - if (result.isPresent()) { - onCompletion.accept(result.get()); - } else { - onFailure.run(); - } - }); - } -} From 784bc52d6df3dc7c1e494f8b34d6e4e5750e72b3 Mon Sep 17 00:00:00 2001 From: Babbaj Date: Tue, 23 Jul 2019 02:46:53 -0400 Subject: [PATCH 517/682] add to usage.md --- USAGE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/USAGE.md b/USAGE.md index f628d542..916adc72 100644 --- a/USAGE.md +++ b/USAGE.md @@ -28,6 +28,7 @@ Some common examples: - `follow playerName` to follow a player. `follow` to follow the entity you're looking at (only works if it hitting range). `followplayers` to follow any players in range (combine with Kill Aura for a fun time). - `save waypointName` to save a waypoint. `goto waypointName` to go to it. - `build` to build a schematic. `build blah` will load `schematics/blah.schematic` and build it with the origin being your player feet. `build blah x y z` to set the origin. Any of those can be relative to your player (`~ 69 ~-420` would build at x=player x, y=69, z=player z-420). +- 'schematica' to build the schematic that is currently open in schematica - `tunnel` to dig just straight ahead and make a tunnel - `farm` to automatically harvest, replant, or bone meal crops - `axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120). From 821e73c1d34b44c1e801fb34ebf502db7ae68060 Mon Sep 17 00:00:00 2001 From: Babbaj Date: Tue, 23 Jul 2019 02:48:40 -0400 Subject: [PATCH 518/682] fix usage.md --- USAGE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/USAGE.md b/USAGE.md index 916adc72..865670b6 100644 --- a/USAGE.md +++ b/USAGE.md @@ -28,7 +28,7 @@ Some common examples: - `follow playerName` to follow a player. `follow` to follow the entity you're looking at (only works if it hitting range). `followplayers` to follow any players in range (combine with Kill Aura for a fun time). - `save waypointName` to save a waypoint. `goto waypointName` to go to it. - `build` to build a schematic. `build blah` will load `schematics/blah.schematic` and build it with the origin being your player feet. `build blah x y z` to set the origin. Any of those can be relative to your player (`~ 69 ~-420` would build at x=player x, y=69, z=player z-420). -- 'schematica' to build the schematic that is currently open in schematica +- `schematica` to build the schematic that is currently open in schematica - `tunnel` to dig just straight ahead and make a tunnel - `farm` to automatically harvest, replant, or bone meal crops - `axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120). From 7000b6cda2399cac853f1cf68896d88d8c1d2c74 Mon Sep 17 00:00:00 2001 From: Babbaj Date: Tue, 23 Jul 2019 02:56:24 -0400 Subject: [PATCH 519/682] fix crash --- .../baritone/utils/schematic/schematica/SchematicaHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java index f7df0a4f..63b85670 100644 --- a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java @@ -32,7 +32,7 @@ public enum SchematicaHelper { try { Class.forName(Schematica.class.getName()); return true; - } catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException | NoClassDefFoundError ex) { return false; } } From 0e51a731496474b73fe772936c3041c38e91d19c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 23 Jul 2019 11:53:21 -0700 Subject: [PATCH 520/682] instanceof BlockLiquid checks this --- src/main/java/baritone/pathing/movement/MovementHelper.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 97a768ab..520baa81 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -254,7 +254,6 @@ public interface MovementHelper extends ActionCosts, Helper { static boolean avoidWalkingInto(Block block) { return block instanceof BlockLiquid - || block instanceof BlockDynamicLiquid || block == Blocks.MAGMA || block == Blocks.CACTUS || block == Blocks.FIRE From 6dc7a7788e90ddfa32419570473d393b5e3edecc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 23 Jul 2019 22:30:04 -0700 Subject: [PATCH 521/682] install for 1.14.4 --- README.md | 5 ++++- SETUP.md | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index db5be4c2..68d4af7a 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,9 @@ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) [![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone/) [![GitHub All Releases](https://img.shields.io/github/downloads/cabaletta/baritone/total.svg)](https://github.com/cabaletta/baritone/releases/) -[![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://github.com/cabaletta/baritone/tree/master/) +[![Minecraft](https://img.shields.io/badge/MC-1.12.2-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/master/) [![Minecraft](https://img.shields.io/badge/MC-1.13.2-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.13.2/) +[![Minecraft](https://img.shields.io/badge/MC-1.14.4-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.14.4/) [![Code of Conduct](https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg?style=flat)](https://github.com/cabaletta/baritone/blob/master/CODE_OF_CONDUCT.md) [![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle) [![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues/) @@ -31,6 +32,8 @@ Baritone is the pathfinding system used in [Impact](https://impactdevelopment.gi The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the forge jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. +For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1). + 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 and 1.13.2. 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). diff --git a/SETUP.md b/SETUP.md index aca5f6c5..3492beaa 100644 --- a/SETUP.md +++ b/SETUP.md @@ -2,6 +2,8 @@ The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. +For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1). + Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. ## Prebuilt official releases From f5b4de023f8a295dac5321ee7e2ef060410c27ed Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 24 Jul 2019 15:33:39 -0700 Subject: [PATCH 522/682] update usage stuff --- USAGE.md | 5 ++- .../api/utils/ExampleBaritoneControl.java | 45 +++++-------------- 2 files changed, 13 insertions(+), 37 deletions(-) diff --git a/USAGE.md b/USAGE.md index 865670b6..b01bf3fa 100644 --- a/USAGE.md +++ b/USAGE.md @@ -18,14 +18,15 @@ To toggle a boolean setting, just say its name in chat (for example saying `allo Some common examples: - `thisway 1000` then `path` to go in the direction you're facing for a thousand blocks -- `goal x y z` or `goal x z` or `goal y`, then `path` to go to a certain coordinate +- `goal x y z` or `goal x z` or `goal y`, then `path` to set a goal to a certain coordinate then path to it +- `goto x y z` or `goto x z` or `goto y` to go to a certain coordinate (in a single step, starts going immediately) - `goal` to set the goal to your player's feet - `goal clear` to clear the goal - `cancel` or `stop` to stop everything - `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part) - `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) - `click` to click your destination on the screen. Right click path to on top of the block, left click to path into it (either at foot level or eye level), and left click and drag to clear all blocks from an area. -- `follow playerName` to follow a player. `follow` to follow the entity you're looking at (only works if it hitting range). `followplayers` to follow any players in range (combine with Kill Aura for a fun time). +- `follow playerName` to follow a player. `followplayers` to follow any players in range (combine with Kill Aura for a fun time). `followentities` to follow any entities. `followentity pig` to follow entities of a specific type. - `save waypointName` to save a waypoint. `goto waypointName` to go to it. - `build` to build a schematic. `build blah` will load `schematics/blah.schematic` and build it with the origin being your player feet. `build blah x y z` to set the origin. Any of those can be relative to your player (`~ 69 ~-420` would build at x=player x, y=69, z=player z-420). - `schematica` to build the schematic that is currently open in schematica diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 46300150..bfa6a640 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -40,44 +40,16 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ReportedException; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.event.ClickEvent; import net.minecraft.world.chunk.Chunk; import java.nio.file.Path; import java.util.*; public class ExampleBaritoneControl implements Helper, AbstractGameEventListener { - - private static final String HELP_MSG = - "baritone - Output settings into chat\n" + - "settings - Same as baritone\n" + - "goal - Create a goal (one number is '', two is ' ', three is ' , 'clear' to clear)\n" + - "path - Go towards goal\n" + - "repack - (debug) Repacks chunk cache\n" + - "rescan - (debug) Same as repack\n" + - "axis - Paths towards the closest axis or diagonal axis, at y=120\n" + - "cancel - Cancels current path\n" + - "forcecancel - sudo cancel (only use if very glitched, try toggling 'pause' first)\n" + - "gc - Calls System.gc();\n" + - "invert - Runs away from the goal instead of towards it\n" + - "follow - Follows a player 'follow username'\n" + - "reloadall - (debug) Reloads chunk cache\n" + - "saveall - (debug) Saves chunk cache\n" + - "find - (debug) outputs how many blocks of a certain type are within the cache\n" + - "mine - Paths to and mines specified blocks 'mine x_ore y_ore ...'\n" + - "thisway - Creates a goal X blocks where you're facing\n" + - "list - Lists waypoints under a category\n" + - "get - Same as list\n" + - "show - Same as list\n" + - "save - Saves a waypoint (works but don't try to make sense of it)\n" + - "delete - Deletes a waypoint\n" + - "goto - Paths towards specified block or waypoint\n" + - "spawn - Paths towards world spawn or your most recent bed right-click\n" + - "sethome - Sets \"home\"\n" + - "home - Paths towards \"home\" \n" + - "costs - (debug) all movement costs from current location\n" + - "damn - Daniel\n" + - "Go to https://github.com/cabaletta/baritone/blob/master/USAGE.md for more information"; - private static final String COMMAND_PREFIX = "#"; public final IBaritone baritone; @@ -148,9 +120,12 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return true; } if (msg.equals("") || msg.equals("help") || msg.equals("?")) { - for (String line : HELP_MSG.split("\n")) { - logDirect(line); - } + ITextComponent component = MESSAGE_PREFIX.createCopy(); + component.getStyle().setColor(TextFormatting.GRAY); + TextComponentString helpLink = new TextComponentString(" Click here for instructions on how to use Baritone (https://github.com/cabaletta/baritone/blob/master/USAGE.md)"); + helpLink.getStyle().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://github.com/cabaletta/baritone/blob/master/USAGE.md")); + component.appendSibling(helpLink); + BaritoneAPI.getSettings().logger.value.accept(component); return true; } if (msg.contains(" ")) { From bc849daccbb717c75a4fa8f8de28026c375ee99e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 24 Jul 2019 15:38:14 -0700 Subject: [PATCH 523/682] v1.2.8 --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 1264f0fe..05b95395 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.2.7' +version '1.2.8' buildscript { repositories { @@ -59,7 +59,7 @@ sourceSets { schematica_api { compileClasspath += main.compileClasspath } - + main { compileClasspath += schematica_api.output } From 1c5e0b4d688c740decf0107ee6f3807c29b7d1fc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 25 Jul 2019 23:02:44 -0700 Subject: [PATCH 524/682] bump impact badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 68d4af7a..64c2a0ba 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ ![Lines of Code](https://tokei.rs/b1/github/cabaletta/baritone?category=code) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) -[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.6%20/%20v1.3.2-brightgreen.svg)](https://impactdevelopment.github.io/) +[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.8%20/%20v1.3.4-brightgreen.svg)](https://impactdevelopment.github.io/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) From 1b481c6765d305300d2fadad4c212aa04319e85c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 26 Jul 2019 15:14:04 -0700 Subject: [PATCH 525/682] aristois badge --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 64c2a0ba..67cdb46c 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.8%20/%20v1.3.4-brightgreen.svg)](https://impactdevelopment.github.io/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/) +[![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%22integration-v1.3.4-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com/) From fe6ca97f21a4482bfa915d2d0d0c40e74db5af69 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 26 Jul 2019 15:14:35 -0700 Subject: [PATCH 526/682] whoops --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 67cdb46c..552d5f80 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.8%20/%20v1.3.4-brightgreen.svg)](https://impactdevelopment.github.io/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/) -[![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%22integration-v1.3.4-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api) +[![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%20integration-v1.3.4-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/) [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com/) From 07cbc47fb2bac6d15b460b07493d7e5d175d3216 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 27 Jul 2019 23:51:23 -0700 Subject: [PATCH 527/682] extra line --- src/main/java/baritone/process/BuilderProcess.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 5317c39a..99edba4a 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -434,7 +434,6 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } } - Goal goal = assemble(bcc, approxPlacable.subList(0, 9)); if (goal == null) { goal = assemble(bcc, approxPlacable); // we're far away, so assume that we have our whole inventory to recalculate placable properly From 551b6b88d2bdafa38a3ca63a18b1fd380c39ce74 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 28 Jul 2019 00:19:14 -0700 Subject: [PATCH 528/682] EXTREMELY old comment that is no longer true --- src/main/java/baritone/pathing/path/PathExecutor.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index e03a20cc..97bee424 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -43,8 +43,7 @@ import java.util.*; import static baritone.api.pathing.movement.MovementStatus.*; /** - * Behavior to execute a precomputed path. Does not (yet) deal with path segmentation or stitching - * or cutting (jumping onto the next path if it starts with a backtrack of this path's ending) + * Behavior to execute a precomputed path * * @author leijurv */ From 6f251b64f1fbeea2be52f31e7356705fdbe39837 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 29 Jul 2019 17:35:06 -0700 Subject: [PATCH 529/682] i am very stupid --- src/api/java/baritone/api/utils/MyChunkPos.java | 2 +- src/main/java/baritone/process/ExploreProcess.java | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/MyChunkPos.java b/src/api/java/baritone/api/utils/MyChunkPos.java index 1df7481d..8b61012f 100644 --- a/src/api/java/baritone/api/utils/MyChunkPos.java +++ b/src/api/java/baritone/api/utils/MyChunkPos.java @@ -27,7 +27,7 @@ public class MyChunkPos { @SerializedName("x") public int x; - @SerializedName("y") + @SerializedName("z") public int z; @Override diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 54c2a698..3fa3d413 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -140,6 +140,9 @@ public final class ExploreProcess extends BaritoneProcessHelper implements IExpl centers.add(new BlockPos(centerX, 0, centerZ)); } } + if (dist % 10 == 0) { + count = Math.min(filter.countRemain(), Baritone.settings().exploreChunkSetMinimumSize.value); + } if (centers.size() >= count) { return centers.stream().map(pos -> createGoal(pos.getX(), pos.getZ())).toArray(Goal[]::new); } From 06c62029c5455107ac88f0d4b1a1bb286579c92d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 30 Jul 2019 20:04:50 -0700 Subject: [PATCH 530/682] not iffy --- src/main/java/baritone/Baritone.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 5838134a..a4b2d436 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -148,12 +148,12 @@ public class Baritone implements IBaritone { } @Override - public CustomGoalProcess getCustomGoalProcess() { // Iffy + public CustomGoalProcess getCustomGoalProcess() { return this.customGoalProcess; } @Override - public GetToBlockProcess getGetToBlockProcess() { // Iffy + public GetToBlockProcess getGetToBlockProcess() { return this.getToBlockProcess; } From bba4c091954172b6a002f455d3937db61f642f84 Mon Sep 17 00:00:00 2001 From: Conner Date: Tue, 30 Jul 2019 21:07:26 -0700 Subject: [PATCH 531/682] Add parkour ascend --- src/api/java/baritone/api/Settings.java | 7 +++ .../pathing/calc/AbstractNodeCostSearch.java | 2 +- .../pathing/movement/CalculationContext.java | 2 + .../java/baritone/pathing/movement/Moves.java | 8 +-- .../movement/movements/MovementParkour.java | 58 ++++++++++++++----- 5 files changed, 56 insertions(+), 21 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 031443f4..4ea5f8da 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -124,6 +124,13 @@ public final class Settings { */ public final Setting allowJumpAt256 = new Setting<>(false); + /** + * This should be monetized it's so good + *

+ * Defaults to true, but only actually takes effect if allowParkour is also true + */ + public final Setting allowParkourAscend = new Setting<>(true); + /** * Allow descending diagonally *

diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 30282748..a67384ac 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -127,7 +127,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder, Helper { return new PathCalculationResult(PathCalculationResult.Type.SUCCESS_SEGMENT, path); } } catch (Exception e) { - Helper.HELPER.logDebug("Pathing exception: " + e); + Helper.HELPER.logDirect("Pathing exception: " + e); e.printStackTrace(); return new PathCalculationResult(PathCalculationResult.Type.EXCEPTION); } finally { diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 4dda3283..2f82513e 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -58,6 +58,7 @@ public class CalculationContext { public final boolean allowParkour; public final boolean allowParkourPlace; public final boolean allowJumpAt256; + public final boolean allowParkourAscend; public final boolean assumeWalkOnWater; public final boolean allowDiagonalDescend; public final boolean allowDownward; @@ -90,6 +91,7 @@ public class CalculationContext { this.allowParkour = Baritone.settings().allowParkour.value; this.allowParkourPlace = Baritone.settings().allowParkourPlace.value; this.allowJumpAt256 = Baritone.settings().allowJumpAt256.value; + this.allowParkourAscend = Baritone.settings().allowParkourAscend.value; this.assumeWalkOnWater = Baritone.settings().assumeWalkOnWater.value; this.allowDiagonalDescend = Baritone.settings().allowDiagonalDescend.value; this.allowDownward = Baritone.settings().allowDownward.value; diff --git a/src/main/java/baritone/pathing/movement/Moves.java b/src/main/java/baritone/pathing/movement/Moves.java index c626327e..da278436 100644 --- a/src/main/java/baritone/pathing/movement/Moves.java +++ b/src/main/java/baritone/pathing/movement/Moves.java @@ -276,7 +276,7 @@ public enum Moves { } }, - PARKOUR_NORTH(0, 0, -4, true, false) { + PARKOUR_NORTH(0, 0, -4, true, true) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { return MovementParkour.cost(context, src, EnumFacing.NORTH); @@ -288,7 +288,7 @@ public enum Moves { } }, - PARKOUR_SOUTH(0, 0, +4, true, false) { + PARKOUR_SOUTH(0, 0, +4, true, true) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { return MovementParkour.cost(context, src, EnumFacing.SOUTH); @@ -300,7 +300,7 @@ public enum Moves { } }, - PARKOUR_EAST(+4, 0, 0, true, false) { + PARKOUR_EAST(+4, 0, 0, true, true) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { return MovementParkour.cost(context, src, EnumFacing.EAST); @@ -312,7 +312,7 @@ public enum Moves { } }, - PARKOUR_WEST(-4, 0, 0, true, false) { + PARKOUR_WEST(-4, 0, 0, true, true) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { return MovementParkour.cost(context, src, EnumFacing.WEST); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 88ffb1d9..fc170e62 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -43,18 +43,20 @@ public class MovementParkour extends Movement { private final EnumFacing direction; private final int dist; + private final boolean ascend; - private MovementParkour(IBaritone baritone, BetterBlockPos src, int dist, EnumFacing dir) { - super(baritone, src, src.offset(dir, dist), EMPTY, src.offset(dir, dist).down()); + private MovementParkour(IBaritone baritone, BetterBlockPos src, int dist, EnumFacing dir, boolean ascend) { + super(baritone, src, src.offset(dir, dist).up(ascend ? 1 : 0), EMPTY, src.offset(dir, dist).down(ascend ? 0 : 1)); this.direction = dir; this.dist = dist; + this.ascend = ascend; } public static MovementParkour cost(CalculationContext context, BetterBlockPos src, EnumFacing direction) { MutableMoveResult res = new MutableMoveResult(); cost(context, src.x, src.y, src.z, direction, res); int dist = Math.abs(res.x - src.x) + Math.abs(res.z - src.z); - return new MovementParkour(context.getBaritone(), src, dist, direction); + return new MovementParkour(context.getBaritone(), src, dist, direction, res.y != src.y); } public static void cost(CalculationContext context, int x, int y, int z, EnumFacing dir, MutableMoveResult res) { @@ -103,19 +105,35 @@ public class MovementParkour extends Movement { } } for (int i = 2; i <= maxJump; i++) { - // TODO perhaps dest.up(3) doesn't need to be fullyPassable, just canWalkThrough, possibly? - for (int y2 = 0; y2 < 4; y2++) { - if (!MovementHelper.fullyPassable(context, x + xDiff * i, y + y2, z + zDiff * i)) { - return; - } + int destX = x + xDiff * i; + int destZ = z + zDiff * i; + if (!MovementHelper.fullyPassable(context, destX, y + 1, destZ)) { + return; } - IBlockState landingOn = context.bsi.get0(x + xDiff * i, y - 1, z + zDiff * i); + if (!MovementHelper.fullyPassable(context, destX, y + 2, destZ)) { + return; + } + if (!MovementHelper.fullyPassable(context, destX, y, destZ)) { + if (i <= 3 && context.allowParkourAscend && context.canSprint && MovementHelper.canWalkOn(context.bsi, destX, y, destZ) && checkOvershootSafety(context.bsi, destX + xDiff, y + 1, destZ + zDiff)) { + res.x = destX; + res.y = y + 1; + res.z = destZ; + res.cost = costFromJumpDistance(i) + context.jumpPenalty; + } + return; + } + IBlockState landingOn = context.bsi.get0(destX, y - 1, destZ); // farmland needs to be canwalkon otherwise farm can never work at all, but we want to specifically disallow ending a jumy on farmland haha - if (landingOn.getBlock() != Blocks.FARMLAND && MovementHelper.canWalkOn(context.bsi, x + xDiff * i, y - 1, z + zDiff * i, landingOn)) { - res.x = x + xDiff * i; - res.y = y; - res.z = z + zDiff * i; - res.cost = costFromJumpDistance(i) + context.jumpPenalty; + if (landingOn.getBlock() != Blocks.FARMLAND && MovementHelper.canWalkOn(context.bsi, destX, y - 1, destZ, landingOn)) { + if (checkOvershootSafety(context.bsi, destX + xDiff, y, destZ + zDiff)) { + res.x = destX; + res.y = y; + res.z = destZ; + res.cost = costFromJumpDistance(i) + context.jumpPenalty; + } + return; + } + if (!MovementHelper.fullyPassable(context, destX, y + 3, destZ)) { return; } } @@ -136,6 +154,9 @@ public class MovementParkour extends Movement { if (!MovementHelper.isReplacable(destX, y - 1, destZ, toReplace, context.bsi)) { return; } + if (!checkOvershootSafety(context.bsi, destX + xDiff, y, destZ + zDiff)) { + return; + } for (int i = 0; i < 5; i++) { int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); int againstY = y - 1 + HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP[i].getYOffset(); @@ -153,6 +174,11 @@ public class MovementParkour extends Movement { } } + private static boolean checkOvershootSafety(BlockStateInterface bsi, int x, int y, int z) { + // we're going to walk into these two blocks after the landing of the parkour anyway, so make sure they aren't avoidWalkingInto + return !MovementHelper.avoidWalkingInto(bsi.get0(x, y, z).getBlock()) && !MovementHelper.avoidWalkingInto(bsi.get0(x, y + 1, z).getBlock()); + } + private static double costFromJumpDistance(int dist) { switch (dist) { case 2: @@ -211,7 +237,7 @@ public class MovementParkour extends Movement { logDebug("sorry"); return state.setStatus(MovementStatus.UNREACHABLE); } - if (dist >= 4) { + if (dist >= 4 || ascend) { state.setInput(Input.SPRINT, true); } MovementHelper.moveTowards(ctx, state, dest); @@ -231,7 +257,7 @@ public class MovementParkour extends Movement { // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory state.setInput(Input.CLICK_RIGHT, true); } - if (dist == 3) { // this is a 2 block gap, dest = src + direction * 3 + if (dist == 3 && !ascend) { // this is a 2 block gap, dest = src + direction * 3 double xDiff = (src.x + 0.5) - ctx.player().posX; double zDiff = (src.z + 0.5) - ctx.player().posZ; double distFromStart = Math.max(Math.abs(xDiff), Math.abs(zDiff)); From 9541a45451aefa87a4534bc2aa19a8de202bada0 Mon Sep 17 00:00:00 2001 From: Conner Date: Tue, 30 Jul 2019 21:37:50 -0700 Subject: [PATCH 532/682] Resolve comments --- .../baritone/pathing/movement/movements/MovementParkour.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index fc170e62..40cf2565 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -56,7 +56,7 @@ public class MovementParkour extends Movement { MutableMoveResult res = new MutableMoveResult(); cost(context, src.x, src.y, src.z, direction, res); int dist = Math.abs(res.x - src.x) + Math.abs(res.z - src.z); - return new MovementParkour(context.getBaritone(), src, dist, direction, res.y != src.y); + return new MovementParkour(context.getBaritone(), src, dist, direction, res.y > src.y); } public static void cost(CalculationContext context, int x, int y, int z, EnumFacing dir, MutableMoveResult res) { @@ -118,7 +118,7 @@ public class MovementParkour extends Movement { res.x = destX; res.y = y + 1; res.z = destZ; - res.cost = costFromJumpDistance(i) + context.jumpPenalty; + res.cost = i * SPRINT_ONE_BLOCK_COST + context.jumpPenalty; } return; } @@ -257,6 +257,7 @@ public class MovementParkour extends Movement { // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory state.setInput(Input.CLICK_RIGHT, true); } + // prevent jumping too late by checking for ascend if (dist == 3 && !ascend) { // this is a 2 block gap, dest = src + direction * 3 double xDiff = (src.x + 0.5) - ctx.player().posX; double zDiff = (src.z + 0.5) - ctx.player().posZ; From 5f721b544e2b46682f10a143f38ccd79b39554b8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 31 Jul 2019 20:47:46 -0700 Subject: [PATCH 533/682] smh conner, imagine getting the same block position 2x without caching --- .../baritone/pathing/movement/movements/MovementParkour.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 40cf2565..736e6ee1 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -113,8 +113,9 @@ public class MovementParkour extends Movement { if (!MovementHelper.fullyPassable(context, destX, y + 2, destZ)) { return; } - if (!MovementHelper.fullyPassable(context, destX, y, destZ)) { - if (i <= 3 && context.allowParkourAscend && context.canSprint && MovementHelper.canWalkOn(context.bsi, destX, y, destZ) && checkOvershootSafety(context.bsi, destX + xDiff, y + 1, destZ + zDiff)) { + IBlockState destInto = context.bsi.get0(destX, y, destZ); + if (!MovementHelper.fullyPassable(destInto)) { + if (i <= 3 && context.allowParkourAscend && context.canSprint && MovementHelper.canWalkOn(context.bsi, destX, y, destZ, destInto) && checkOvershootSafety(context.bsi, destX + xDiff, y + 1, destZ + zDiff)) { res.x = destX; res.y = y + 1; res.z = destZ; From 01c0e321b598f48dc3a90bc5130057d37abab55b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 31 Jul 2019 20:58:45 -0700 Subject: [PATCH 534/682] what was i THINKING --- src/main/java/baritone/behavior/PathingBehavior.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index a5ffc598..e061f757 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -135,7 +135,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, ) { // when it was *just* started, currentBest will be empty so we need to also check calcFrom since that's always present inProgress.cancel(); // cancellation doesn't dispatch any events - inProgress = null; // this is safe since we hold both locks } } } From 8bcbd0231e726d64be6724295c5d68492eec4cb4 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 31 Jul 2019 21:45:57 -0700 Subject: [PATCH 535/682] bye --- src/main/java/baritone/behavior/PathingBehavior.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index e061f757..7a23222f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -360,12 +360,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } } - /*public void secretCursedFunctionDoNotCall(IPath path) { - synchronized (pathPlanLock) { - current = new PathExecutor(this, path); - } - }*/ - public CalculationContext secretInternalGetCalculationContext() { return context; } From 19fe29ad1edba3033063e0884bca8a3ad99bb5e3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 31 Jul 2019 22:17:44 -0700 Subject: [PATCH 536/682] i am stupid --- src/main/java/baritone/pathing/movement/MovementHelper.java | 2 +- .../baritone/pathing/movement/movements/MovementParkour.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 520baa81..b7dd442d 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -506,7 +506,7 @@ public interface MovementHelper extends ActionCosts, Helper { return PlaceResult.NO_OPTION; } double faceX = (placeAt.getX() + against1.getX() + 1.0D) * 0.5D; - double faceY = (placeAt.getY() + against1.getY() + 1.0D) * 0.5D; + double faceY = (placeAt.getY() + against1.getY() + 0.5D) * 0.5D; double faceZ = (placeAt.getZ() + against1.getZ() + 1.0D) * 0.5D; Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance()); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 736e6ee1..8b33d68a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -198,7 +198,7 @@ public class MovementParkour extends Movement { public double calculateCost(CalculationContext context) { MutableMoveResult res = new MutableMoveResult(); cost(context, src.x, src.y, src.z, direction, res); - if (res.x != dest.x || res.z != dest.z) { + if (res.x != dest.x || res.y != dest.y || res.z != dest.z) { return COST_INF; } return res.cost; From 014d3b3a99ba306c8131f79438f466347fcfa7db Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 1 Aug 2019 23:47:12 -0700 Subject: [PATCH 537/682] goal can never be null --- src/main/java/baritone/behavior/PathingBehavior.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 7a23222f..7219175e 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -338,7 +338,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } // just cancel the current path - public void secretInternalSegmentCancel() { + private void secretInternalSegmentCancel() { queuePathEvent(PathEvent.CANCELED); synchronized (pathPlanLock) { getInProgress().ifPresent(AbstractNodeCostSearch::cancel); @@ -488,7 +488,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } } if (talkAboutIt && current != null && current.getPath() != null) { - if (goal == null || goal.isInGoal(current.getPath().getDest())) { + if (goal.isInGoal(current.getPath().getDest())) { logDebug("Finished finding a path from " + start + " to " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered"); } else { logDebug("Found path segment from " + start + " towards " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered"); @@ -501,7 +501,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, }); } - public static AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, IPath previous, CalculationContext context) { + private static AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, IPath previous, CalculationContext context) { Goal transformed = goal; if (Baritone.settings().simplifyUnloadedYCoord.value && goal instanceof IGoalRenderPos) { BlockPos pos = ((IGoalRenderPos) goal).getGoalPos(); From 081fae98c4f98c262ea68bd4a353d7033a9cb532 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 1 Aug 2019 23:47:32 -0700 Subject: [PATCH 538/682] 1 year later --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 552d5f80..bdc405f1 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Barito 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 and 1.13.2. 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). -Have committed at least once a day for the last 11 months =D 🦀 +Have committed at least once a day from Aug 1 2018 to Aug 1 2019. 1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2 From d402ba61cc425c25dcfe70c7c58d929218f258a9 Mon Sep 17 00:00:00 2001 From: Howard Stark Date: Thu, 8 Aug 2019 09:36:55 -1000 Subject: [PATCH 539/682] Disable lighting on path render --- src/main/java/baritone/utils/PathRenderer.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index b0924cc1..b0157247 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -122,6 +122,7 @@ public final class PathRenderer implements Helper { public static void drawPath(IPath path, int startIndex, Entity player, float partialTicks, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) { GlStateManager.enableBlend(); + GlStateManager.disableLighting(); GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F); GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); @@ -176,6 +177,7 @@ public final class PathRenderer implements Helper { //GlStateManager.color(0.0f, 0.0f, 0.0f, 0.4f); GlStateManager.depthMask(true); GlStateManager.enableTexture2D(); + GlStateManager.enableLighting(); GlStateManager.disableBlend(); } From 17a07ba85e043588c67f59065c6b767676e1ebc7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 8 Aug 2019 09:56:06 -1000 Subject: [PATCH 540/682] better render --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index bfa6a640..73f63e0c 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -370,7 +370,8 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } if (msg.equals("render")) { BetterBlockPos pf = ctx.playerFeet(); - Minecraft.getMinecraft().renderGlobal.markBlockRangeForRenderUpdate(pf.x - 500, pf.y - 500, pf.z - 500, pf.x + 500, pf.y + 500, pf.z + 500); + int dist = (Minecraft.getMinecraft().gameSettings.renderDistanceChunks + 1) * 16; + Minecraft.getMinecraft().renderGlobal.markBlockRangeForRenderUpdate(pf.x - dist, pf.y - 256, pf.z - dist, pf.x + dist, pf.y + 256, pf.z + dist); logDirect("okay"); return true; } From ac6c413fb888cb53e6a357e11f00ade8362c7810 Mon Sep 17 00:00:00 2001 From: Friedolin2000 Date: Thu, 8 Aug 2019 22:45:18 +0200 Subject: [PATCH 541/682] dimensional coords extension --- .../api/utils/ExampleBaritoneControl.java | 42 +++++++++++++++---- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index bfa6a640..d03c6fa4 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -44,11 +44,14 @@ import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; +import net.minecraft.world.DimensionType; import net.minecraft.world.chunk.Chunk; import java.nio.file.Path; import java.util.*; +import static org.apache.commons.lang3.StringUtils.isNumeric; + public class ExampleBaritoneControl implements Helper, AbstractGameEventListener { private static final String COMMAND_PREFIX = "#"; @@ -260,7 +263,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener try { String[] coords = msg.substring("build".length()).trim().split(" "); file = coords[0] + ".schematic"; - origin = new BlockPos(parseOrDefault(coords[1], ctx.playerFeet().x), parseOrDefault(coords[2], ctx.playerFeet().y), parseOrDefault(coords[3], ctx.playerFeet().z)); + origin = new BlockPos(parseOrDefault(coords[1], ctx.playerFeet().x, 1), parseOrDefault(coords[2], ctx.playerFeet().y, 1), parseOrDefault(coords[3], ctx.playerFeet().z, 1)); } catch (Exception ex) { file = msg.substring(5).trim() + ".schematic"; origin = ctx.playerFeet(); @@ -672,8 +675,8 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return false; } - private int parseOrDefault(String str, int i) { - return str.equals("~") ? i : str.startsWith("~") ? Integer.parseInt(str.substring(1)) + i : Integer.parseInt(str); + private int parseOrDefault(String str, int i, double dimensionFactor) { + return str.equals("~") ? i : str.startsWith("~") ? (int) (Integer.parseInt(str.substring(1)) * dimensionFactor) + i : (int) (Integer.parseInt(str) * dimensionFactor); } private void log(List stacks) { @@ -688,18 +691,23 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener Goal goal; try { BetterBlockPos playerFeet = ctx.playerFeet(); - switch (params.length) { + + int length = params.length - 1; // length has to be smaller when a dimension parameter is added + if (params.length < 1 || (isNumeric(params[params.length - 1]) || params[params.length - 1].startsWith("~"))) { + length = params.length; + } + switch (length) { case 0: goal = new GoalBlock(playerFeet); break; case 1: - goal = new GoalYLevel(parseOrDefault(params[0], playerFeet.y)); + goal = new GoalYLevel(parseOrDefault(params[0], playerFeet.y, 1)); break; case 2: - goal = new GoalXZ(parseOrDefault(params[0], playerFeet.x), parseOrDefault(params[1], playerFeet.z)); + goal = new GoalXZ(parseOrDefault(params[0], playerFeet.x, calculateDimensionFactor(params[params.length - 1])), parseOrDefault(params[1], playerFeet.z, calculateDimensionFactor(params[params.length - 1]))); break; case 3: - goal = new GoalBlock(new BlockPos(parseOrDefault(params[0], playerFeet.x), parseOrDefault(params[1], playerFeet.y), parseOrDefault(params[2], playerFeet.z))); + goal = new GoalBlock(new BlockPos(parseOrDefault(params[0], playerFeet.x, calculateDimensionFactor(params[params.length - 1])), parseOrDefault(params[1], playerFeet.y, 1), parseOrDefault(params[2], playerFeet.z, calculateDimensionFactor(params[params.length - 1])))); break; default: logDirect("unable to understand lol"); @@ -711,4 +719,24 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } return goal; } + + + + private double calculateDimensionFactor(String to) { + return Math.pow(8, ctx.world().provider.getDimensionType().getId() - getDimensionByName(to.toLowerCase()).getId()); + } + + private DimensionType getDimensionByName(String name) { + if ("the_end".contains(name)) { + return DimensionType.THE_END; + } + if ("the_overworld".contains(name) || "surface".contains(name)) { + return DimensionType.OVERWORLD; + } + if ("the_nether".contains(name) || "hell".contains(name)) { + return DimensionType.NETHER; + } + return ctx.world().provider.getDimensionType(); + } + } From 3d221dcda45b09e99e51a6b8b0e982930644fb3b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 8 Aug 2019 18:04:49 -1000 Subject: [PATCH 542/682] antiquated and does more harm than good --- .../baritone/pathing/movement/movements/MovementParkour.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 8b33d68a..8e660aff 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -229,10 +229,6 @@ public class MovementParkour extends Movement { if (state.getStatus() != MovementStatus.RUNNING) { return state; } - if (ctx.player().isHandActive()) { - logDebug("Pausing parkour since hand is active"); - return state; - } if (ctx.playerFeet().y < src.y) { // we have fallen logDebug("sorry"); From 4c935fc44784b5020b7d23dfdea68c67f059d755 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 8 Aug 2019 18:09:25 -1000 Subject: [PATCH 543/682] epicer cached bedrock level pathing --- src/main/java/baritone/cache/CachedChunk.java | 118 ++++++++++-------- 1 file changed, 65 insertions(+), 53 deletions(-) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 249daa5b..67ac6942 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -26,7 +26,10 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; -import java.util.*; +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; +import java.util.Map; /** * @author Brady @@ -35,57 +38,57 @@ import java.util.*; public final class CachedChunk { public static final ImmutableSet BLOCKS_TO_KEEP_TRACK_OF = ImmutableSet.of( - Blocks.DIAMOND_BLOCK, - //Blocks.COAL_ORE, - Blocks.COAL_BLOCK, - //Blocks.IRON_ORE, - Blocks.IRON_BLOCK, - //Blocks.GOLD_ORE, - Blocks.GOLD_BLOCK, - Blocks.EMERALD_ORE, - Blocks.EMERALD_BLOCK, + Blocks.DIAMOND_BLOCK, + //Blocks.COAL_ORE, + Blocks.COAL_BLOCK, + //Blocks.IRON_ORE, + Blocks.IRON_BLOCK, + //Blocks.GOLD_ORE, + Blocks.GOLD_BLOCK, + Blocks.EMERALD_ORE, + Blocks.EMERALD_BLOCK, - Blocks.ENDER_CHEST, - Blocks.FURNACE, - Blocks.CHEST, - Blocks.TRAPPED_CHEST, - Blocks.END_PORTAL, - Blocks.END_PORTAL_FRAME, - Blocks.MOB_SPAWNER, - Blocks.BARRIER, - Blocks.OBSERVER, - Blocks.WHITE_SHULKER_BOX, - Blocks.ORANGE_SHULKER_BOX, - Blocks.MAGENTA_SHULKER_BOX, - Blocks.LIGHT_BLUE_SHULKER_BOX, - Blocks.YELLOW_SHULKER_BOX, - Blocks.LIME_SHULKER_BOX, - Blocks.PINK_SHULKER_BOX, - Blocks.GRAY_SHULKER_BOX, - Blocks.SILVER_SHULKER_BOX, - Blocks.CYAN_SHULKER_BOX, - Blocks.PURPLE_SHULKER_BOX, - Blocks.BLUE_SHULKER_BOX, - Blocks.BROWN_SHULKER_BOX, - Blocks.GREEN_SHULKER_BOX, - Blocks.RED_SHULKER_BOX, - Blocks.BLACK_SHULKER_BOX, - Blocks.PORTAL, - Blocks.HOPPER, - Blocks.BEACON, - Blocks.BREWING_STAND, - Blocks.SKULL, - Blocks.ENCHANTING_TABLE, - Blocks.ANVIL, - Blocks.LIT_FURNACE, - Blocks.BED, - Blocks.DRAGON_EGG, - Blocks.JUKEBOX, - Blocks.END_GATEWAY, - Blocks.WEB, - Blocks.NETHER_WART, - Blocks.LADDER, - Blocks.VINE + Blocks.ENDER_CHEST, + Blocks.FURNACE, + Blocks.CHEST, + Blocks.TRAPPED_CHEST, + Blocks.END_PORTAL, + Blocks.END_PORTAL_FRAME, + Blocks.MOB_SPAWNER, + Blocks.BARRIER, + Blocks.OBSERVER, + Blocks.WHITE_SHULKER_BOX, + Blocks.ORANGE_SHULKER_BOX, + Blocks.MAGENTA_SHULKER_BOX, + Blocks.LIGHT_BLUE_SHULKER_BOX, + Blocks.YELLOW_SHULKER_BOX, + Blocks.LIME_SHULKER_BOX, + Blocks.PINK_SHULKER_BOX, + Blocks.GRAY_SHULKER_BOX, + Blocks.SILVER_SHULKER_BOX, + Blocks.CYAN_SHULKER_BOX, + Blocks.PURPLE_SHULKER_BOX, + Blocks.BLUE_SHULKER_BOX, + Blocks.BROWN_SHULKER_BOX, + Blocks.GREEN_SHULKER_BOX, + Blocks.RED_SHULKER_BOX, + Blocks.BLACK_SHULKER_BOX, + Blocks.PORTAL, + Blocks.HOPPER, + Blocks.BEACON, + Blocks.BREWING_STAND, + Blocks.SKULL, + Blocks.ENCHANTING_TABLE, + Blocks.ANVIL, + Blocks.LIT_FURNACE, + Blocks.BED, + Blocks.DRAGON_EGG, + Blocks.JUKEBOX, + Blocks.END_GATEWAY, + Blocks.WEB, + Blocks.NETHER_WART, + Blocks.LADDER, + Blocks.VINE ); @@ -179,8 +182,17 @@ public final class CachedChunk { } } - if (type == PathingBlockType.SOLID && y == 127 && dimension == -1) { - return Blocks.BEDROCK.getDefaultState(); + if (type == PathingBlockType.SOLID) { + if (y == 127 && dimension == -1) { + // nether roof is always unbreakable + return Blocks.BEDROCK.getDefaultState(); + } + if (y < 5 && dimension == 0) { + // solid blocks below 5 are commonly bedrock + // however, returning bedrock always would be a little yikes + // discourage paths that include breaking blocks below 5 a little more heavily just so that it takes paths breaking what's known to be stone (at 5 or above) instead of what could maybe be bedrock (below 5) + return Blocks.OBSIDIAN.getDefaultState(); + } } return ChunkPacker.pathingTypeToBlock(type, dimension); } From e1e6a08eb2fd15ac15c5de298240400b4f43901c Mon Sep 17 00:00:00 2001 From: Scribblefoxx <53978445+Scribblefoxx@users.noreply.github.com> Date: Sun, 11 Aug 2019 03:39:29 +1000 Subject: [PATCH 544/682] Update Settings.java --- 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 4ea5f8da..7d575b0b 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -186,7 +186,7 @@ public final class Settings { * Enables some more advanced vine features. They're honestly just gimmicks and won't ever be needed in real * pathing scenarios. And they can cause Baritone to get trapped indefinitely in a strange scenario. *

- * Never turn this on lol + * Almost never turn this on lol */ public final Setting allowVines = new Setting<>(false); From a98677dbdacc60bec126786de77d07bac7441bfd Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 15 Aug 2019 03:19:19 -0500 Subject: [PATCH 545/682] crucial performance optimization --- src/main/java/baritone/pathing/calc/AStarPathFinder.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index fc964d0f..3e38ff41 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -76,6 +76,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch { int timeCheckInterval = 1 << 6; int pathingMaxChunkBorderFetch = Baritone.settings().pathingMaxChunkBorderFetch.value; // grab all settings beforehand so that changing settings during pathing doesn't cause a crash or unpredictable behavior double minimumImprovement = Baritone.settings().minimumImprovementRepropagation.value ? MIN_IMPROVEMENT : 0; + Moves[] allMoves = Moves.values(); while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && !cancelRequested) { if ((numNodes & (timeCheckInterval - 1)) == 0) { // only call this once every 64 nodes (about half a millisecond) long now = System.currentTimeMillis(); // since nanoTime is slow on windows (takes many microseconds) @@ -95,7 +96,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch { logDebug("Took " + (System.currentTimeMillis() - startTime) + "ms, " + numMovementsConsidered + " movements considered"); return Optional.of(new Path(startNode, currentNode, numNodes, goal, calcContext)); } - for (Moves moves : Moves.values()) { + for (Moves moves : allMoves) { int newX = currentNode.x + moves.xOffset; int newZ = currentNode.z + moves.zOffset; if ((newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) && !calcContext.isLoaded(newX, newZ)) { From 13caaf6fa7a3873e5b1a1423252516c5fafbd9ef Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 15 Aug 2019 19:27:46 -0700 Subject: [PATCH 546/682] ok fine optifine --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bdc405f1..ab2355a8 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Baritone is the pathfinding system used in [Impact](https://impactdevelopment.gi The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the forge jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. -For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1). +For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1). Or [with optifine](https://github.com/cabaletta/baritone/issues/797). 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 and 1.13.2. 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 011b7427e29a7f9f4568138d1c6e293e83e94627 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 15 Aug 2019 23:03:16 -0700 Subject: [PATCH 547/682] fine lmao --- README.md | 2 +- SETUP.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ab2355a8..6a62c32d 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ A Minecraft pathfinder bot. Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. -The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the forge jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. +The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the v1.2.* forge api jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1). Or [with optifine](https://github.com/cabaletta/baritone/issues/797). diff --git a/SETUP.md b/SETUP.md index 3492beaa..909da5a8 100644 --- a/SETUP.md +++ b/SETUP.md @@ -11,6 +11,8 @@ These releases are not always completely up to date with latest features, and ar Link to the releases page: [Releases](https://github.com/cabaletta/baritone/releases) +v1.2.* is for 1.12.2, v1.3.* is for 1.13.2 + Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`. The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone .` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too). From 9046eb500b2a8a3cdc447e05cebc2a6c83a9d8e7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 16 Aug 2019 21:16:41 -0700 Subject: [PATCH 548/682] crucial performance optimization --- src/main/java/baritone/pathing/calc/Path.java | 28 +++++-------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 76cd8396..f7bfbaa2 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -72,28 +72,9 @@ class Path extends PathBase { this.start = new BetterBlockPos(start.x, start.y, start.z); this.end = new BetterBlockPos(end.x, end.y, end.z); this.numNodes = numNodes; - this.path = new ArrayList<>(); this.movements = new ArrayList<>(); - this.nodes = new ArrayList<>(); this.goal = goal; this.context = context; - assemblePath(end); - } - - @Override - public Goal getGoal() { - return goal; - } - - /** - * Assembles this path given the end node. - * - * @param end The end node - */ - private void assemblePath(PathNode end) { - if (!path.isEmpty() || !movements.isEmpty()) { - throw new IllegalStateException(); - } PathNode current = end; LinkedList tempPath = new LinkedList<>(); LinkedList tempNodes = new LinkedList<>(); @@ -107,8 +88,13 @@ class Path extends PathBase { // Can't directly convert from the PathNode pseudo linked list to an array because we don't know how long it is // inserting into a LinkedList keeps track of length, then when we addall (which calls .toArray) it's able // to performantly do that conversion since it knows the length. - path.addAll(tempPath); - nodes.addAll(tempNodes); + this.path = new ArrayList<>(tempPath); + this.nodes = new ArrayList<>(tempNodes); + } + + @Override + public Goal getGoal() { + return goal; } private boolean assembleMovements() { From ed4fba330d3e96078e1817c22e702a10edd68973 Mon Sep 17 00:00:00 2001 From: Graicc <33105645+Graicc@users.noreply.github.com> Date: Sat, 17 Aug 2019 11:59:30 -0400 Subject: [PATCH 549/682] Added mining certain amount of blocks to USAGE.md --- USAGE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/USAGE.md b/USAGE.md index b01bf3fa..7b27a3fc 100644 --- a/USAGE.md +++ b/USAGE.md @@ -24,7 +24,7 @@ Some common examples: - `goal clear` to clear the goal - `cancel` or `stop` to stop everything - `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part) -- `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) +- `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) An amount of blocks can also be specified, for example `mine diamond_ore 64`. - `click` to click your destination on the screen. Right click path to on top of the block, left click to path into it (either at foot level or eye level), and left click and drag to clear all blocks from an area. - `follow playerName` to follow a player. `followplayers` to follow any players in range (combine with Kill Aura for a fun time). `followentities` to follow any entities. `followentity pig` to follow entities of a specific type. - `save waypointName` to save a waypoint. `goto waypointName` to go to it. From 5cbf1eef5fcc33814c6715be600a6cc025a1c26d Mon Sep 17 00:00:00 2001 From: Graicc <33105645+Graicc@users.noreply.github.com> Date: Sat, 17 Aug 2019 12:02:26 -0400 Subject: [PATCH 550/682] Grammer fix --- USAGE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/USAGE.md b/USAGE.md index 7b27a3fc..869d68c2 100644 --- a/USAGE.md +++ b/USAGE.md @@ -24,7 +24,7 @@ Some common examples: - `goal clear` to clear the goal - `cancel` or `stop` to stop everything - `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part) -- `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) An amount of blocks can also be specified, for example `mine diamond_ore 64`. +- `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) An amount of blocks can also be specified, for example, `mine diamond_ore 64`. - `click` to click your destination on the screen. Right click path to on top of the block, left click to path into it (either at foot level or eye level), and left click and drag to clear all blocks from an area. - `follow playerName` to follow a player. `followplayers` to follow any players in range (combine with Kill Aura for a fun time). `followentities` to follow any entities. `followentity pig` to follow entities of a specific type. - `save waypointName` to save a waypoint. `goto waypointName` to go to it. From 24da012903b57a21215b8d13e9a04a735ce55b60 Mon Sep 17 00:00:00 2001 From: reb0rt <37573784+reb0rt@users.noreply.github.com> Date: Sun, 18 Aug 2019 13:04:39 +1000 Subject: [PATCH 551/682] Stop parseGoal from removing the last argument isNumeric returns false if the input is anything other than a positive integer. This meant that baritone wouldn't properly set goals if they ended in anything other than a positive integer. --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 7a90f1be..76849dae 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -50,7 +50,7 @@ import net.minecraft.world.chunk.Chunk; import java.nio.file.Path; import java.util.*; -import static org.apache.commons.lang3.StringUtils.isNumeric; +import static org.apache.commons.lang3.math.NumberUtils.isCreatable; public class ExampleBaritoneControl implements Helper, AbstractGameEventListener { private static final String COMMAND_PREFIX = "#"; @@ -694,7 +694,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener BetterBlockPos playerFeet = ctx.playerFeet(); int length = params.length - 1; // length has to be smaller when a dimension parameter is added - if (params.length < 1 || (isNumeric(params[params.length - 1]) || params[params.length - 1].startsWith("~"))) { + if (params.length < 1 || (isCreatable(params[params.length - 1]) || params[params.length - 1].startsWith("~"))) { length = params.length; } switch (length) { From 1c36bf3300670499660ea2da56bb7b7b982edd36 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 17 Aug 2019 22:01:53 -0700 Subject: [PATCH 552/682] repack on mine cmd --- .../api/utils/ExampleBaritoneControl.java | 36 +++++++++++-------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 76849dae..16a56667 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -241,20 +241,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return true; } if (msg.equals("repack") || msg.equals("rescan")) { - ChunkProviderClient cli = (ChunkProviderClient) ctx.world().getChunkProvider(); - int playerChunkX = ctx.playerFeet().getX() >> 4; - int playerChunkZ = ctx.playerFeet().getZ() >> 4; - int count = 0; - for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) { - for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) { - Chunk chunk = cli.getLoadedChunk(x, z); - if (chunk != null) { - count++; - baritone.getWorldProvider().getCurrentWorld().getCachedWorld().queueForPacking(chunk); - } - } - } - logDirect("Queued " + count + " chunks for repacking"); + logDirect("Queued " + repack() + " chunks for repacking"); return true; } if (msg.startsWith("build")) { @@ -502,6 +489,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return true; } if (msg.startsWith("find")) { + repack(); String blockType = msg.substring(4).trim(); ArrayList locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4); logDirect("Have " + locs.size() + " locations"); @@ -514,6 +502,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return true; } if (msg.startsWith("mine")) { + repack(); String[] blockTypes = msg.substring(4).trim().split(" "); try { int quantity = Integer.parseInt(blockTypes[1]); @@ -603,6 +592,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return true; } if (msg.startsWith("goto")) { + repack(); String waypointType = msg.substring(4).trim(); if (waypointType.endsWith("s") && IWaypoint.Tag.fromString(waypointType.substring(0, waypointType.length() - 1)) != null) { // for example, "show deaths" @@ -676,6 +666,23 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return false; } + private int repack() { + ChunkProviderClient cli = (ChunkProviderClient) ctx.world().getChunkProvider(); + int playerChunkX = ctx.playerFeet().getX() >> 4; + int playerChunkZ = ctx.playerFeet().getZ() >> 4; + int count = 0; + for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) { + for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) { + Chunk chunk = cli.getLoadedChunk(x, z); + if (chunk != null && !chunk.isEmpty()) { + count++; + baritone.getWorldProvider().getCurrentWorld().getCachedWorld().queueForPacking(chunk); + } + } + } + return count; + } + private int parseOrDefault(String str, int i, double dimensionFactor) { return str.equals("~") ? i : str.startsWith("~") ? (int) (Integer.parseInt(str.substring(1)) * dimensionFactor) + i : (int) (Integer.parseInt(str) * dimensionFactor); } @@ -722,7 +729,6 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } - private double calculateDimensionFactor(String to) { return Math.pow(8, ctx.world().provider.getDimensionType().getId() - getDimensionByName(to.toLowerCase()).getId()); } From b9f0da7d27d9d62f7e671f05b087d9f30dce7e4a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 20 Aug 2019 11:23:23 -0700 Subject: [PATCH 553/682] major unscuff of builder --- src/api/java/baritone/api/Settings.java | 20 ++++++++++++++++ .../baritone/behavior/InventoryBehavior.java | 6 ++++- .../java/baritone/process/BuilderProcess.java | 23 +++++++++++++++---- .../utils/schematic/MapArtSchematic.java | 4 ++-- 4 files changed, 46 insertions(+), 7 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 7d575b0b..cd7bdabe 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -697,6 +697,26 @@ public final class Settings { */ public final Setting goalBreakFromAbove = new Setting<>(false); + /** + * Build in map art mode, which makes baritone only care about the top block in each column + */ + public final Setting mapArtMode = new Setting<>(false); + + /** + * Override builder's behavior to not attempt to correct blocks that are currently water + */ + public final Setting okIfWater = new Setting<>(false); + + /** + * The set of incorrect blocks can never grow beyond this size + */ + public final Setting incorrectSize = new Setting<>(100); + + /** + * Multiply the cost of breaking a block that's correct in the builder's schematic by this coefficient + */ + public final Setting breakCorrectBlockPenaltyMultiplier = new Setting<>(10d); + /** * While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)? */ diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 684613af..ae19af86 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -26,6 +26,7 @@ import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.init.Blocks; import net.minecraft.inventory.ClickType; import net.minecraft.item.*; +import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; import java.util.ArrayList; @@ -132,9 +133,12 @@ public final class InventoryBehavior extends Behavior { public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) { IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z); - if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().equals(maybe.getBlock()))) { + if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && maybe.equals(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(ctx.world(), ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ, stack.getItem().getMetadata(stack.getMetadata()), ctx.player())))) { return true; // gotem } + if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().equals(maybe.getBlock()))) { + return true; + } for (Item item : Baritone.settings().acceptableThrowawayItems.value) { if (throwaway(select, stack -> item.equals(stack.getItem()))) { return true; diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 99edba4a..daa04cb9 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -34,6 +34,7 @@ import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; import baritone.utils.PathingCommandContext; import baritone.utils.schematic.AirSchematic; +import baritone.utils.schematic.MapArtSchematic; import baritone.utils.schematic.Schematic; import baritone.utils.schematic.schematica.SchematicaHelper; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; @@ -130,7 +131,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } private static ISchematic parse(NBTTagCompound schematic) { - return new Schematic(schematic); + return Baritone.settings().mapArtMode.value ? new MapArtSchematic(schematic) : new Schematic(schematic); } @Override @@ -512,6 +513,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } else { incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ)); observedCompleted.remove(BetterBlockPos.longHash(blockX, blockY, blockZ)); + if (incorrectPositions.size() > Baritone.settings().incorrectSize.value) { + return; + } } continue; } @@ -520,6 +524,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil // and we've never seen this position be correct // therefore mark as incorrect incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ)); + if (incorrectPositions.size() > Baritone.settings().incorrectSize.value) { + return; + } } } } @@ -618,7 +625,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR; for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) { if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ()).getBlock(), pos, false, facing, null)) { - return new GoalAdjacent(pos, allowSameLevel); + return new GoalAdjacent(pos, pos.offset(facing), allowSameLevel); } } return new GoalPlace(pos); @@ -641,9 +648,11 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil public static class GoalAdjacent extends GoalGetToBlock { private boolean allowSameLevel; + private BlockPos no; - public GoalAdjacent(BlockPos pos, boolean allowSameLevel) { + public GoalAdjacent(BlockPos pos, BlockPos no, boolean allowSameLevel) { super(pos); + this.no = no; this.allowSameLevel = allowSameLevel; } @@ -651,6 +660,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil if (x == this.x && y == this.y && z == this.z) { return false; } + if (x == no.getX() && y == no.getY() && z == no.getZ()) { + return false; + } if (!allowSameLevel && y == this.y - 1) { return false; } @@ -710,6 +722,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil private boolean valid(IBlockState current, IBlockState desired) { // TODO more complicated comparison logic I guess + if (current.getBlock() instanceof BlockLiquid && Baritone.settings().okIfWater.value) { + return true; + } return desired == null || current.equals(desired); } @@ -789,7 +804,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil // it should be a real block // is it already that block? if (valid(bsi.get0(x, y, z), sch)) { - return 3; + return Baritone.settings().breakCorrectBlockPenaltyMultiplier.value; } else { // can break if it's wrong // would be great to return less than 1 here, but that would actually make the cost calculation messed up diff --git a/src/main/java/baritone/utils/schematic/MapArtSchematic.java b/src/main/java/baritone/utils/schematic/MapArtSchematic.java index 1be13195..fa1c2d00 100644 --- a/src/main/java/baritone/utils/schematic/MapArtSchematic.java +++ b/src/main/java/baritone/utils/schematic/MapArtSchematic.java @@ -17,8 +17,8 @@ package baritone.utils.schematic; +import net.minecraft.block.BlockAir; import net.minecraft.block.state.IBlockState; -import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; import java.util.OptionalInt; @@ -36,7 +36,7 @@ public class MapArtSchematic extends Schematic { for (int z = 0; z < lengthZ; z++) { IBlockState[] column = states[x][z]; - OptionalInt lowestBlockY = lastIndexMatching(column, block -> block != Blocks.AIR); + OptionalInt lowestBlockY = lastIndexMatching(column, state -> !(state.getBlock() instanceof BlockAir)); if (lowestBlockY.isPresent()) { heightMap[x][z] = lowestBlockY.getAsInt(); } else { From d927207b67a8efa7311568ea888ac905a5131f8f Mon Sep 17 00:00:00 2001 From: IronException Date: Thu, 22 Aug 2019 17:44:27 +0200 Subject: [PATCH 554/682] added things to avoid Signs should also be avoided. A lot of history can get lost --- src/api/java/baritone/api/Settings.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index cd7bdabe..0037ba00 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -172,7 +172,9 @@ public final class Settings { Blocks.FURNACE, Blocks.LIT_FURNACE, Blocks.CHEST, - Blocks.TRAPPED_CHEST + Blocks.TRAPPED_CHEST, + Blocks.STANDING_SIGN, + Blocks.WALL_SIGN ))); /** From a092a0ba9422d000467b6f847abab8a56da17233 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 21 Aug 2019 23:50:13 -0700 Subject: [PATCH 555/682] update badges --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6a62c32d..d0a6cc3c 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,9 @@ ![Lines of Code](https://tokei.rs/b1/github/cabaletta/baritone?category=code) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) -[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.8%20/%20v1.3.4-brightgreen.svg)](https://impactdevelopment.github.io/) +[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.8%20/%20v1.3.4%20/%20v1.4.1-brightgreen.svg)](https://impactdevelopment.github.io/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/) -[![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%20integration-v1.3.4-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api) +[![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%20integration-v1.3.4%20/%20v1.4.1-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com/) From a2159d62e57353e0c1d7a2c9c0742676f33391e6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Aug 2019 00:21:29 -0700 Subject: [PATCH 556/682] quite annoying --- src/api/java/baritone/api/Settings.java | 5 +++++ src/main/java/baritone/process/BuilderProcess.java | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 0037ba00..a2fe4239 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -724,6 +724,11 @@ public final class Settings { */ public final Setting mineScanDroppedItems = new Setting<>(true); + /** + * Trim incorrect positions too far away, helps performance but hurts reliability in very large schematics + */ + public final Setting distanceTrim = new Setting<>(false); + /** * Cancel the current path if the goal has changed, and the path originally ended in the goal but doesn't anymore. *

diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index daa04cb9..84ea8da3 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -375,7 +375,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil logDirect("Repeating build in vector " + repeat + ", new origin is " + origin); return onTick(calcFailed, isSafeToCancel); } - trim(); + if (Baritone.settings().distanceTrim.value) { + trim(); + } Optional> toBreak = toBreakNearPlayer(bcc); if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) { From dae6cc8e20ae7cd2e11917ef23a39fc77a1a2e05 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Aug 2019 15:23:36 -0700 Subject: [PATCH 557/682] maintain current behavior --- 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 a2fe4239..c7cee8bb 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -727,7 +727,7 @@ public final class Settings { /** * Trim incorrect positions too far away, helps performance but hurts reliability in very large schematics */ - public final Setting distanceTrim = new Setting<>(false); + public final Setting distanceTrim = new Setting<>(true); /** * Cancel the current path if the goal has changed, and the path originally ended in the goal but doesn't anymore. From 33080a4e1c332a094511759bba08a61a4dbcce55 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Aug 2019 15:23:54 -0700 Subject: [PATCH 558/682] v1.2.9 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 05b95395..d0ba4720 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.2.8' +version '1.2.9' buildscript { repositories { From d2a046c8b48741d9bb47143ecb14bd3c0669ce89 Mon Sep 17 00:00:00 2001 From: Orinion Date: Wed, 28 Aug 2019 20:15:41 +0200 Subject: [PATCH 559/682] Add replantCrops setting add replantCrops setting, simmilar to replantNetherWart for the other crops. --- src/api/java/baritone/api/Settings.java | 5 +++++ src/main/java/baritone/process/FarmProcess.java | 12 +++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index c7cee8bb..0d8e37a0 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -656,6 +656,11 @@ public final class Settings { */ public final Setting exploreMaintainY = new Setting<>(64); + /** + * Replant normal Crops while farming and leave cactus and sugarcane to regrow + */ + public final Setting replantCrops = new Setting<>(true); + /** * Replant nether wart while farming */ diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index 350b1ac8..d9cf9b2a 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -112,13 +112,17 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro SUGARCANE(Blocks.REEDS, null) { @Override public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { - return world.getBlockState(pos.down()).getBlock() instanceof BlockReed; + if(Baritone.settings().replantCrops.value) + return world.getBlockState(pos.down()).getBlock() instanceof BlockReed; + return true; } }, CACTUS(Blocks.CACTUS, null) { @Override public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { - return world.getBlockState(pos.down()).getBlock() instanceof BlockCactus; + if(Baritone.settings().replantCrops.value) + return world.getBlockState(pos.down()).getBlock() instanceof BlockCactus; + return true; } }; public final Block block; @@ -166,7 +170,9 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro for (Harvest harvest : Harvest.values()) { scan.add(harvest.block); } - scan.add(Blocks.FARMLAND); + if (Baritone.settings().replantCrops.value) { + scan.add(Blocks.FARMLAND); + } if (Baritone.settings().replantNetherWart.value) { scan.add(Blocks.SOUL_SAND); } From a7add6bc13df16cfbe42e6ae02ff1c6a0c4c1313 Mon Sep 17 00:00:00 2001 From: Babbaj Date: Wed, 28 Aug 2019 20:37:05 -0400 Subject: [PATCH 560/682] Replace klass with cla$$ --- src/api/java/baritone/api/Settings.java | 4 ++-- src/api/java/baritone/api/utils/SettingsUtil.java | 14 +++++++------- .../java/baritone/behavior/InventoryBehavior.java | 4 ++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index c7cee8bb..22125a77 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -985,10 +985,10 @@ public final class Settings { } @SuppressWarnings("unchecked") - public List> getAllValuesByType(Class klass) { + public List> getAllValuesByType(Class cla$$) { List> result = new ArrayList<>(); for (Setting setting : allSettings) { - if (setting.getValueClass().equals(klass)) { + if (setting.getValueClass().equals(cla$$)) { result.add((Setting) setting); } } diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 9c21dcf3..4e659dec 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -222,22 +222,22 @@ public class SettingsUtil { } }; - private final Class klass; + private final Class cla$$; private final Function parser; private final Function toString; Parser() { - this.klass = null; + this.cla$$ = null; this.parser = null; this.toString = null; } - Parser(Class klass, Function parser) { - this(klass, parser, Object::toString); + Parser(Class cla$$, Function parser) { + this(cla$$, parser, Object::toString); } - Parser(Class klass, Function parser, Function toString) { - this.klass = klass; + Parser(Class cla$$, Function parser, Function toString) { + this.cla$$ = cla$$; this.parser = parser::apply; this.toString = x -> toString.apply((T) x); } @@ -256,7 +256,7 @@ public class SettingsUtil { @Override public boolean accepts(Type type) { - return type instanceof Class && this.klass.isAssignableFrom((Class) type); + return type instanceof Class && this.cla$$.isAssignableFrom((Class) type); } public static Parser getParser(Type type) { diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index ae19af86..eface5c0 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -102,7 +102,7 @@ public final class InventoryBehavior extends Behavior { return -1; } - private int bestToolAgainst(Block against, Class klass) { + private int bestToolAgainst(Block against, Class cla$$) { NonNullList invy = ctx.player().inventory.mainInventory; int bestInd = -1; double bestSpeed = -1; @@ -111,7 +111,7 @@ public final class InventoryBehavior extends Behavior { if (stack.isEmpty()) { continue; } - if (klass.isInstance(stack.getItem())) { + if (cla$$.isInstance(stack.getItem())) { double speed = ToolSet.calculateSpeedVsBlock(stack, against.getDefaultState()); // takes into account enchants if (speed > bestSpeed) { bestSpeed = speed; From 65a9b1a78a2d03c5c27d7358bdb276a2ee2c2677 Mon Sep 17 00:00:00 2001 From: Orinion Date: Thu, 29 Aug 2019 10:36:31 +0200 Subject: [PATCH 561/682] Make replantCrops override replantNetherWart When replantCrops is false, baritone will not replant nether wart. Also fixed spacing. --- src/api/java/baritone/api/Settings.java | 2 +- src/main/java/baritone/process/FarmProcess.java | 13 ++++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 0d8e37a0..03de96e8 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -662,7 +662,7 @@ public final class Settings { public final Setting replantCrops = new Setting<>(true); /** - * Replant nether wart while farming + * Replant nether wart while farming. This setting only has an effect when replantCrops is also enabled */ public final Setting replantNetherWart = new Setting<>(false); diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index d9cf9b2a..00273a9f 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -112,16 +112,18 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro SUGARCANE(Blocks.REEDS, null) { @Override public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { - if(Baritone.settings().replantCrops.value) + if (Baritone.settings().replantCrops.value) { return world.getBlockState(pos.down()).getBlock() instanceof BlockReed; + } return true; } }, CACTUS(Blocks.CACTUS, null) { @Override public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { - if(Baritone.settings().replantCrops.value) + if (Baritone.settings().replantCrops.value) { return world.getBlockState(pos.down()).getBlock() instanceof BlockCactus; + } return true; } }; @@ -172,10 +174,11 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro } if (Baritone.settings().replantCrops.value) { scan.add(Blocks.FARMLAND); + if (Baritone.settings().replantNetherWart.value) { + scan.add(Blocks.SOUL_SAND); + } } - if (Baritone.settings().replantNetherWart.value) { - scan.add(Blocks.SOUL_SAND); - } + if (Baritone.settings().mineGoalUpdateInterval.value != 0 && tickCount++ % Baritone.settings().mineGoalUpdateInterval.value == 0) { Baritone.getExecutor().execute(() -> locations = WorldScanner.INSTANCE.scanChunkRadius(ctx, scan, 256, 10, 10)); } From 6a181abdcb3c8f668af9f08dca4b9199f78b6ade Mon Sep 17 00:00:00 2001 From: Orinion Date: Fri, 30 Aug 2019 02:43:59 +0200 Subject: [PATCH 562/682] Check if waypoint name is Tag before, saving a waypint with a tag name would not result in an error, but you would not be able to run "goto" on it. see #869 --- .../java/baritone/api/utils/ExampleBaritoneControl.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 16a56667..263349ef 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -576,6 +576,13 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } name = parts[0]; } + for (IWaypoint.Tag tag : IWaypoint.Tag.values()) + { + if (tag.name().equalsIgnoreCase(name)) { + logDirect("Unable to use Tags as name. Tags are: " + Arrays.asList(IWaypoint.Tag.values()).toString().toLowerCase()); + return true; + } + } baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, IWaypoint.Tag.USER, pos)); logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto " + name + "' to set goal, say 'list user' to list custom waypoints."); return true; From 6327c8492ff99f394ae204f0828ec075f6d2c875 Mon Sep 17 00:00:00 2001 From: Orinion Date: Fri, 30 Aug 2019 11:54:04 +0200 Subject: [PATCH 563/682] fix codestyle --- src/api/java/baritone/api/utils/ExampleBaritoneControl.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 263349ef..32ddcdd2 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -576,10 +576,9 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } name = parts[0]; } - for (IWaypoint.Tag tag : IWaypoint.Tag.values()) - { + for (IWaypoint.Tag tag : IWaypoint.Tag.values()) { if (tag.name().equalsIgnoreCase(name)) { - logDirect("Unable to use Tags as name. Tags are: " + Arrays.asList(IWaypoint.Tag.values()).toString().toLowerCase()); + logDirect("Unable to use tags as name. Tags are: " + Arrays.asList(IWaypoint.Tag.values()).toString().toLowerCase()); return true; } } From e3c4d06b2b4c7dfc20bb44c2620032d38bdbedd6 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 11:55:25 -0700 Subject: [PATCH 564/682] Initial commit of commands --- .gitignore | 2 + src/api/java/baritone/api/Settings.java | 31 +- .../api/behavior/IPathingBehavior.java | 14 +- .../baritone/api/cache/IWorldScanner.java | 9 +- .../api/event/events/TabCompleteEvent.java | 50 +++ .../api/event/events/type/Overrideable.java | 35 ++ .../listener/AbstractGameEventListener.java | 6 + .../event/listener/IGameEventListener.java | 15 + .../api/pathing/goals/GoalInverted.java | 46 +++ .../baritone/api/pathing/goals/GoalXZ.java | 6 + .../baritone/api/process/IBuilderProcess.java | 2 + .../baritone/api/process/IMineProcess.java | 30 +- .../baritone/api/utils/BlockListFilter.java | 46 +++ .../baritone/api/utils/BlockSelector.java | 63 ++++ .../java/baritone/api/utils/BlockUtils.java | 2 +- .../api/utils/CompositeBlockFilter.java | 51 +++ ...ol.java => ExampleBaritoneControlOld.java} | 33 +- src/api/java/baritone/api/utils/Helper.java | 58 +++- .../java/baritone/api/utils/IBlockFilter.java | 22 ++ .../java/baritone/api/utils/SettingsUtil.java | 33 +- .../utils/command/BaritoneChatControl.java | 231 +++++++++++++ .../baritone/api/utils/command/Command.java | 114 +++++++ .../java/baritone/api/utils/command/Lol.java | 7 + .../utils/command/argparser/ArgParser.java | 45 +++ .../command/argparser/ArgParserManager.java | 100 ++++++ .../command/argparser/DefaultArgParsers.java | 110 +++++++ .../utils/command/argparser/IArgParser.java | 50 +++ .../command/argument/CommandArgument.java | 104 ++++++ .../utils/command/datatypes/BlockById.java | 43 +++ .../command/datatypes/EntityClassById.java | 45 +++ .../command/datatypes/ForBlockSelector.java | 28 ++ .../utils/command/datatypes/IDatatype.java | 17 + .../utils/command/datatypes/IDatatypeFor.java | 5 + .../command/datatypes/IDatatypePost.java | 5 + .../command/datatypes/PlayerByUsername.java | 53 +++ .../command/datatypes/RelativeBlockPos.java | 54 +++ .../command/datatypes/RelativeCoordinate.java | 57 ++++ .../utils/command/datatypes/RelativeFile.java | 51 +++ .../utils/command/datatypes/RelativeGoal.java | 64 ++++ .../command/datatypes/RelativeGoalBlock.java | 42 +++ .../command/datatypes/RelativeGoalXZ.java | 40 +++ .../command/datatypes/RelativeGoalYLevel.java | 34 ++ .../utils/command/defaults/AxisCommand.java | 58 ++++ .../command/defaults/BlacklistCommand.java | 66 ++++ .../utils/command/defaults/BuildCommand.java | 81 +++++ .../utils/command/defaults/CancelCommand.java | 55 ++++ .../utils/command/defaults/ChestsCommand.java | 79 +++++ .../command/defaults/ClearareaCommand.java | 78 +++++ .../utils/command/defaults/ComeCommand.java | 68 ++++ .../utils/command/defaults/CommandAlias.java | 56 ++++ .../command/defaults/DefaultCommands.java | 64 ++++ .../utils/command/defaults/EmptyCommand.java | 54 +++ .../utils/command/defaults/ExcCommand.java | 49 +++ .../command/defaults/ExploreCommand.java | 71 ++++ .../defaults/ExploreFilterCommand.java | 89 +++++ .../utils/command/defaults/FarmCommand.java | 55 ++++ .../utils/command/defaults/FindCommand.java | 77 +++++ .../utils/command/defaults/FollowCommand.java | 171 ++++++++++ .../command/defaults/ForceCancelCommand.java | 58 ++++ .../api/utils/command/defaults/GcCommand.java | 57 ++++ .../utils/command/defaults/GoalCommand.java | 104 ++++++ .../utils/command/defaults/HelpCommand.java | 131 ++++++++ .../utils/command/defaults/InvertCommand.java | 74 +++++ .../utils/command/defaults/MineCommand.java | 69 ++++ .../utils/command/defaults/PathCommand.java | 92 ++++++ .../command/defaults/PauseResumeCommands.java | 150 +++++++++ .../utils/command/defaults/ProcCommand.java | 83 +++++ .../command/defaults/ReloadAllCommand.java | 55 ++++ .../utils/command/defaults/RenderCommand.java | 67 ++++ .../utils/command/defaults/RepackCommand.java | 78 +++++ .../command/defaults/SaveAllCommand.java | 55 ++++ .../command/defaults/SchematicaCommand.java | 54 +++ .../utils/command/defaults/SetCommand.java | 275 ++++++++++++++++ .../utils/command/defaults/TunnelCommand.java | 63 ++++ .../command/defaults/VersionCommand.java | 63 ++++ .../CommandErrorMessageException.java | 37 +++ .../command/exception/CommandException.java | 37 +++ .../CommandInvalidArgumentException.java | 34 ++ .../CommandInvalidStateException.java | 24 ++ .../CommandInvalidTypeException.java | 38 +++ .../CommandNoParserForTypeException.java | 27 ++ .../CommandNotEnoughArgumentsException.java | 24 ++ .../exception/CommandNotFoundException.java | 39 +++ .../CommandTooManyArgumentsException.java | 24 ++ .../exception/CommandUnhandledException.java | 83 +++++ .../command/execution/CommandExecution.java | 113 +++++++ .../helpers/arguments/ArgConsumer.java | 310 ++++++++++++++++++ .../command/helpers/pagination/Paginator.java | 162 +++++++++ .../tabcomplete/TabCompleteHelper.java | 158 +++++++++ .../utils/command/manager/CommandManager.java | 93 ++++++ .../api/utils/command/registry/Registry.java | 148 +++++++++ .../launch/mixins/MixinChatTabCompleter.java | 20 ++ .../baritone/launch/mixins/MixinGuiChat.java | 23 ++ .../launch/mixins/MixinGuiScreen.java | 15 + .../launch/mixins/MixinTabCompleter.java | 115 +++++++ src/launch/resources/mixins.baritone.json | 6 +- src/main/java/baritone/Baritone.java | 4 +- .../baritone/behavior/PathingBehavior.java | 23 +- .../java/baritone/cache/WorldScanner.java | 23 +- .../java/baritone/event/GameEventHandler.java | 10 + .../java/baritone/process/BuilderProcess.java | 5 + .../java/baritone/process/FarmProcess.java | 3 +- .../baritone/process/GetToBlockProcess.java | 3 +- .../java/baritone/process/MineProcess.java | 106 +++--- .../java/baritone/utils/PathRenderer.java | 16 +- .../utils/accessor/ITabCompleter.java | 9 + 106 files changed, 6155 insertions(+), 129 deletions(-) create mode 100644 src/api/java/baritone/api/event/events/TabCompleteEvent.java create mode 100644 src/api/java/baritone/api/event/events/type/Overrideable.java create mode 100644 src/api/java/baritone/api/pathing/goals/GoalInverted.java create mode 100644 src/api/java/baritone/api/utils/BlockListFilter.java create mode 100644 src/api/java/baritone/api/utils/BlockSelector.java create mode 100644 src/api/java/baritone/api/utils/CompositeBlockFilter.java rename src/api/java/baritone/api/utils/{ExampleBaritoneControl.java => ExampleBaritoneControlOld.java} (97%) create mode 100644 src/api/java/baritone/api/utils/IBlockFilter.java create mode 100644 src/api/java/baritone/api/utils/command/BaritoneChatControl.java create mode 100644 src/api/java/baritone/api/utils/command/Command.java create mode 100644 src/api/java/baritone/api/utils/command/Lol.java create mode 100644 src/api/java/baritone/api/utils/command/argparser/ArgParser.java create mode 100644 src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java create mode 100644 src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java create mode 100644 src/api/java/baritone/api/utils/command/argparser/IArgParser.java create mode 100644 src/api/java/baritone/api/utils/command/argument/CommandArgument.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/BlockById.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/IDatatype.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/AxisCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/BlacklistCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/BuildCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/CancelCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/ClearareaCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/ComeCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/CommandAlias.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/EmptyCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/ExcCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/ExploreCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/FarmCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/FindCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/FollowCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/ForceCancelCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/GcCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/GoalCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/HelpCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/InvertCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/MineCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/PathCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/ProcCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/ReloadAllCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/RenderCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/RepackCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/SaveAllCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/SchematicaCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/SetCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/TunnelCommand.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/VersionCommand.java create mode 100644 src/api/java/baritone/api/utils/command/exception/CommandErrorMessageException.java create mode 100644 src/api/java/baritone/api/utils/command/exception/CommandException.java create mode 100644 src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java create mode 100644 src/api/java/baritone/api/utils/command/exception/CommandInvalidStateException.java create mode 100644 src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java create mode 100644 src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java create mode 100644 src/api/java/baritone/api/utils/command/exception/CommandNotEnoughArgumentsException.java create mode 100644 src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java create mode 100644 src/api/java/baritone/api/utils/command/exception/CommandTooManyArgumentsException.java create mode 100644 src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java create mode 100644 src/api/java/baritone/api/utils/command/execution/CommandExecution.java create mode 100644 src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java create mode 100644 src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java create mode 100644 src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java create mode 100644 src/api/java/baritone/api/utils/command/manager/CommandManager.java create mode 100644 src/api/java/baritone/api/utils/command/registry/Registry.java create mode 100644 src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java create mode 100644 src/launch/java/baritone/launch/mixins/MixinGuiChat.java create mode 100644 src/launch/java/baritone/launch/mixins/MixinGuiScreen.java create mode 100644 src/launch/java/baritone/launch/mixins/MixinTabCompleter.java create mode 100644 src/main/java/baritone/utils/accessor/ITabCompleter.java diff --git a/.gitignore b/.gitignore index 0834b1e8..bd3b054a 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,8 @@ classes/ # IntelliJ Files .idea/ *.iml +*.ipr +*.iws /logs/ # Copyright Files diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 80dcf5ce..6ff01352 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -483,15 +483,20 @@ public final class Settings { public final Setting chatControl = new Setting<>(true); /** - * A second override over chatControl to force it on + * Some clients like Impact try to force chatControl to off, so here's a second setting to do it anyway */ - public final Setting removePrefix = new Setting<>(false); + public final Setting chatControlAnyway = new Setting<>(false); /** * Render the path */ public final Setting renderPath = new Setting<>(true); + /** + * Render the path as a line instead of a frickin thingy + */ + public final Setting renderPathAsLine = new Setting<>(true); + /** * Render the goal */ @@ -592,10 +597,25 @@ public final class Settings { public final Setting cachedChunksOpacity = new Setting<>(0.5f); /** - * Whether or not to use the "#" command prefix + * Whether or not to allow you to run Baritone commands with the prefix */ public final Setting prefixControl = new Setting<>(true); + /** + * The command prefix for chat control + */ + public final Setting prefix = new Setting<>("#"); + + /** + * Use a short Baritone prefix [B] instead of [Baritone] when logging to chat + */ + public final Setting shortBaritonePrefix = new Setting<>(false); + + /** + * Echo commands to chat when they are run + */ + public final Setting echoCommands = new Setting<>(true); + /** * Don't stop walking forward when you need to break blocks in your way */ @@ -894,6 +914,11 @@ public final class Settings { */ public final Setting colorGoalBox = new Setting<>(Color.GREEN); + /** + * The color of the goal box when it's inverted + */ + public final Setting colorInvertedGoalBox = new Setting<>(Color.RED); + /** * A map of lowercase setting field names to their respective setting diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index 15777448..8890fdc3 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -64,11 +64,17 @@ public interface IPathingBehavior extends IBehavior { Goal getGoal(); /** - * @return Whether or not a path is currently being executed. + * @return Whether or not a path is currently being executed. This will be false if there's currently a pause. + * @see #hasPath() */ - default boolean isPathing() { - return getCurrent() != null; - } + boolean isPathing(); + + /** + * @return If there is a current path. Note that the path is not necessarily being executed, for example when there + * is a pause in effect. + * @see #isPathing() + */ + boolean hasPath(); /** * Cancels the pathing behavior or the current path calculation, and all processes that could be controlling path. diff --git a/src/api/java/baritone/api/cache/IWorldScanner.java b/src/api/java/baritone/api/cache/IWorldScanner.java index caa44cbc..6f4349ac 100644 --- a/src/api/java/baritone/api/cache/IWorldScanner.java +++ b/src/api/java/baritone/api/cache/IWorldScanner.java @@ -17,6 +17,7 @@ package baritone.api.cache; +import baritone.api.utils.IBlockFilter; import baritone.api.utils.IPlayerContext; import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; @@ -35,26 +36,26 @@ public interface IWorldScanner { * * @param ctx The {@link IPlayerContext} containing player and world info that the * scan is based upon - * @param blocks The blocks to scan for + * @param filter The block filter to scan for * @param max The maximum number of blocks to scan before cutoff * @param yLevelThreshold If a block is found within this Y level, the current result will be * returned, if the value is negative, then this condition doesn't apply. * @param maxSearchRadius The maximum chunk search radius * @return The matching block positions */ - List scanChunkRadius(IPlayerContext ctx, List blocks, int max, int yLevelThreshold, int maxSearchRadius); + List scanChunkRadius(IPlayerContext ctx, IBlockFilter filter, int max, int yLevelThreshold, int maxSearchRadius); /** * Scans a single chunk for the specified blocks. * * @param ctx The {@link IPlayerContext} containing player and world info that the * scan is based upon - * @param blocks The blocks to scan for + * @param filter The block filter to scan for * @param pos The position of the target chunk * @param max The maximum number of blocks to scan before cutoff * @param yLevelThreshold If a block is found within this Y level, the current result will be * returned, if the value is negative, then this condition doesn't apply. * @return The matching block positions */ - List scanChunk(IPlayerContext ctx, List blocks, ChunkPos pos, int max, int yLevelThreshold); + List scanChunk(IPlayerContext ctx, IBlockFilter filter, ChunkPos pos, int max, int yLevelThreshold); } diff --git a/src/api/java/baritone/api/event/events/TabCompleteEvent.java b/src/api/java/baritone/api/event/events/TabCompleteEvent.java new file mode 100644 index 00000000..d5bed1ff --- /dev/null +++ b/src/api/java/baritone/api/event/events/TabCompleteEvent.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.event.events; + +import baritone.api.event.events.type.Cancellable; +import baritone.api.event.events.type.Overrideable; + +/** + * @author LoganDark + */ +public abstract class TabCompleteEvent extends Cancellable { + public final Overrideable prefix; + public final Overrideable completions; + + TabCompleteEvent(String prefix, String[] completions) { + this.prefix = new Overrideable<>(prefix); + this.completions = new Overrideable<>(completions); + } + + public boolean wasModified() { + return prefix.wasModified() || completions.wasModified(); + } + + public static final class Pre extends TabCompleteEvent { + public Pre(String prefix) { + super(prefix, null); + } + } + + public static final class Post extends TabCompleteEvent { + public Post(String prefix, String[] completions) { + super(prefix, completions); + } + } +} diff --git a/src/api/java/baritone/api/event/events/type/Overrideable.java b/src/api/java/baritone/api/event/events/type/Overrideable.java new file mode 100644 index 00000000..987e64f7 --- /dev/null +++ b/src/api/java/baritone/api/event/events/type/Overrideable.java @@ -0,0 +1,35 @@ +package baritone.api.event.events.type; + +/** + * @author LoganDark + */ +public class Overrideable { + private T value; + private boolean modified; + + public Overrideable(T current) { + value = current; + } + + public T get() { + return value; + } + + public void set(T newValue) { + value = newValue; + modified = true; + } + + public boolean wasModified() { + return modified; + } + + @Override + public String toString() { + return String.format( + "Overrideable{modified=%s,value=%s}", + Boolean.toString(modified), + value.toString() + ); + } +} diff --git a/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java b/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java index 71045768..9e5b6dbb 100644 --- a/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java +++ b/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java @@ -39,6 +39,12 @@ public interface AbstractGameEventListener extends IGameEventListener { @Override default void onSendChatMessage(ChatEvent event) {} + @Override + default void onPreTabComplete(TabCompleteEvent.Pre event) {}; + + @Override + default void onPostTabComplete(TabCompleteEvent.Post event) {}; + @Override default void onChunkEvent(ChunkEvent event) {} diff --git a/src/api/java/baritone/api/event/listener/IGameEventListener.java b/src/api/java/baritone/api/event/listener/IGameEventListener.java index dc471e5f..00b24e3d 100644 --- a/src/api/java/baritone/api/event/listener/IGameEventListener.java +++ b/src/api/java/baritone/api/event/listener/IGameEventListener.java @@ -57,6 +57,21 @@ public interface IGameEventListener { */ void onSendChatMessage(ChatEvent event); + /** + * Runs whenever the client player tries to tab complete in chat. + * + * @param event The event + */ + void onPreTabComplete(TabCompleteEvent.Pre event); + + /** + * Runs whenever the client player tries to tab complete in chat once completions have been recieved from the + * server. This will only be called if the {@link TabCompleteEvent.Pre#cancel()} method was not called. + * + * @param event The event + */ + void onPostTabComplete(TabCompleteEvent.Post event); + /** * Runs before and after whenever a chunk is either loaded, unloaded, or populated. * diff --git a/src/api/java/baritone/api/pathing/goals/GoalInverted.java b/src/api/java/baritone/api/pathing/goals/GoalInverted.java new file mode 100644 index 00000000..dfe5c770 --- /dev/null +++ b/src/api/java/baritone/api/pathing/goals/GoalInverted.java @@ -0,0 +1,46 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.pathing.goals; + +/** + * Invert any goal + * + * @author LoganDark + */ +public class GoalInverted implements Goal { + public final Goal origin; + + public GoalInverted(Goal origin) { + this.origin = origin; + } + + @Override + public boolean isInGoal(int x, int y, int z) { + return false; + } + + @Override + public double heuristic(int x, int y, int z) { + return -origin.heuristic(x, y, z); + } + + @Override + public String toString() { + return String.format("GoalInverted{%s}", origin.toString()); + } +} diff --git a/src/api/java/baritone/api/pathing/goals/GoalXZ.java b/src/api/java/baritone/api/pathing/goals/GoalXZ.java index 7f8d16ab..5ad23336 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalXZ.java +++ b/src/api/java/baritone/api/pathing/goals/GoalXZ.java @@ -18,6 +18,7 @@ package baritone.api.pathing.goals; import baritone.api.BaritoneAPI; +import baritone.api.utils.BetterBlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; @@ -45,6 +46,11 @@ public class GoalXZ implements Goal { this.z = z; } + public GoalXZ(BetterBlockPos pos) { + this.x = pos.x; + this.z = pos.z; + } + @Override public boolean isInGoal(int x, int y, int z) { return x == this.x && z == this.z; diff --git a/src/api/java/baritone/api/process/IBuilderProcess.java b/src/api/java/baritone/api/process/IBuilderProcess.java index f73f0e74..5ca5f804 100644 --- a/src/api/java/baritone/api/process/IBuilderProcess.java +++ b/src/api/java/baritone/api/process/IBuilderProcess.java @@ -58,6 +58,8 @@ public interface IBuilderProcess extends IBaritoneProcess { void pause(); + boolean isPaused(); + void resume(); void clearArea(BlockPos corner1, BlockPos corner2); diff --git a/src/api/java/baritone/api/process/IMineProcess.java b/src/api/java/baritone/api/process/IMineProcess.java index 7ebabc9c..4885e32f 100644 --- a/src/api/java/baritone/api/process/IMineProcess.java +++ b/src/api/java/baritone/api/process/IMineProcess.java @@ -17,6 +17,8 @@ package baritone.api.process; +import baritone.api.utils.BlockListFilter; +import baritone.api.utils.IBlockFilter; import net.minecraft.block.Block; /** @@ -24,13 +26,12 @@ import net.minecraft.block.Block; * @since 9/23/2018 */ public interface IMineProcess extends IBaritoneProcess { - /** * Begin to search for and mine the specified blocks until * the number of specified items to get from the blocks that - * are mined. This is based on the first target block to mine. + * are mined. * - * @param quantity The number of items to get from blocks mined + * @param quantity The total number of items to get * @param blocks The blocks to mine */ void mineByName(int quantity, String... blocks); @@ -41,9 +42,18 @@ public interface IMineProcess extends IBaritoneProcess { * are mined. This is based on the first target block to mine. * * @param quantity The number of items to get from blocks mined - * @param blocks The blocks to mine + * @param filter The filter to run blocks through */ - void mine(int quantity, Block... blocks); + void mine(int quantity, IBlockFilter filter); + + /** + * Begin to search for and mine the specified blocks. + * + * @param filter The filter to run blocks through + */ + default void mine(IBlockFilter filter) { + mine(0, filter); + } /** * Begin to search for and mine the specified blocks. @@ -54,6 +64,16 @@ public interface IMineProcess extends IBaritoneProcess { mineByName(0, blocks); } + /** + * Begin to search for and mine the specified blocks. + * + * @param quantity The total number of items to get + * @param blocks The blocks to mine + */ + default void mine(int quantity, Block... blocks) { + mine(quantity, new BlockListFilter(blocks)); + } + /** * Begin to search for and mine the specified blocks. * diff --git a/src/api/java/baritone/api/utils/BlockListFilter.java b/src/api/java/baritone/api/utils/BlockListFilter.java new file mode 100644 index 00000000..7168687d --- /dev/null +++ b/src/api/java/baritone/api/utils/BlockListFilter.java @@ -0,0 +1,46 @@ +package baritone.api.utils; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.util.ResourceLocation; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class BlockListFilter implements IBlockFilter { + private final List blocks = new ArrayList<>(); + + public BlockListFilter(List blocks) { + this.blocks.addAll(blocks); + } + + public BlockListFilter(Block... blocks) { + this.blocks.addAll(Arrays.asList(blocks)); + } + + @Override + public boolean selected(@Nonnull IBlockState blockstate) { + return false; + } + + @Override + public List blocks() { + return null; + } + + @Override + public String toString() { + return String.format( + "BlockListFilter{%s}", + String.join( + ",", + blocks.stream() + .map(Block.REGISTRY::getNameForObject) + .map(ResourceLocation::toString) + .toArray(String[]::new) + ) + ); + } +} diff --git a/src/api/java/baritone/api/utils/BlockSelector.java b/src/api/java/baritone/api/utils/BlockSelector.java new file mode 100644 index 00000000..c711d725 --- /dev/null +++ b/src/api/java/baritone/api/utils/BlockSelector.java @@ -0,0 +1,63 @@ +package baritone.api.utils; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; + +import javax.annotation.Nonnull; +import java.util.Collections; +import java.util.List; +import java.util.regex.MatchResult; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static java.util.Objects.isNull; + +public class BlockSelector implements IBlockFilter { + private final Block block; + private final IBlockState blockstate; + private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); + + public BlockSelector(@Nonnull String selector) { + Matcher matcher = pattern.matcher(selector); + + if (!matcher.find()) { + throw new RuntimeException("invalid block selector"); + } + + MatchResult matchResult = matcher.toMatchResult(); + boolean hasData = matchResult.groupCount() > 1; + + ResourceLocation id = new ResourceLocation(matchResult.group(1)); + + if (!Block.REGISTRY.containsKey(id)) { + throw new IllegalArgumentException("Invalid block ID"); + } + + block = Block.REGISTRY.getObject(id); + //noinspection deprecation + blockstate = hasData ? block.getStateFromMeta(Integer.parseInt(matchResult.group(2))) : null; + } + + @Override + public boolean selected(@Nonnull IBlockState blockstate) { + return blockstate.getBlock() == block && (isNull(this.blockstate) || + block.damageDropped(blockstate) == block.damageDropped(this.blockstate)); + } + + @Override + public List blocks() { + return Collections.singletonList(block); + } + + @Override + public String toString() { + return String.format("BlockSelector{block=%s,blockstate=%s}", block, blockstate); + } + + public static IBlockState stateFromItem(ItemStack stack) { + //noinspection deprecation + return Block.getBlockFromItem(stack.getItem()).getStateFromMeta(stack.getMetadata()); + } +} diff --git a/src/api/java/baritone/api/utils/BlockUtils.java b/src/api/java/baritone/api/utils/BlockUtils.java index a7e00608..7d148c9f 100644 --- a/src/api/java/baritone/api/utils/BlockUtils.java +++ b/src/api/java/baritone/api/utils/BlockUtils.java @@ -39,7 +39,7 @@ public class BlockUtils { public static Block stringToBlockRequired(String name) { Block block = stringToBlockNullable(name); - Objects.requireNonNull(block); + Objects.requireNonNull(block, String.format("Invalid block name %s", name)); return block; } diff --git a/src/api/java/baritone/api/utils/CompositeBlockFilter.java b/src/api/java/baritone/api/utils/CompositeBlockFilter.java new file mode 100644 index 00000000..39b52f21 --- /dev/null +++ b/src/api/java/baritone/api/utils/CompositeBlockFilter.java @@ -0,0 +1,51 @@ +package baritone.api.utils; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import static java.util.Arrays.asList; + +public class CompositeBlockFilter implements IBlockFilter { + List filters = new ArrayList<>(); + + public CompositeBlockFilter() { + } + + public CompositeBlockFilter(List filters) { + this.filters.addAll(filters); + } + + public CompositeBlockFilter(IBlockFilter... filters) { + this.filters.addAll(asList(filters)); + } + + @Override + public boolean selected(@Nonnull IBlockState blockstate) { + return filters.stream() + .map(f -> f.selected(blockstate)) + .filter(Boolean::valueOf).findFirst() + .orElse(false); + } + + @Override + public List blocks() { + return filters.stream() + .map(IBlockFilter::blocks) + .flatMap(Collection::stream) + .collect(Collectors.toCollection(ArrayList::new)); + } + + @Override + public String toString() { + return String.format( + "CompositeBlockFilter{%s}", + String.join(",", filters.stream().map(Object::toString).toArray(String[]::new)) + ); + } +} diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java similarity index 97% rename from src/api/java/baritone/api/utils/ExampleBaritoneControl.java rename to src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java index 16a56667..de0cbf6b 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java @@ -26,7 +26,14 @@ import baritone.api.cache.IWaypoint; import baritone.api.cache.Waypoint; import baritone.api.event.events.ChatEvent; import baritone.api.event.listener.AbstractGameEventListener; -import baritone.api.pathing.goals.*; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalAxis; +import baritone.api.pathing.goals.GoalBlock; +import baritone.api.pathing.goals.GoalGetToBlock; +import baritone.api.pathing.goals.GoalRunAway; +import baritone.api.pathing.goals.GoalStrictDirection; +import baritone.api.pathing.goals.GoalXZ; +import baritone.api.pathing.goals.GoalYLevel; import baritone.api.process.IBaritoneProcess; import baritone.api.process.ICustomGoalProcess; import baritone.api.process.IGetToBlockProcess; @@ -48,17 +55,24 @@ import net.minecraft.world.DimensionType; import net.minecraft.world.chunk.Chunk; import java.nio.file.Path; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import static org.apache.commons.lang3.math.NumberUtils.isCreatable; -public class ExampleBaritoneControl implements Helper, AbstractGameEventListener { +public class ExampleBaritoneControlOld implements Helper, AbstractGameEventListener { private static final String COMMAND_PREFIX = "#"; public final IBaritone baritone; public final IPlayerContext ctx; - public ExampleBaritoneControl(IBaritone baritone) { + public ExampleBaritoneControlOld(IBaritone baritone) { this.baritone = baritone; this.ctx = baritone.getPlayerContext(); baritone.getGameEventHandler().registerEventListener(this); @@ -74,7 +88,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener event.cancel(); // always cancel if using prefixControl return; } - if (!BaritoneAPI.getSettings().chatControl.value && !BaritoneAPI.getSettings().removePrefix.value) { + if (!BaritoneAPI.getSettings().chatControl.value && !BaritoneAPI.getSettings().chatControlAnyway.value) { return; } if (runCommand(msg)) { @@ -123,7 +137,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return true; } if (msg.equals("") || msg.equals("help") || msg.equals("?")) { - ITextComponent component = MESSAGE_PREFIX.createCopy(); + ITextComponent component = Helper.getPrefix(); component.getStyle().setColor(TextFormatting.GRAY); TextComponentString helpLink = new TextComponentString(" Click here for instructions on how to use Baritone (https://github.com/cabaletta/baritone/blob/master/USAGE.md)"); helpLink.getStyle().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://github.com/cabaletta/baritone/blob/master/USAGE.md")); @@ -166,7 +180,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } else { String[] params = rest.split(" "); if (params[0].equals("")) { - params = new String[]{}; + params = new String[] {}; } goal = parseGoal(params); if (goal == null) { @@ -232,7 +246,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener return true; } if (msg.equals("version")) { - String version = ExampleBaritoneControl.class.getPackage().getImplementationVersion(); + String version = ExampleBaritoneControlOld.class.getPackage().getImplementationVersion(); if (version == null) { logDirect("No version detected. Either dev environment or broken install."); } else { @@ -510,7 +524,8 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener baritone.getMineProcess().mine(quantity, block); logDirect("Will mine " + quantity + " " + blockTypes[0]); return true; - } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {} + } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) { + } for (String s : blockTypes) { if (BlockUtils.stringToBlockNullable(s) == null) { logDirect(s + " isn't a valid block name"); diff --git a/src/api/java/baritone/api/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java index 99683d8a..7b36a716 100755 --- a/src/api/java/baritone/api/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -23,6 +23,10 @@ import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; +import java.util.Arrays; + +import static java.util.Arrays.asList; + /** * @author Brady * @since 8/1/2018 @@ -32,15 +36,19 @@ public interface Helper { /** * Instance of {@link Helper}. Used for static-context reference. */ - Helper HELPER = new Helper() {}; + Helper HELPER = new Helper() { + }; - ITextComponent MESSAGE_PREFIX = new TextComponentString(String.format( - "%s[%sBaritone%s]%s", - TextFormatting.DARK_PURPLE, - TextFormatting.LIGHT_PURPLE, - TextFormatting.DARK_PURPLE, - TextFormatting.GRAY - )); + static ITextComponent getPrefix() { + return new TextComponentString("") {{ + getStyle().setColor(TextFormatting.DARK_PURPLE); + appendSibling(new TextComponentString("[")); + appendSibling(new TextComponentString(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone") {{ + getStyle().setColor(TextFormatting.LIGHT_PURPLE); + }}); + appendSibling(new TextComponentString("]")); + }}; + } Minecraft mc = Minecraft.getMinecraft(); @@ -58,15 +66,41 @@ public interface Helper { logDirect(message); } + /** + * Send components to chat with the [Baritone] prefix + * + * @param components The components to send + */ + default void logDirect(ITextComponent... components) { + ITextComponent component = new TextComponentString("") {{ + appendSibling(getPrefix()); + appendSibling(new TextComponentString(" ")); + asList(components).forEach(this::appendSibling); + }}; + + Minecraft.getMinecraft().addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component)); + } + + /** + * Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command) + * + * @param message The message to display in chat + * @param color The color to print that message in + */ + default void logDirect(String message, TextFormatting color) { + Arrays.stream(message.split("\\n")).forEach(line -> + logDirect(new TextComponentString(line.replace("\t", " ")) {{ + getStyle().setColor(color); + }}) + ); + } + /** * Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command) * * @param message The message to display in chat */ default void logDirect(String message) { - ITextComponent component = MESSAGE_PREFIX.createCopy(); - component.getStyle().setColor(TextFormatting.GRAY); - component.appendSibling(new TextComponentString(" " + message)); - Minecraft.getMinecraft().addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component)); + logDirect(message, TextFormatting.GRAY); } } diff --git a/src/api/java/baritone/api/utils/IBlockFilter.java b/src/api/java/baritone/api/utils/IBlockFilter.java new file mode 100644 index 00000000..2ad44823 --- /dev/null +++ b/src/api/java/baritone/api/utils/IBlockFilter.java @@ -0,0 +1,22 @@ +package baritone.api.utils; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; + +import javax.annotation.Nonnull; +import java.util.List; + +public interface IBlockFilter { + /** + * @param blockstate The blockstate of the block to test. + * @return If that blockstate passes this filter. + */ + boolean selected(@Nonnull IBlockState blockstate); + + /** + * @return A possibly incomplete list of blocks this filter selects. Not all states of each block may be selected, + * and this may not contain all selected blocks, but every block on this list is guaranteed to have a selected + * state. + */ + List blocks(); +} diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 4e659dec..17387aa0 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -120,15 +120,37 @@ public class SettingsUtil { return modified; } + public static String settingTypeToString(Settings.Setting setting) { + return setting.getType().getTypeName() + .replaceAll("(?:\\w+\\.)+(\\w+)", "$1"); + } + + public static String settingValueToString(Settings.Setting setting, T value) throws IllegalArgumentException { + Parser io = Parser.getParser(setting.getType()); + + if (io == null) { + throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName()); + } + + return io.toString(new ParserContext(setting), value); + } + + public static String settingValueToString(Settings.Setting setting) throws IllegalArgumentException { + //noinspection unchecked + return settingValueToString(setting, setting.value); + } + + public static String settingDefaultToString(Settings.Setting setting) throws IllegalArgumentException { + //noinspection unchecked + return settingValueToString(setting, setting.defaultValue); + } + public static String settingToString(Settings.Setting setting) throws IllegalStateException { if (setting.getName().equals("logger")) { return "logger"; } - Parser io = Parser.getParser(setting.getType()); - if (io == null) { - throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName()); - } - return setting.getName() + " " + io.toString(new ParserContext(setting), setting.value); + + return setting.getName() + " " + settingValueToString(setting); } public static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException { @@ -174,6 +196,7 @@ public class SettingsUtil { INTEGER(Integer.class, Integer::parseInt), FLOAT(Float.class, Float::parseFloat), LONG(Long.class, Long::parseLong), + STRING(String.class, String::new), ENUMFACING(EnumFacing.class, EnumFacing::byName), COLOR( Color.class, diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java new file mode 100644 index 00000000..3de8a7eb --- /dev/null +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -0,0 +1,231 @@ +/* + * 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.command; + +import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; +import baritone.api.Settings; +import baritone.api.event.events.ChatEvent; +import baritone.api.event.events.TabCompleteEvent; +import baritone.api.event.listener.AbstractGameEventListener; +import baritone.api.utils.Helper; +import baritone.api.utils.IPlayerContext; +import baritone.api.utils.SettingsUtil; +import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.exception.CommandNotFoundException; +import baritone.api.utils.command.execution.CommandExecution; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import baritone.api.utils.command.manager.CommandManager; +import com.mojang.realmsclient.util.Pair; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.event.ClickEvent; +import net.minecraft.util.text.event.HoverEvent; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.stream.Stream; + +import static java.util.Objects.isNull; +import static java.util.Objects.nonNull; +import static java.util.stream.Stream.of; + +public class BaritoneChatControl implements Helper, AbstractGameEventListener { + public final IBaritone baritone; + public final IPlayerContext ctx; + public final Settings settings = BaritoneAPI.getSettings(); + public static String FORCE_COMMAND_PREFIX = String.format("<<%s>>", UUID.randomUUID().toString()); + + public BaritoneChatControl(IBaritone baritone) { + this.baritone = baritone; + this.ctx = baritone.getPlayerContext(); + baritone.getGameEventHandler().registerEventListener(this); + } + + @Override + public void onSendChatMessage(ChatEvent event) { + String msg = event.getMessage(); + String prefix = settings.prefix.value; + boolean forceRun = msg.startsWith(FORCE_COMMAND_PREFIX); + + if (!forceRun && !settings.chatControl.value && !settings.chatControlAnyway.value && !settings.prefixControl.value) { + return; + } + + if ((settings.prefixControl.value && msg.startsWith(prefix)) || forceRun) { + event.cancel(); + + String commandStr = msg.substring(forceRun ? FORCE_COMMAND_PREFIX.length() : prefix.length()); + + if (!runCommand(commandStr) && !commandStr.trim().isEmpty()) { + new CommandNotFoundException(CommandExecution.expand(commandStr).first()).handle(null, null); + } + + return; + } + + if ((settings.chatControl.value || settings.chatControlAnyway.value) && runCommand(msg)) { + event.cancel(); + } + } + + private void logRanCommand(String msg) { + if (settings.echoCommands.value) { + logDirect(new TextComponentString(String.format("> %s", msg)) {{ + getStyle() + .setColor(TextFormatting.WHITE) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to rerun command") + )) + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + FORCE_COMMAND_PREFIX + msg + )); + }}); + } + } + + public boolean runCommand(String msg) { + if (msg.trim().equalsIgnoreCase("damn")) { + logDirect("daniel"); + return false; + } else if (msg.trim().equalsIgnoreCase("orderpizza")) { + try { + ((Lol) mc.currentScreen).openLink(new URI("https://www.dominos.com/en/pages/order/")); + } catch (NullPointerException | URISyntaxException ignored) { + } + + return false; + } + + if (msg.isEmpty()) { + msg = "help"; + } + + Pair> pair = CommandExecution.expand(msg); + ArgConsumer argc = new ArgConsumer(pair.second()); + + if (!argc.has()) { + for (Settings.Setting setting : settings.allSettings) { + if (setting.getName().equals("logger")) { + continue; + } + + if (setting.getName().equalsIgnoreCase(pair.first())) { + logRanCommand(msg); + + if (setting.getValueClass() == Boolean.class) { + CommandManager.execute(String.format("set toggle %s", setting.getName())); + } else { + CommandManager.execute(String.format("set %s", setting.getName())); + } + + return true; + } + } + } else if (argc.hasExactlyOne()) { + for (Settings.Setting setting : settings.allSettings) { + if (setting.getName().equals("logger")) { + continue; + } + + if (setting.getName().equalsIgnoreCase(pair.first())) { + logRanCommand(msg); + CommandManager.execute(String.format("set %s %s", setting.getName(), argc.getS())); + return true; + } + } + } + + CommandExecution execution = CommandExecution.from(pair); + + if (isNull(execution)) { + return false; + } + + logRanCommand(msg); + CommandManager.execute(execution); + + return true; + } + + @Override + public void onPreTabComplete(TabCompleteEvent.Pre event) { + if (!settings.prefixControl.value) { + return; + } + + String prefix = event.prefix.get(); + String commandPrefix = settings.prefix.value; + + if (!prefix.startsWith(commandPrefix)) { + return; + } + + String msg = prefix.substring(commandPrefix.length()); + + List args = CommandArgument.from(msg, true); + Stream stream = tabComplete(msg); + + if (args.size() == 1) { + stream = stream.map(x -> commandPrefix + x); + } + + event.completions.set(stream.toArray(String[]::new)); + } + + public Stream tabComplete(String msg) { + List args = CommandArgument.from(msg, true); + ArgConsumer argc = new ArgConsumer(args); + + if (argc.hasAtMost(2)) { + if (argc.hasExactly(1)) { + return new TabCompleteHelper() + .addCommands() + .addSettings() + .filterPrefix(argc.getS()) + .stream(); + } + + Settings.Setting setting = settings.byLowerName.get(argc.getS().toLowerCase(Locale.US)); + + if (nonNull(setting)) { + if (setting.getValueClass() == Boolean.class) { + TabCompleteHelper helper = new TabCompleteHelper(); + + if ((Boolean) setting.value) { + helper.append(of("true", "false")); + } else { + helper.append(of("false", "true")); + } + + return helper.filterPrefix(argc.getS()).stream(); + } else { + return of(SettingsUtil.settingValueToString(setting)); + } + } + } + + return CommandManager.tabComplete(msg); + } +} diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java new file mode 100644 index 00000000..26fca9e1 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -0,0 +1,114 @@ +/* + * 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.command; + +import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; +import baritone.api.Settings; +import baritone.api.utils.Helper; +import baritone.api.utils.IPlayerContext; +import baritone.api.utils.command.execution.CommandExecution; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.client.Minecraft; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public abstract class Command implements Helper { + protected IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone(); + protected IPlayerContext ctx = baritone.getPlayerContext(); + protected Minecraft MC = mc; + + /** + * The names of this command. This is what you put after the command prefix. + */ + public final List names; + + /** + * A single-line string containing a short description of this command's purpose. + */ + public final String shortDesc; + + /** + * Creates a new Baritone control command. + * + * @param names The names of this command. This is what you put after the command prefix. + * @param shortDesc A single-line string containing a short description of this command's purpose. + */ + protected Command(List names, String shortDesc) { + this.names = names.stream() + .map(s -> s.toLowerCase(Locale.US)) + .collect(Collectors.toCollection(ArrayList::new)); + this.shortDesc = shortDesc; + } + + protected Command(String name, String shortDesc) { + this(Collections.singletonList(name), shortDesc); + } + + /** + * Executes this command with the specified arguments. + * + * @param execution The command execution to execute this command with + */ + public void execute(CommandExecution execution) { + executed(execution.label, execution.args, execution.settings); + } + + /** + * Tab completes this command with the specified arguments. This won't throw any exceptions ever. + * + * @param execution The command execution to tab complete + * @return The list of completions. + */ + public Stream tabComplete(CommandExecution execution) { + try { + return tabCompleted(execution.label, execution.args, execution.settings); + } catch (Throwable t) { + return Arrays.stream(new String[0]); + } + } + + /** + * Called when this command is executed. + */ + protected abstract void executed(String label, ArgConsumer args, Settings settings); + + /** + * Called when the command needs to tab complete. Return a Stream representing the entries to put in the completions + * list. + */ + protected abstract Stream tabCompleted(String label, ArgConsumer args, Settings settings); + + /** + * @return A list of lines that will be printed by the help command when the user wishes to view them. + */ + public abstract List getLongDesc(); + + /** + * @return {@code true} if this command should be hidden from the help menu + */ + public boolean hiddenFromHelp() { + return false; + } +} diff --git a/src/api/java/baritone/api/utils/command/Lol.java b/src/api/java/baritone/api/utils/command/Lol.java new file mode 100644 index 00000000..5c56544e --- /dev/null +++ b/src/api/java/baritone/api/utils/command/Lol.java @@ -0,0 +1,7 @@ +package baritone.api.utils.command; + +import java.net.URI; + +public interface Lol { + void openLink(URI url); +} diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParser.java b/src/api/java/baritone/api/utils/command/argparser/ArgParser.java new file mode 100644 index 00000000..8fc08e86 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParser.java @@ -0,0 +1,45 @@ +/* + * 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.command.argparser; + +public abstract class ArgParser implements IArgParser { + private final Class klass; + + protected ArgParser(Class klass) { + this.klass = klass; + } + + @Override + public Class getKlass() { + return klass; + } + + public static abstract class Stated extends ArgParser implements IArgParser.Stated { + private final Class stateKlass; + + protected Stated(Class klass, Class stateKlass) { + super(klass); + this.stateKlass = stateKlass; + } + + @Override + public Class getStateKlass() { + return stateKlass; + } + } +} diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java new file mode 100644 index 00000000..6b5d4761 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -0,0 +1,100 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.command.argparser; + +import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.exception.CommandNoParserForTypeException; +import baritone.api.utils.command.registry.Registry; + +import java.util.Iterator; + +import static java.util.Objects.isNull; + +public class ArgParserManager { + public static final Registry REGISTRY = new Registry<>(); + + static { + DefaultArgParsers.all.forEach(REGISTRY::register); + } + + /** + * @param klass The class to search for. + * @return A parser that can parse arguments into this class, if found. + */ + public static ArgParser.Stateless getParserStateless(Class klass) { + for (Iterator it = REGISTRY.descendingIterator(); it.hasNext(); ) { + ArgParser parser = it.next(); + + if (parser instanceof ArgParser.Stateless && parser.getKlass().isAssignableFrom(klass)) { + //noinspection unchecked + return (ArgParser.Stateless) parser; + } + } + + return null; + } + + /** + * @param klass The class to search for. + * @return A parser that can parse arguments into this class, if found. + */ + public static ArgParser.Stated getParserStated(Class klass, Class stateKlass) { + for (Iterator it = REGISTRY.descendingIterator(); it.hasNext(); ) { + ArgParser parser = it.next(); + + //noinspection unchecked + if (parser instanceof ArgParser.Stated + && parser.getKlass().isAssignableFrom(klass) + && ((ArgParser.Stated) parser).getStateKlass().isAssignableFrom(stateKlass)) { + //noinspection unchecked + return (ArgParser.Stated) parser; + } + } + + return null; + } + + public static T parseStateless(Class klass, CommandArgument arg) { + ArgParser.Stateless parser = getParserStateless(klass); + + if (isNull(parser)) { + throw new CommandNoParserForTypeException(klass); + } + + try { + return parser.parseArg(arg); + } catch (RuntimeException exc) { + throw new CommandInvalidTypeException(arg, klass.getSimpleName()); + } + } + + public static T parseStated(Class klass, Class stateKlass, CommandArgument arg, S state) { + ArgParser.Stated parser = getParserStated(klass, stateKlass); + + if (isNull(parser)) { + throw new CommandNoParserForTypeException(klass); + } + + try { + return parser.parseArg(arg, state); + } catch (RuntimeException exc) { + throw new CommandInvalidTypeException(arg, klass.getSimpleName()); + } + } +} diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java new file mode 100644 index 00000000..301ad891 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -0,0 +1,110 @@ +/* + * 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.command.argparser; + +import baritone.api.utils.command.argument.CommandArgument; + +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +import static java.util.Arrays.asList; + +public class DefaultArgParsers { + public static class IntArgumentParser extends ArgParser implements IArgParser.Stateless { + public static final IntArgumentParser INSTANCE = new IntArgumentParser(); + + public IntArgumentParser() { + super(Integer.class); + } + + @Override + public Integer parseArg(CommandArgument arg) throws RuntimeException { + return Integer.parseInt(arg.value); + } + } + + public static class FloatArgumentParser extends ArgParser implements IArgParser.Stateless { + public static final FloatArgumentParser INSTANCE = new FloatArgumentParser(); + + public FloatArgumentParser() { + super(Float.class); + } + + @Override + public Float parseArg(CommandArgument arg) throws RuntimeException { + String value = arg.value; + + if (!value.matches("^[+-]?\\d+(?:\\.\\d+)$")) { + throw new RuntimeException("failed float format check"); + } + + return Float.parseFloat(value); + } + } + + public static class DoubleArgumentParser extends ArgParser implements IArgParser.Stateless { + public static final DoubleArgumentParser INSTANCE = new DoubleArgumentParser(); + + public DoubleArgumentParser() { + super(Double.class); + } + + @Override + public Double parseArg(CommandArgument arg) throws RuntimeException { + String value = arg.value; + + if (!value.matches("^[+-]?\\d+(?:\\.\\d+)$")) { + throw new RuntimeException("failed double format check"); + } + + return Double.parseDouble(value); + } + } + + public static class BooleanArgumentParser extends ArgParser implements IArgParser.Stateless { + public static final BooleanArgumentParser INSTANCE = new BooleanArgumentParser(); + + public static final List TRUTHY_VALUES = asList("1", "true", "yes", "t", "y", "on", "enable"); + public static final List FALSY_VALUES = asList("0", "false", "no", "f", "n", "off", "disable"); + + public BooleanArgumentParser() { + super(Boolean.class); + } + + @Override + public Boolean parseArg(CommandArgument arg) throws RuntimeException { + String value = arg.value; + + if (TRUTHY_VALUES.contains(value.toLowerCase(Locale.US))) { + return true; + } else if (FALSY_VALUES.contains(value.toLowerCase(Locale.US))) { + return false; + } else { + throw new RuntimeException("invalid boolean"); + } + } + } + + public static final List> all = Collections.unmodifiableList(asList( + IntArgumentParser.INSTANCE, + FloatArgumentParser.INSTANCE, + DoubleArgumentParser.INSTANCE, + BooleanArgumentParser.INSTANCE + )); +} diff --git a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java new file mode 100644 index 00000000..1d8890ed --- /dev/null +++ b/src/api/java/baritone/api/utils/command/argparser/IArgParser.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.utils.command.argparser; + +import baritone.api.utils.command.argument.CommandArgument; + +public interface IArgParser { + /** + * @return the class of this parser. + */ + Class getKlass(); + + interface Stateless extends IArgParser { + /** + * @param arg The argument to parse. + * @return What it was parsed into. + * @throws RuntimeException if you want the parsing to fail. The exception will be caught and turned into an + * appropriate error. + */ + T parseArg(CommandArgument arg) throws RuntimeException; + } + + interface Stated extends IArgParser { + Class getStateKlass(); + + /** + * @param arg The argument to parse. + * @param state Can be anything. + * @return What it was parsed into. + * @throws RuntimeException if you want the parsing to fail. The exception will be caught and turned into an + * appropriate error. + */ + T parseArg(CommandArgument arg, S state) throws RuntimeException; + } +} diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java new file mode 100644 index 00000000..5b507fcd --- /dev/null +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -0,0 +1,104 @@ +/* + * 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.command.argument; + +import baritone.api.utils.command.argparser.ArgParserManager; +import baritone.api.utils.command.exception.CommandInvalidTypeException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@SuppressWarnings("UnusedReturnValue") +public class CommandArgument { + public final int index; + public final String value; + public final String rawRest; + public final static Pattern argPattern = Pattern.compile("\\S+"); + + private CommandArgument(int index, String value, String rawRest) { + this.index = index; + this.value = value; + this.rawRest = rawRest; + } + + public > E getE(Class enumClass) { + //noinspection OptionalGetWithoutIsPresent + return Arrays.stream(enumClass.getEnumConstants()) + .filter(e -> e.name().equalsIgnoreCase(value)) + .findFirst() + .get(); + } + + public T getAs(Class type) { + return ArgParserManager.parseStateless(type, this); + } + + public boolean is(Class type) { + try { + getAs(type); + return true; + } catch (Throwable t) { + return false; + } + } + + public T getAs(Class type, Class stateType, S state) { + return ArgParserManager.parseStated(type, stateType, this, state); + } + + public boolean is(Class type, Class stateType, S state) { + try { + getAs(type, stateType, state); + return true; + } catch (Throwable t) { + return false; + } + } + + public static List from(String string, boolean preserveEmptyLast) { + List args = new ArrayList<>(); + Matcher argMatcher = argPattern.matcher(string); + int lastEnd = -1; + while (argMatcher.find()) { + args.add(new CommandArgument( + args.size(), + argMatcher.group(), + string.substring(argMatcher.start()) + )); + + lastEnd = argMatcher.end(); + } + + if (preserveEmptyLast && lastEnd < string.length()) { + args.add(new CommandArgument(args.size(), "", "")); + } + + return args; + } + + public static List from(String string) { + return from(string, false); + } + + public static CommandArgument unknown() { + return new CommandArgument(-1, "", ""); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java new file mode 100644 index 00000000..c8cfe274 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java @@ -0,0 +1,43 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.util.ResourceLocation; + +import java.util.stream.Stream; + +public class BlockById implements IDatatypeFor { + public final Block block; + + public BlockById() { + block = null; + } + + public BlockById(ArgConsumer consumer) { + ResourceLocation id = new ResourceLocation(consumer.getS()); + + if ((block = Block.REGISTRY.getObject(id)) == Blocks.AIR) { + throw new RuntimeException("no block found by that id"); + } + } + + @Override + public Block get() { + return block; + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + return new TabCompleteHelper() + .append( + Block.REGISTRY.getKeys() + .stream() + .map(Object::toString) + ) + .filterPrefixNamespaced(consumer.getS()) + .sortAlphabetically() + .stream(); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java new file mode 100644 index 00000000..eb841724 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java @@ -0,0 +1,45 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityList; +import net.minecraft.util.ResourceLocation; + +import java.util.stream.Stream; + +import static java.util.Objects.isNull; + +public class EntityClassById implements IDatatypeFor> { + public final Class entity; + + public EntityClassById() { + entity = null; + } + + public EntityClassById(ArgConsumer consumer) { + ResourceLocation id = new ResourceLocation(consumer.getS()); + + if (isNull(entity = EntityList.REGISTRY.getObject(id))) { + throw new RuntimeException("no entity found by that id"); + } + } + + @Override + public Class get() { + return entity; + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + return new TabCompleteHelper() + .append( + EntityList.getEntityNameList() + .stream() + .map(Object::toString) + ) + .filterPrefixNamespaced(consumer.getS()) + .sortAlphabetically() + .stream(); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java b/src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java new file mode 100644 index 00000000..7b7dbf72 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java @@ -0,0 +1,28 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.utils.BlockSelector; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.stream.Stream; + +public class ForBlockSelector implements IDatatypeFor { + public final BlockSelector selector; + + public ForBlockSelector() { + selector = null; + } + + public ForBlockSelector(ArgConsumer consumer) { + selector = new BlockSelector(consumer.getS()); + } + + @Override + public BlockSelector get() { + return selector; + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + return consumer.tabCompleteDatatype(BlockById.class); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java new file mode 100644 index 00000000..35caeaa2 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java @@ -0,0 +1,17 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.utils.command.exception.CommandInvalidArgumentException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.stream.Stream; + +/** + * Since interfaces cannot enforce the presence of a constructor, it's on you to make sure there is a constructor that + * accepts a single {@link ArgConsumer} argument. The constructor will perform all needed validation, and + * {@link ArgConsumer#getDatatype(Class)} will handle RuntimeExceptions and translate them into + * {@link CommandInvalidArgumentException}s. There must always be a constructor with no arguments so that + * {@link ArgConsumer} can create an instance for tab completion. + */ +public interface IDatatype { + Stream tabComplete(ArgConsumer consumer); +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java new file mode 100644 index 00000000..313fd6b1 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java @@ -0,0 +1,5 @@ +package baritone.api.utils.command.datatypes; + +public interface IDatatypeFor extends IDatatype { + T get(); +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java new file mode 100644 index 00000000..2168f25a --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java @@ -0,0 +1,5 @@ +package baritone.api.utils.command.datatypes; + +public interface IDatatypePost extends IDatatype { + T apply(O original); +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java new file mode 100644 index 00000000..07e765e5 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java @@ -0,0 +1,53 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.BaritoneAPI; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import net.minecraft.entity.player.EntityPlayer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Objects.isNull; + +public class PlayerByUsername implements IDatatypeFor { + private final List players = + BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().playerEntities; + public final EntityPlayer player; + + public PlayerByUsername() { + player = null; + } + + public PlayerByUsername(ArgConsumer consumer) { + String username = consumer.getS(); + + if (isNull( + player = players + .stream() + .filter(s -> s.getName().equalsIgnoreCase(username)) + .findFirst() + .orElse(null) + )) { + throw new RuntimeException("no player found by that username"); + } + } + + @Override + public EntityPlayer get() { + return player; + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + return new TabCompleteHelper() + .append( + players + .stream() + .map(EntityPlayer::getName) + ) + .filterPrefix(consumer.getS()) + .sortAlphabetically() + .stream(); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java new file mode 100644 index 00000000..788986b1 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java @@ -0,0 +1,54 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.stream.Stream; + +import static java.util.Objects.isNull; + +public class RelativeBlockPos implements IDatatypePost { + final RelativeCoordinate x; + final RelativeCoordinate y; + final RelativeCoordinate z; + + public RelativeBlockPos() { + x = null; + y = null; + z = null; + } + + public RelativeBlockPos(ArgConsumer consumer) { + x = consumer.getDatatype(RelativeCoordinate.class); + y = consumer.getDatatype(RelativeCoordinate.class); + z = consumer.getDatatype(RelativeCoordinate.class); + } + + @Override + public BetterBlockPos apply(BetterBlockPos origin) { + return new BetterBlockPos( + x.apply((double) origin.x), + y.apply((double) origin.y), + z.apply((double) origin.z) + ); + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + if (consumer.has() && !consumer.has(4)) { + while (consumer.has(2)) { + if (isNull(consumer.peekDatatypeOrNull(RelativeCoordinate.class))) { + break; + } + + consumer.get(); + + if (!consumer.has(2)) { + return consumer.tabCompleteDatatype(RelativeCoordinate.class); + } + } + } + + return Stream.empty(); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java new file mode 100644 index 00000000..9516fea7 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java @@ -0,0 +1,57 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.util.math.MathHelper; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +public class RelativeCoordinate implements IDatatypePost { + public static Pattern PATTERN = Pattern.compile("^(~?)([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$"); + + final boolean isRelative; + final double offset; + + public RelativeCoordinate() { + isRelative = true; + offset = 0; + } + + public RelativeCoordinate(ArgConsumer consumer) { + if (!consumer.has()) { + throw new RuntimeException("relative coordinate requires an argument"); + } + + Matcher matcher = PATTERN.matcher(consumer.getS()); + + if (!matcher.matches()) { + throw new RuntimeException("pattern doesn't match"); + } + + isRelative = !matcher.group(1).isEmpty(); + offset = matcher.group(2).isEmpty() ? 0 : Double.parseDouble(matcher.group(2)); + } + + @Override + public Double apply(Double origin) { + if (isRelative) { + return origin + offset; + } + + return offset; + } + + public int applyFloor(double origin) { + return MathHelper.floor(apply(origin)); + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + if (!consumer.has(2) && consumer.getS().matches("^(~|$)")) { + return Stream.of("~"); + } + + return Stream.empty(); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java new file mode 100644 index 00000000..58013f4f --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -0,0 +1,51 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.io.File; +import java.nio.file.FileSystems; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Locale; +import java.util.Objects; +import java.util.stream.Stream; + +public class RelativeFile implements IDatatypePost { + private final Path path; + + public RelativeFile() { + path = null; + } + + public RelativeFile(ArgConsumer consumer) { + try { + path = FileSystems.getDefault().getPath(consumer.getS()); + } catch (InvalidPathException e) { + throw new RuntimeException("invalid path"); + } + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + return Stream.empty(); + } + + public static Stream tabComplete(ArgConsumer consumer, File base) { + String currentPathStringThing = consumer.getS(); + Path currentPath = FileSystems.getDefault().getPath(currentPathStringThing); + Path basePath = currentPath.isAbsolute() ? currentPath.getRoot() : base.toPath(); + boolean useParent = !currentPathStringThing.isEmpty() && !currentPathStringThing.endsWith(File.separator); + File currentFile = currentPath.isAbsolute() ? currentPath.toFile() : new File(base, currentPathStringThing); + + return Arrays.stream(Objects.requireNonNull((useParent ? currentFile.getParentFile() : currentFile).listFiles())) + .map(f -> (currentPath.isAbsolute() ? f : basePath.relativize(f.toPath()).toString()) + + (f.isDirectory() ? File.separator : "")) + .filter(s -> s.toLowerCase(Locale.US).startsWith(currentPathStringThing.toLowerCase(Locale.US))); + } + + @Override + public File apply(File original) { + return original.toPath().resolve(path).toFile(); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java new file mode 100644 index 00000000..13033549 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java @@ -0,0 +1,64 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalBlock; +import baritone.api.pathing.goals.GoalXZ; +import baritone.api.pathing.goals.GoalYLevel; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Objects.nonNull; + +public class RelativeGoal implements IDatatypePost { + final RelativeCoordinate[] coords; + + public RelativeGoal() { + coords = new RelativeCoordinate[0]; + } + + public RelativeGoal(ArgConsumer consumer) { + List coordsList = new ArrayList<>(); + + for (int i = 0; i < 3; i++) { + if (nonNull(consumer.peekDatatypeOrNull(RelativeCoordinate.class))) { + coordsList.add(consumer.getDatatype(RelativeCoordinate.class)); + } + } + + coords = coordsList.toArray(new RelativeCoordinate[0]); + } + + @Override + public Goal apply(BetterBlockPos origin) { + switch (coords.length) { + case 0: + return new GoalBlock(origin); + case 1: + return new GoalYLevel( + coords[0].applyFloor(origin.y) + ); + case 2: + return new GoalXZ( + coords[0].applyFloor(origin.x), + coords[1].applyFloor(origin.z) + ); + case 3: + return new GoalBlock( + coords[0].applyFloor(origin.x), + coords[1].applyFloor(origin.y), + coords[2].applyFloor(origin.z) + ); + default: + throw new IllegalStateException("Unexpected coords size: " + coords.length); + } + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + return consumer.tabCompleteDatatype(RelativeCoordinate.class); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java new file mode 100644 index 00000000..28ff08bb --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java @@ -0,0 +1,42 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalBlock; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.stream.Stream; + +public class RelativeGoalBlock implements IDatatypePost { + final RelativeCoordinate[] coords; + + public RelativeGoalBlock() { + coords = new RelativeCoordinate[0]; + } + + public RelativeGoalBlock(ArgConsumer consumer) { + coords = new RelativeCoordinate[] { + consumer.getDatatype(RelativeCoordinate.class), + consumer.getDatatype(RelativeCoordinate.class), + consumer.getDatatype(RelativeCoordinate.class) + }; + } + + @Override + public GoalBlock apply(BetterBlockPos origin) { + return new GoalBlock( + coords[0].applyFloor(origin.x), + coords[1].applyFloor(origin.y), + coords[2].applyFloor(origin.z) + ); + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + if (consumer.hasAtMost(3)) { + return consumer.tabCompleteDatatype(RelativeCoordinate.class); + } + + return Stream.empty(); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java new file mode 100644 index 00000000..8607c512 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java @@ -0,0 +1,40 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalXZ; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.stream.Stream; + +public class RelativeGoalXZ implements IDatatypePost { + final RelativeCoordinate[] coords; + + public RelativeGoalXZ() { + coords = new RelativeCoordinate[0]; + } + + public RelativeGoalXZ(ArgConsumer consumer) { + coords = new RelativeCoordinate[] { + consumer.getDatatype(RelativeCoordinate.class), + consumer.getDatatype(RelativeCoordinate.class) + }; + } + + @Override + public GoalXZ apply(BetterBlockPos origin) { + return new GoalXZ( + coords[0].applyFloor(origin.x), + coords[1].applyFloor(origin.z) + ); + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + if (consumer.hasAtMost(2)) { + return consumer.tabCompleteDatatype(RelativeCoordinate.class); + } + + return Stream.empty(); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java new file mode 100644 index 00000000..041eeded --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java @@ -0,0 +1,34 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalYLevel; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.stream.Stream; + +public class RelativeGoalYLevel implements IDatatypePost { + final RelativeCoordinate coord; + + public RelativeGoalYLevel() { + coord = null; + } + + public RelativeGoalYLevel(ArgConsumer consumer) { + coord = consumer.getDatatype(RelativeCoordinate.class); + } + + @Override + public GoalYLevel apply(BetterBlockPos origin) { + return new GoalYLevel(coord.applyFloor(origin.y)); + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + if (consumer.hasAtMost(1)) { + return consumer.tabCompleteDatatype(RelativeCoordinate.class); + } + + return Stream.empty(); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/AxisCommand.java b/src/api/java/baritone/api/utils/command/defaults/AxisCommand.java new file mode 100644 index 00000000..367bc698 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/AxisCommand.java @@ -0,0 +1,58 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalAxis; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class AxisCommand extends Command { + public AxisCommand() { + super(asList("axis", "highway"), "Set a goal to the axes"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + Goal goal = new GoalAxis(); + baritone.getCustomGoalProcess().setGoal(goal); + logDirect(String.format("Goal: %s", goal.toString())); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The axis command sets a goal that tells Baritone to head towards the nearest axis. That is, X=0 or Z=0.", + "", + "Usage:", + "> axis" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/BlacklistCommand.java b/src/api/java/baritone/api/utils/command/defaults/BlacklistCommand.java new file mode 100644 index 00000000..e51fa5fc --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/BlacklistCommand.java @@ -0,0 +1,66 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.process.IGetToBlockProcess; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class BlacklistCommand extends Command { + public BlacklistCommand() { + super("blacklist", "Blacklist closest block"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + IGetToBlockProcess proc = baritone.getGetToBlockProcess(); + + if (!proc.isActive()) { + throw new CommandInvalidStateException("GetToBlockProcess is not currently active"); + } + + if (proc.blacklistClosest()) { + logDirect("Blacklisted closest instances"); + } else { + throw new CommandInvalidStateException("No known locations, unable to blacklist"); + } + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "While, for example, mining, this command blacklists the closest block so that Baritone won't attempt to get to it.", + "", + "Usage:", + "> blacklist" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java b/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java new file mode 100644 index 00000000..ab6b3371 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java @@ -0,0 +1,81 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.RelativeBlockPos; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class BuildCommand extends Command { + public BuildCommand() { + super("build", "Build a schematic"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + String filename = String.format("%s.schematic", args.getS()); + BetterBlockPos origin = ctx.playerFeet(); + BetterBlockPos buildOrigin; + + if (args.has()) { + args.requireMax(3); + buildOrigin = args.getDatatype(RelativeBlockPos.class).apply(origin); + } else { + args.requireMax(0); + buildOrigin = origin; + } + + boolean success = baritone.getBuilderProcess().build(filename, buildOrigin); + + if (!success) { + throw new CommandInvalidStateException("Couldn't load the schematic"); + } + + logDirect(String.format("Successfully loaded schematic '%s' for building\nOrigin: %s", filename, buildOrigin)); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + if (args.has(2)) { + args.get(); + + return args.tabCompleteDatatype(RelativeBlockPos.class); + } + + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "Build a schematic from a file.", + "", + "Usage:", + "> build - Loads and builds '.schematic'", + "> build - Custom position" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/CancelCommand.java b/src/api/java/baritone/api/utils/command/defaults/CancelCommand.java new file mode 100644 index 00000000..416feae5 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/CancelCommand.java @@ -0,0 +1,55 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class CancelCommand extends Command { + public CancelCommand() { + super(asList("cancel", "stop"), "Cancel what Baritone is currently doing"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + baritone.getPathingBehavior().cancelEverything(); + logDirect("ok canceled"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The cancel command tells Baritons to stop whatever it's currently doing.", + "", + "Usage:", + "> cancel" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java b/src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java new file mode 100644 index 00000000..300cf974 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java @@ -0,0 +1,79 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.cache.IRememberedInventory; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.ITextComponent; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class ChestsCommand extends Command { + public ChestsCommand() { + super("chests", "Display remembered inventories"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + Set> entries = + ctx.worldData().getContainerMemory().getRememberedInventories().entrySet(); + + if (entries.isEmpty()) { + throw new CommandInvalidStateException("No remembered inventories"); + } + + for (Map.Entry entry : entries) { + BlockPos pos = entry.getKey(); + IRememberedInventory inv = entry.getValue(); + + logDirect(pos.toString()); + + for (ItemStack item : inv.getContents()) { + ITextComponent component = item.getTextComponent(); + component.appendText(String.format(" x %d", item.getCount())); + logDirect(component); + } + } + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The chests command lists remembered inventories, I guess?", + "", + "Usage:", + "> chests" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/ClearareaCommand.java b/src/api/java/baritone/api/utils/command/defaults/ClearareaCommand.java new file mode 100644 index 00000000..f3da2913 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ClearareaCommand.java @@ -0,0 +1,78 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalBlock; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.RelativeBlockPos; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class ClearareaCommand extends Command { + public ClearareaCommand() { + super("cleararea", "Clear an area of all blocks"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + BetterBlockPos pos1 = ctx.playerFeet(); + BetterBlockPos pos2; + + if (args.has()) { + args.requireMax(3); + pos2 = args.getDatatype(RelativeBlockPos.class).apply(pos1); + } else { + args.requireMax(0); + + Goal goal = baritone.getCustomGoalProcess().getGoal(); + + if (!(goal instanceof GoalBlock)) { + throw new CommandInvalidStateException("Goal is not a GoalBlock"); + } else { + pos2 = new BetterBlockPos(((GoalBlock) goal).getGoalPos()); + } + } + + baritone.getBuilderProcess().clearArea(pos1, pos2); + logDirect("Success"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return args.tabCompleteDatatype(RelativeBlockPos.class); + } + + @Override + public List getLongDesc() { + return asList( + "Clear an area of all blocks.", + "", + "Usage:", + "> cleararea - Clears the area marked by your current position and the current GoalBlock", + "> cleararea - Custom second corner rather than your goal" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/ComeCommand.java b/src/api/java/baritone/api/utils/command/defaults/ComeCommand.java new file mode 100644 index 00000000..9817afb7 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ComeCommand.java @@ -0,0 +1,68 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.pathing.goals.GoalBlock; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.entity.Entity; +import net.minecraft.util.math.BlockPos; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Objects.isNull; + +public class ComeCommand extends Command { + public ComeCommand() { + super("come", "Start heading towards your camera"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + Entity entity = MC.getRenderViewEntity(); + + if (isNull(entity)) { + throw new CommandInvalidStateException("render view entity is null"); + } + + baritone.getCustomGoalProcess().setGoalAndPath(new GoalBlock(new BlockPos(entity))); + logDirect("Coming"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The come command tells Baritone to head towards your camera.", + "", + "I'm... not actually sure how useful this is, to be honest.", + "", + "Usage:", + "> come" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/CommandAlias.java b/src/api/java/baritone/api/utils/command/defaults/CommandAlias.java new file mode 100644 index 00000000..94fcd4ed --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/CommandAlias.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.utils.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.manager.CommandManager; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; + +public class CommandAlias extends Command { + public final String target; + + public CommandAlias(List names, String shortDesc, String target) { + super(names, shortDesc); + this.target = target; + } + + public CommandAlias(String name, String shortDesc, String target) { + super(name, shortDesc); + this.target = target; + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + CommandManager.execute(String.format("%s %s", target, args.rawRest())); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return CommandManager.tabComplete(String.format("%s %s", target, args.rawRest())); + } + + @Override + public List getLongDesc() { + return Collections.singletonList(String.format("This command is an alias, for: %s ...", target)); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java b/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java new file mode 100644 index 00000000..18e0bc9d --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.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.utils.command.defaults; + +import baritone.api.utils.command.Command; + +import java.util.Collections; +import java.util.List; + +import static java.util.Arrays.asList; + +public class DefaultCommands { + public static final List commands = Collections.unmodifiableList(asList( + new HelpCommand(), + new SetCommand(), + new CommandAlias(asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), + new CommandAlias("reset", "Reset all settings or just one", "set reset"), + new ExcCommand(), // TODO: remove this debug command... eventually + new GoalCommand(), + new PathCommand(), + new ProcCommand(), + new VersionCommand(), + new RepackCommand(), + new BuildCommand(), + new SchematicaCommand(), + new ComeCommand(), + new AxisCommand(), + new CancelCommand(), + new ForceCancelCommand(), + new GcCommand(), + new InvertCommand(), + new ClearareaCommand(), + PauseResumeCommands.pauseCommand, + PauseResumeCommands.resumeCommand, + PauseResumeCommands.pausedCommand, + new TunnelCommand(), + new RenderCommand(), + new FarmCommand(), + new ChestsCommand(), + new FollowCommand(), + new ExploreFilterCommand(), + new ReloadAllCommand(), + new SaveAllCommand(), + new ExploreCommand(), + new BlacklistCommand(), + new FindCommand(), + new MineCommand() + )); +} diff --git a/src/api/java/baritone/api/utils/command/defaults/EmptyCommand.java b/src/api/java/baritone/api/utils/command/defaults/EmptyCommand.java new file mode 100644 index 00000000..1b5934ba --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/EmptyCommand.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.utils.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.Helper; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class EmptyCommand extends Command { + public EmptyCommand() { + super(asList("name1", "name2"), "Short description"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + ; + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "", + "", + "Usage:", + "> " + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/ExcCommand.java b/src/api/java/baritone/api/utils/command/defaults/ExcCommand.java new file mode 100644 index 00000000..4c05bd02 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ExcCommand.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.utils.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; + +public class ExcCommand extends Command { + public ExcCommand() { + super("exc", "Throw an unhandled exception"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + throw new RuntimeException("HI THERE"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return Collections.emptyList(); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/ExploreCommand.java b/src/api/java/baritone/api/utils/command/defaults/ExploreCommand.java new file mode 100644 index 00000000..a4b2d746 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ExploreCommand.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.utils.command.defaults; + +import baritone.api.Settings; +import baritone.api.pathing.goals.GoalXZ; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.RelativeGoalXZ; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class ExploreCommand extends Command { + public ExploreCommand() { + super("explore", "Explore things"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + if (args.has()) { + args.requireExactly(2); + } else { + args.requireMax(0); + } + + GoalXZ goal = args.has() + ? args.getDatatypePost(RelativeGoalXZ.class, ctx.playerFeet()) + : new GoalXZ(ctx.playerFeet()); + + baritone.getExploreProcess().explore(goal.getX(), goal.getZ()); + logDirect(String.format("Exploring from %s", goal.toString())); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + if (args.hasAtMost(2)) { + return args.tabCompleteDatatype(RelativeGoalXZ.class); + } + + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "Tell Baritone to explore randomly. If you used explorefilter before this, it will be applied.", + "", + "Usage:", + "> explore - Explore from your current position.", + "> explore - Explore from the specified X and Z position." + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java b/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java new file mode 100644 index 00000000..2bd41ae4 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java @@ -0,0 +1,89 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.RelativeFile; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import com.google.gson.JsonSyntaxException; + +import java.io.File; +import java.nio.file.NoSuchFileException; +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class ExploreFilterCommand extends Command { + public ExploreFilterCommand() { + super("explorefilter", "Explore chunks from a json"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(2); + File file = args.getDatatypePost(RelativeFile.class, MC.gameDir.getAbsoluteFile().getParentFile()); + boolean invert = false; + + if (args.has()) { + if (args.getS().equalsIgnoreCase("invert")) { + invert = true; + } else { + throw new CommandInvalidTypeException(args.consumed(), "either \"invert\" or nothing"); + } + } + + try { + baritone.getExploreProcess().applyJsonFilter(file.toPath().toAbsolutePath(), invert); + } catch (NoSuchFileException e) { + throw new CommandInvalidStateException("File not found"); + } catch (JsonSyntaxException e) { + throw new CommandInvalidStateException("Invalid JSON syntax"); + } catch (Exception e) { + throw new RuntimeException(e); + } + + logDirect(String.format("Explore filter applied. Inverted: %s", Boolean.toString(invert))); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + if (args.hasExactlyOne()) { + return RelativeFile.tabComplete(args, MC.gameDir.getAbsoluteFile().getParentFile()); + } + + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "Apply an explore filter before using explore, which tells the explore process which chunks have been explored/not explored.", + "", + "The JSON file will follow this format: [{\"x\":0,\"z\":0},...]", + "", + "If 'invert' is specified, the chunks listed will be considered NOT explored, rather than explored.", + "", + "Usage:", + "> explorefilter [invert] - Load the JSON file referenced by the specified path. If invert is specified, it must be the literal word 'invert'." + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/FarmCommand.java b/src/api/java/baritone/api/utils/command/defaults/FarmCommand.java new file mode 100644 index 00000000..1828dec3 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/FarmCommand.java @@ -0,0 +1,55 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class FarmCommand extends Command { + public FarmCommand() { + super("farm", "Farm nearby crops"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + baritone.getFarmProcess().farm(); + logDirect("Farming"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The farm command starts farming nearby plants. It harvests mature crops and plants new ones.", + "", + "Usage:", + "> farm" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/FindCommand.java b/src/api/java/baritone/api/utils/command/defaults/FindCommand.java new file mode 100644 index 00000000..1f9ce9a7 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/FindCommand.java @@ -0,0 +1,77 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.BlockById; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.block.Block; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class FindCommand extends Command { + public FindCommand() { + super("find", "Find positions of a certain block"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + List toFind = new ArrayList<>(); + + while (args.has()) { + toFind.add(args.getDatatypeFor(BlockById.class)); + } + + BetterBlockPos origin = ctx.playerFeet(); + + toFind.stream() + .flatMap(block -> + ctx.worldData().getCachedWorld().getLocationsOf( + Block.REGISTRY.getNameForObject(block).getPath(), + Integer.MAX_VALUE, + origin.x, + origin.y, + 4 + ).stream() + ) + .map(BetterBlockPos::new) + .map(BetterBlockPos::toString) + .forEach(this::logDirect); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return args.tabCompleteDatatype(BlockById.class); + } + + @Override + public List getLongDesc() { + return asList( + "", + "", + "Usage:", + "> " + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java b/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java new file mode 100644 index 00000000..a2ae8951 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java @@ -0,0 +1,171 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.EntityClassById; +import baritone.api.utils.command.datatypes.IDatatype; +import baritone.api.utils.command.datatypes.IDatatypeFor; +import baritone.api.utils.command.datatypes.PlayerByUsername; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityList; +import net.minecraft.entity.EntityLiving; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ResourceLocation; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.function.Predicate; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Objects.isNull; +import static java.util.Objects.nonNull; + +public class FollowCommand extends Command { + public FollowCommand() { + super("follow", "Follow entity things"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMin(1); + + FollowGroup group; + FollowList list; + List entities = new ArrayList<>(); + List> classes = new ArrayList<>(); + + if (args.hasExactlyOne()) { + baritone.getFollowProcess().follow((group = args.getE(FollowGroup.class)).filter); + list = null; + } else { + args.requireMin(2); + + group = null; + list = args.getE(FollowList.class); + + while (args.has()) { + //noinspection unchecked + Object gotten = args.getDatatypeFor(list.datatype); + + if (gotten instanceof Class) { + //noinspection unchecked + classes.add((Class) gotten); + } else { + entities.add((Entity) gotten); + } + } + + baritone.getFollowProcess().follow( + classes.isEmpty() + ? entities::contains + : e -> classes.stream().anyMatch(c -> c.isInstance(e)) + ); + } + + if (nonNull(group)) { + logDirect(String.format("Following all %s", group.name().toLowerCase(Locale.US))); + } else { + logDirect("Following these types of entities:"); + + if (classes.isEmpty()) { + entities.stream() + .map(Entity::toString) + .forEach(this::logDirect); + } else { + classes.stream() + .map(EntityList::getKey) + .map(Objects::requireNonNull) + .map(ResourceLocation::toString) + .forEach(this::logDirect); + } + } + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + if (args.hasExactlyOne()) { + return new TabCompleteHelper() + .append(FollowGroup.class) + .append(FollowList.class) + .filterPrefix(args.getS()) + .stream(); + } else { + Class followType; + + try { + followType = args.getE(FollowList.class).datatype; + } catch (NullPointerException e) { + return Stream.empty(); + } + + while (args.has(2)) { + if (isNull(args.peekDatatypeOrNull(followType))) { + return Stream.empty(); + } + + args.get(); + } + + return args.tabCompleteDatatype(followType); + } + } + + @Override + public List getLongDesc() { + return asList( + "The follow command tells Baritone to follow certain kinds of entities.", + "", + "Usage:", + "> follow entities - Follows all entities.", + "> follow entity <...> - Follow certain entities (for example 'skeleton', 'horse' etc.)", + "> follow players - Follow players", + "> follow player <...> - Follow certain players" + ); + } + + private enum FollowGroup { + ENTITIES(EntityLiving.class::isInstance), + PLAYERS(EntityPlayer.class::isInstance); /* , + FRIENDLY(entity -> entity.getAttackTarget() != HELPER.mc.player), + HOSTILE(FRIENDLY.filter.negate()); */ + + final Predicate filter; + + FollowGroup(Predicate filter) { + this.filter = filter; + } + } + + private enum FollowList { + ENTITY(EntityClassById.class), + PLAYER(PlayerByUsername.class); + + final Class datatype; + + FollowList(Class datatype) { + this.datatype = datatype; + } + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/ForceCancelCommand.java b/src/api/java/baritone/api/utils/command/defaults/ForceCancelCommand.java new file mode 100644 index 00000000..e78cb696 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ForceCancelCommand.java @@ -0,0 +1,58 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.behavior.IPathingBehavior; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class ForceCancelCommand extends Command { + public ForceCancelCommand() { + super("forcecancel", "Force cancel"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + IPathingBehavior pathingBehavior = baritone.getPathingBehavior(); + pathingBehavior.cancelEverything(); + pathingBehavior.forceCancel(); + logDirect("ok force canceled"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "Like cancel, but more forceful.", + "", + "Usage:", + "> forcecancel" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/GcCommand.java b/src/api/java/baritone/api/utils/command/defaults/GcCommand.java new file mode 100644 index 00000000..7790f2a4 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/GcCommand.java @@ -0,0 +1,57 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class GcCommand extends Command { + public GcCommand() { + super("gc", "Call System.gc()"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + System.gc(); + + logDirect("ok called System.gc()"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "Calls System.gc().", + "", + "Usage:", + "> gc" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/GoalCommand.java b/src/api/java/baritone/api/utils/command/defaults/GoalCommand.java new file mode 100644 index 00000000..cb6a2fbf --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/GoalCommand.java @@ -0,0 +1,104 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.pathing.goals.Goal; +import baritone.api.process.ICustomGoalProcess; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.RelativeCoordinate; +import baritone.api.utils.command.datatypes.RelativeGoal; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Objects.isNull; +import static java.util.Objects.nonNull; + +public class GoalCommand extends Command { + public GoalCommand() { + super("goal", "Set or clear the goal"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + ICustomGoalProcess goalProcess = baritone.getCustomGoalProcess(); + + if (args.has() && asList("reset", "clear", "none").contains(args.peekS())) { + args.requireMax(1); + + if (nonNull(goalProcess.getGoal())) { + goalProcess.setGoal(null); + logDirect("Cleared goal"); + } else { + logDirect("There was no goal to clear"); + } + } else { + args.requireMax(3); + BetterBlockPos origin = baritone.getPlayerContext().playerFeet(); + Goal goal = args.getDatatype(RelativeGoal.class).apply(origin); + goalProcess.setGoal(goal); + logDirect(String.format("Goal: %s", goal.toString())); + } + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + TabCompleteHelper helper = new TabCompleteHelper(); + + if (args.hasExactlyOne()) { + helper.append(Stream.of("reset", "clear", "none", "~")); + } else { + if (args.hasAtMost(3)) { + while (args.has(2)) { + if (isNull(args.peekDatatypeOrNull(RelativeCoordinate.class))) { + break; + } + + args.get(); + + if (!args.has(2)) { + helper.append("~"); + } + } + } + } + + return helper.filterPrefix(args.getS()).stream(); + } + + @Override + public List getLongDesc() { + return asList( + "The goal command allows you to set or clear Baritone's goal.", + "", + "Wherever a coordinate is expected, you can use ~ just like in regular Minecraft commands. Or, you can just use regular numbers.", + "", + "Usage:", + "> goal - Set the goal to your current position", + "> goal - Erase the goal", + "> goal - Set the goal to a Y level", + "> goal - Set the goal to an X,Z position", + "> goal - Set the goal to an X,Y,Z position" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java b/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java new file mode 100644 index 00000000..e96bf5eb --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java @@ -0,0 +1,131 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandNotFoundException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.pagination.Paginator; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import baritone.api.utils.command.manager.CommandManager; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.event.ClickEvent; +import net.minecraft.util.text.event.HoverEvent; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; +import static baritone.api.utils.command.manager.CommandManager.getCommand; +import static java.util.Arrays.asList; +import static java.util.Objects.isNull; + +public class HelpCommand extends Command { + public HelpCommand() { + super(asList("help", "?"), "View all commands or help on specific ones"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(1); + + if (!args.has() || args.is(Integer.class)) { + Paginator.paginate( + args, new Paginator<>( + CommandManager.REGISTRY.descendingStream() + .filter(command -> !command.hiddenFromHelp()) + .collect(Collectors.toCollection(ArrayList::new)) + ), + () -> logDirect("All Baritone commands (clickable):"), + command -> { + String names = String.join("/", command.names); + String name = command.names.get(0); + + return new TextComponentString(name) {{ + getStyle() + .setColor(TextFormatting.GRAY) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("") {{ + getStyle().setColor(TextFormatting.GRAY); + + appendSibling(new TextComponentString(names + "\n") {{ + getStyle().setColor(TextFormatting.WHITE); + }}); + + appendText(command.shortDesc); + appendText("\n\nClick to view full help"); + }} + )) + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + FORCE_COMMAND_PREFIX + String.format("help %s", command.names.get(0)) + )); + + appendSibling(new TextComponentString(" - " + command.shortDesc) {{ + getStyle().setColor(TextFormatting.DARK_GRAY); + }}); + }}; + }, + FORCE_COMMAND_PREFIX + "help %d" + ); + } else { + String commandName = args.getS().toLowerCase(); + Command command = getCommand(commandName); + + if (isNull(command)) { + throw new CommandNotFoundException(commandName); + } + + logDirect(String.format("%s - %s", String.join(" / ", command.names), command.shortDesc)); + logDirect(""); + command.getLongDesc().forEach(this::logDirect); + logDirect(""); + logDirect(new TextComponentString("Click to return to the help menu") {{ + getStyle().setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + FORCE_COMMAND_PREFIX + "help" + )); + }}); + } + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + if (args.hasExactlyOne()) { + return new TabCompleteHelper().addCommands().filterPrefix(args.getS()).stream(); + } + + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "Using this command, you can view detailed help information on how to use certain commands of Baritone.", + "", + "Usage:", + "> help - Lists all commands and their short descriptions.", + "> help - Displays help information on a specific command." + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/InvertCommand.java b/src/api/java/baritone/api/utils/command/defaults/InvertCommand.java new file mode 100644 index 00000000..da420db8 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/InvertCommand.java @@ -0,0 +1,74 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalInverted; +import baritone.api.process.ICustomGoalProcess; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Objects.isNull; + +public class InvertCommand extends Command { + public InvertCommand() { + super("invert", "Run away from the current goal"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); + Goal goal; + + if (isNull(goal = customGoalProcess.getGoal())) { + throw new CommandInvalidStateException("No goal"); + } + + if (goal instanceof GoalInverted) { + goal = ((GoalInverted) goal).origin; + } else { + goal = new GoalInverted(goal); + } + + customGoalProcess.setGoal(goal); + logDirect(String.format("Goal: %s", goal.toString())); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The invert command tells Baritone to head away from the current goal rather than towards it.", + "", + "Usage:", + "> invert - Invert the current goal." + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/MineCommand.java b/src/api/java/baritone/api/utils/command/defaults/MineCommand.java new file mode 100644 index 00000000..ec87dd75 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/MineCommand.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.utils.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.BlockSelector; +import baritone.api.utils.CompositeBlockFilter; +import baritone.api.utils.IBlockFilter; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.BlockById; +import baritone.api.utils.command.datatypes.ForBlockSelector; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class MineCommand extends Command { + public MineCommand() { + super("mine", "Mine some blocks"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + int quantity = args.getAsOrDefault(Integer.class, 0); + args.requireMin(1); + List selectors = new ArrayList<>(); + + while (args.has()) { + selectors.add(args.getDatatypeFor(ForBlockSelector.class)); + } + + IBlockFilter filter = new CompositeBlockFilter(selectors); + baritone.getMineProcess().mine(quantity, filter); + logDirect(String.format("Mining %s", filter.toString())); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return args.tabCompleteDatatype(BlockById.class); + } + + @Override + public List getLongDesc() { + return asList( + "", + "", + "Usage:", + "> " + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/PathCommand.java b/src/api/java/baritone/api/utils/command/defaults/PathCommand.java new file mode 100644 index 00000000..2eafe55c --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/PathCommand.java @@ -0,0 +1,92 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.pathing.goals.Goal; +import baritone.api.process.ICustomGoalProcess; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.RelativeCoordinate; +import baritone.api.utils.command.datatypes.RelativeGoal; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Objects.isNull; + +public class PathCommand extends Command { + public PathCommand() { + super("path", "Start heading towards a goal"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); + Goal goal; + + if (args.has()) { + args.requireMax(3); + goal = args.getDatatype(RelativeGoal.class).apply(ctx.playerFeet()); + } else if (isNull(goal = customGoalProcess.getGoal())) { + throw new CommandInvalidStateException("No goal"); + } + + args.requireMax(0); + customGoalProcess.setGoalAndPath(goal); + logDirect("Now pathing"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + if (args.has() && !args.has(4)) { + while (args.has(2)) { + if (isNull(args.peekDatatypeOrNull(RelativeCoordinate.class))) { + break; + } + + args.get(); + + if (!args.has(2)) { + return new TabCompleteHelper() + .append("~") + .filterPrefix(args.getS()) + .stream(); + } + } + } + + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The path command tells Baritone to head towards the current goal.", + "", + "Usage:", + "> path - Start the pathing.", + "> path ", + "> path ", + "> path - Define the goal here" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java b/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java new file mode 100644 index 00000000..d7746623 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java @@ -0,0 +1,150 @@ +package baritone.api.utils.command.defaults; + +import baritone.api.BaritoneAPI; +import baritone.api.Settings; +import baritone.api.process.IBaritoneProcess; +import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +/** + * Contains the pause, resume, and paused commands. + * + * This thing is scoped to hell, private so far you can't even access it using reflection, because you AREN'T SUPPOSED + * TO USE THIS to pause and resume Baritone. Make your own process that returns {@link PathingCommandType#REQUEST_PAUSE + * REQUEST_PAUSE} + * as needed. + */ +public class PauseResumeCommands { + public static Command pauseCommand; + public static Command resumeCommand; + public static Command pausedCommand; + + static { + final boolean[] paused = {false}; + + BaritoneAPI.getProvider().getPrimaryBaritone().getPathingControlManager().registerProcess( + new IBaritoneProcess() { + @Override + public boolean isActive() { + return paused[0]; + } + + @Override + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + + @Override + public boolean isTemporary() { + return true; + } + + @Override + public void onLostControl() { + } + + @Override + public double priority() { + return DEFAULT_PRIORITY + 1; + } + + @Override + public String displayName0() { + return "Pause/Resume Commands"; + } + } + ); + + pauseCommand = new Command("pause", "Pauses Baritone until you use resume") { + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + if (paused[0]) { + throw new CommandInvalidStateException("Already paused"); + } + + paused[0] = true; + logDirect("Paused"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The pause command tells Baritone to temporarily stop whatever it's doing.", + "", + "This can be used to pause pathing, building, following, whatever. A single use of the resume command will start it right back up again!", + "", + "Usage:", + "> pause" + ); + } + }; + + resumeCommand = new Command("resume", "Resumes Baritone after a pause") { + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + if (!paused[0]) { + throw new CommandInvalidStateException("Not paused"); + } + + paused[0] = false; + logDirect("Resumed"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The resume command tells Baritone to resume whatever it was doing when you last used pause.", + "", + "Usage:", + "> resume" + ); + } + }; + + pausedCommand = new Command("paused", "Tells you if Baritone is paused") { + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + logDirect(String.format("Baritone is %spaused", paused[0] ? "" : "not ")); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The paused command tells you if Baritone is currently paused by use of the pause command.", + "", + "Usage:", + "> paused" + ); + } + }; + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/ProcCommand.java b/src/api/java/baritone/api/utils/command/defaults/ProcCommand.java new file mode 100644 index 00000000..68dbc339 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ProcCommand.java @@ -0,0 +1,83 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.pathing.calc.IPathingControlManager; +import baritone.api.process.IBaritoneProcess; +import baritone.api.process.PathingCommand; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Objects.isNull; + +public class ProcCommand extends Command { + public ProcCommand() { + super("proc", "View process state information"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + IPathingControlManager pathingControlManager = baritone.getPathingControlManager(); + IBaritoneProcess process = pathingControlManager.mostRecentInControl().orElse(null); + + if (isNull(process)) { + throw new CommandInvalidStateException("No process in control"); + } + + logDirect(String.format( + "Class: %s\n" + + "Priority: %s\n" + + "Temporary: %s\n" + + "Display name: %s\n" + + "Last command: %s", + process.getClass().getTypeName(), + Double.toString(process.priority()), + Boolean.toString(process.isTemporary()), + process.displayName(), + pathingControlManager + .mostRecentCommand() + .map(PathingCommand::toString) + .orElse("None") + )); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The proc command provides miscellaneous information about the process currently controlling Baritone.", + "", + "You are not expected to understand this if you aren't familiar with how Baritone works.", + "", + "Usage:", + "> proc - View process information, if present" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/ReloadAllCommand.java b/src/api/java/baritone/api/utils/command/defaults/ReloadAllCommand.java new file mode 100644 index 00000000..633701ba --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ReloadAllCommand.java @@ -0,0 +1,55 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class ReloadAllCommand extends Command { + public ReloadAllCommand() { + super("reloadall", "Reloads Baritone's cache for this world"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + ctx.worldData().getCachedWorld().reloadAllFromDisk(); + logDirect("Reloaded"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The reloadall command reloads Baritone's world cache.", + "", + "Usage:", + "> reloadall" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/RenderCommand.java b/src/api/java/baritone/api/utils/command/defaults/RenderCommand.java new file mode 100644 index 00000000..82398b35 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/RenderCommand.java @@ -0,0 +1,67 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class RenderCommand extends Command { + public RenderCommand() { + super("render", "Fix glitched chunks"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + BetterBlockPos origin = ctx.playerFeet(); + int renderDistance = (MC.gameSettings.renderDistanceChunks + 1) * 16; + MC.renderGlobal.markBlockRangeForRenderUpdate( + origin.x - renderDistance, + 0, + origin.z - renderDistance, + origin.x + renderDistance, + 255, + origin.z + renderDistance + ); + + logDirect("Done"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The render command fixes glitched chunk rendering without having to reload all of them.", + "", + "Usage:", + "> render" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/RepackCommand.java b/src/api/java/baritone/api/utils/command/defaults/RepackCommand.java new file mode 100644 index 00000000..d371603e --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/RepackCommand.java @@ -0,0 +1,78 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.cache.ICachedWorld; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.IChunkProvider; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Objects.nonNull; + +public class RepackCommand extends Command { + public RepackCommand() { + super(asList("repack", "rescan"), "Re-cache chunks"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + 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 queued = 0; + for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) { + for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) { + Chunk chunk = chunkProvider.getLoadedChunk(x, z); + + if (nonNull(chunk) && !chunk.isEmpty()) { + queued++; + cachedWorld.queueForPacking(chunk); + } + } + } + + logDirect(String.format("Queued %d chunks for repacking", queued)); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "Repack chunks around you. This basically re-caches them.", + "", + "Usage:", + "> repack - Repack chunks." + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/SaveAllCommand.java b/src/api/java/baritone/api/utils/command/defaults/SaveAllCommand.java new file mode 100644 index 00000000..163408cc --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/SaveAllCommand.java @@ -0,0 +1,55 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class SaveAllCommand extends Command { + public SaveAllCommand() { + super("saveall", "Saves Baritone's cache for this world"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + ctx.worldData().getCachedWorld().save(); + logDirect("Saved"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The saveall command saves Baritone's world cache.", + "", + "Usage:", + "> saveall" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/SchematicaCommand.java b/src/api/java/baritone/api/utils/command/defaults/SchematicaCommand.java new file mode 100644 index 00000000..2522674f --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/SchematicaCommand.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.utils.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class SchematicaCommand extends Command { + public SchematicaCommand() { + super("schematica", "Opens a Schematica schematic?"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + baritone.getBuilderProcess().buildOpenSchematic(); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "I'm not actually sure what this does.", + "", + "Usage:", + "> schematica" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java b/src/api/java/baritone/api/utils/command/defaults/SetCommand.java new file mode 100644 index 00000000..e9541131 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/SetCommand.java @@ -0,0 +1,275 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.SettingsUtil; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.pagination.Paginator; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.event.ClickEvent; +import net.minecraft.util.text.event.HoverEvent; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static baritone.api.utils.SettingsUtil.settingDefaultToString; +import static baritone.api.utils.SettingsUtil.settingTypeToString; +import static baritone.api.utils.SettingsUtil.settingValueToString; +import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; +import static java.util.Arrays.asList; +import static java.util.Objects.isNull; +import static java.util.Objects.nonNull; +import static java.util.stream.Stream.of; + +public class SetCommand extends Command { + public SetCommand() { + super(asList("set", "setting", "settings"), "View or change settings"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + String arg = args.has() ? args.getS().toLowerCase(Locale.US) : "list"; + boolean viewModified = asList("m", "mod", "modified").contains(arg); + boolean viewAll = asList("all", "l", "list").contains(arg); + boolean paginate = viewModified | viewAll; + if (paginate) { + String search = args.has() && args.peekAsOrNull(Integer.class) == null ? args.getS() : ""; + args.requireMax(1); + + List toPaginate = + viewModified + ? SettingsUtil.modifiedSettings(settings) + : settings.allSettings.stream() + .filter(s -> !s.getName().equals("logger")) + .filter(s -> s.getName().toLowerCase(Locale.US).contains(search.toLowerCase(Locale.US))) + .collect(Collectors.toCollection(ArrayList::new)); + + toPaginate.sort((setting1, setting2) -> String.CASE_INSENSITIVE_ORDER.compare( + setting1.getName(), + setting2.getName() + )); + + Paginator.paginate( + args, + new Paginator<>(toPaginate), + () -> logDirect( + !search.isEmpty() + ? String.format("All settings containing the string '%s':", search) + : String.format("All %ssettings:", viewModified ? "modified " : "") + ), + setting -> new TextComponentString(setting.getName()) {{ + getStyle() + .setColor(TextFormatting.GRAY) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("") {{ + getStyle().setColor(TextFormatting.GRAY); + appendText(setting.getName()); + appendText(String.format("\nType: %s", settingTypeToString(setting))); + appendText(String.format("\n\nValue:\n%s", settingValueToString(setting))); + + if (setting.value != setting.defaultValue) { + appendText(String.format("\n\nDefault:\n%s", settingDefaultToString(setting))); + } + }} + )) + .setClickEvent(new ClickEvent( + ClickEvent.Action.SUGGEST_COMMAND, + settings.prefix.value + String.format("set %s ", setting.getName()) + )); + + appendSibling(new TextComponentString(String.format(" (%s)", settingTypeToString(setting))) {{ + getStyle().setColor(TextFormatting.DARK_GRAY); + }}); + }}, + FORCE_COMMAND_PREFIX + "set " + arg + " " + search + " %d" + ); + + return; + } + + args.requireMax(1); + + boolean resetting = arg.equalsIgnoreCase("reset"); + boolean toggling = arg.equalsIgnoreCase("toggle"); + boolean doingSomething = resetting || toggling; + + if (resetting) { + if (!args.has()) { + logDirect("Please specify 'all' as an argument to reset to confirm you'd really like to do this"); + logDirect("ALL settings will be reset. Use the 'set modified' or 'modified' commands to see what will be reset."); + logDirect("Specify a setting name instead of 'all' to only reset one setting"); + } else if (args.peekS().equalsIgnoreCase("all")) { + SettingsUtil.modifiedSettings(settings).forEach(Settings.Setting::reset); + logDirect("All settings have been reset to their default values"); + + return; + } + } + + if (toggling) { + args.requireMin(1); + } + + String settingName = doingSomething ? args.getS() : arg; + Settings.Setting setting = settings.allSettings.stream() + .filter(s -> s.getName().equalsIgnoreCase(settingName)) + .findFirst() + .orElse(null); + + if (isNull(setting)) { + throw new CommandInvalidTypeException(args.consumed(), "a valid setting"); + } + + if (!doingSomething && !args.has()) { + logDirect(String.format("Value of setting %s:", setting.getName())); + logDirect(settingValueToString(setting)); + } else { + String oldValue = settingValueToString(setting); + + if (resetting) { + setting.reset(); + } else if (toggling) { + if (setting.getValueClass() != Boolean.class) { + throw new CommandInvalidTypeException(args.consumed(), "a toggleable setting", "some other setting"); + } + + //noinspection unchecked + ((Settings.Setting) setting).value ^= true; + + logDirect(String.format( + "Toggled setting %s to %s", + setting.getName(), + Boolean.toString((Boolean) setting.value) + )); + } else { + String newValue = args.getS(); + + try { + SettingsUtil.parseAndApply(settings, arg, newValue); + } catch (Throwable t) { + t.printStackTrace(); + throw new CommandInvalidTypeException(args.consumed(), "a valid value", t); + } + } + + if (!toggling) { + logDirect(String.format( + "Successfully %s %s to %s", + resetting ? "reset" : "set", + setting.getName(), + settingValueToString(setting) + )); + } + + logDirect(new TextComponentString(String.format("Old value: %s", oldValue)) {{ + getStyle() + .setColor(TextFormatting.GRAY) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to set the setting back to this value") + )) + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue) + )); + }}); + + if ((setting.getName().equals("chatControl") && !(Boolean) setting.value && !settings.chatControlAnyway.value) || + setting.getName().equals("chatControlAnyway") && !(Boolean) setting.value && !settings.chatControl.value) { + logDirect("Warning: Chat commands will no longer work. If you want to revert this change, use prefix control (if enabled) or click the old value listed above.", TextFormatting.RED); + } else if (setting.getName().equals("prefixControl") && !(Boolean) setting.value) { + logDirect("Warning: Prefixed commands will no longer work. If you want to revert this change, use chat control (if enabled) or click the old value listed above.", TextFormatting.RED); + } + } + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + if (args.has()) { + String arg = args.getS(); + + if (args.hasExactlyOne()) { + if (arg.equalsIgnoreCase("reset")) { + return new TabCompleteHelper() + .addModifiedSettings() + .prepend("all") + .filterPrefix(args.getS()) + .stream(); + } else if (arg.equalsIgnoreCase("toggle")) { + return new TabCompleteHelper() + .addToggleableSettings() + .filterPrefix(args.getS()) + .stream(); + } + + Settings.Setting setting = settings.byLowerName.get(arg.toLowerCase(Locale.US)); + + if (nonNull(setting)) { + if (setting.getType() == Boolean.class) { + TabCompleteHelper helper = new TabCompleteHelper(); + + if ((Boolean) setting.value) { + helper.append(of("true", "false")); + } else { + helper.append(of("false", "true")); + } + + return helper.filterPrefix(args.getS()).stream(); + } else { + return Stream.of(settingValueToString(setting)); + } + } + } else if (!args.has()) { + return new TabCompleteHelper() + .addSettings() + .sortAlphabetically() + .prepend("list", "modified", "reset", "toggle") + .filterPrefix(arg) + .stream(); + } + } + + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "Using the set command, you can manage all of Baritone's settings. Almost every aspect is controlled by these settings - go wild!", + "", + "Usage:", + "> set - Same as `set list`", + "> set list [page] - View all settings", + "> set modified [page] - View modified settings", + "> set - View the current value of a setting", + "> set - Set the value of a setting", + "> set reset all - Reset ALL SETTINGS to their defaults", + "> set reset - Reset a setting to its default", + "> set toggle - Toggle a boolean setting" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/TunnelCommand.java b/src/api/java/baritone/api/utils/command/defaults/TunnelCommand.java new file mode 100644 index 00000000..62b47562 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/TunnelCommand.java @@ -0,0 +1,63 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalStrictDirection; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class TunnelCommand extends Command { + public TunnelCommand() { + super("tunnel", "Set a goal to tunnel in your current direction"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + Goal goal = new GoalStrictDirection( + ctx.playerFeet(), + ctx.player().getHorizontalFacing() + ); + + baritone.getCustomGoalProcess().setGoal(goal); + logDirect(String.format("Goal: %s", goal.toString())); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The tunnel command sets a goal that tells Baritone to mine completely straight in the direction that you're facing.", + "", + "Usage:", + "> tunnel" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/VersionCommand.java b/src/api/java/baritone/api/utils/command/defaults/VersionCommand.java new file mode 100644 index 00000000..a232ddc3 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/VersionCommand.java @@ -0,0 +1,63 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Objects.isNull; + +public class VersionCommand extends Command { + public VersionCommand() { + super("version", "View the Baritone version"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + + String version = getClass().getPackage().getImplementationVersion(); + + if (isNull(version)) { + throw new CommandInvalidStateException("Null version (this is normal in a dev environment)"); + } else { + logDirect(String.format("You are running Baritone v%s", version)); + } + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The version command prints the version of Baritone you're currently running.", + "", + "Usage:", + "> version - View version information, if present" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/exception/CommandErrorMessageException.java b/src/api/java/baritone/api/utils/command/exception/CommandErrorMessageException.java new file mode 100644 index 00000000..0b33c2d6 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/CommandErrorMessageException.java @@ -0,0 +1,37 @@ +/* + * 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.command.exception; + +import baritone.api.utils.command.Command; +import baritone.api.utils.command.argument.CommandArgument; +import net.minecraft.util.text.TextFormatting; + +import java.util.List; + +import static baritone.api.utils.Helper.HELPER; + +public abstract class CommandErrorMessageException extends CommandException { + protected CommandErrorMessageException(String reason) { + super(reason); + } + + @Override + public void handle(Command command, List args) { + HELPER.logDirect(getMessage(), TextFormatting.RED); + } +} diff --git a/src/api/java/baritone/api/utils/command/exception/CommandException.java b/src/api/java/baritone/api/utils/command/exception/CommandException.java new file mode 100644 index 00000000..8e12f6b6 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/CommandException.java @@ -0,0 +1,37 @@ +/* + * 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.command.exception; + +import baritone.api.utils.command.Command; +import baritone.api.utils.command.argument.CommandArgument; + +import java.util.List; + +public abstract class CommandException extends RuntimeException { + protected CommandException(String reason) { + super(reason); + } + + /** + * Called when this exception is thrown, to handle the exception. + * + * @param command The command that threw it. + * @param args The arguments the command was called with. + */ + public abstract void handle(Command command, List args); +} diff --git a/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java b/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java new file mode 100644 index 00000000..342cf336 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java @@ -0,0 +1,34 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.command.exception; + +import baritone.api.utils.command.argument.CommandArgument; + +public abstract class CommandInvalidArgumentException extends CommandErrorMessageException { + public final CommandArgument arg; + + protected CommandInvalidArgumentException(CommandArgument arg, String reason) { + super(String.format( + "Error at argument #%s: %s", + arg.index == -1 ? "" : Integer.toString(arg.index + 1), + reason + )); + + this.arg = arg; + } +} diff --git a/src/api/java/baritone/api/utils/command/exception/CommandInvalidStateException.java b/src/api/java/baritone/api/utils/command/exception/CommandInvalidStateException.java new file mode 100644 index 00000000..76ad3af0 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/CommandInvalidStateException.java @@ -0,0 +1,24 @@ +/* + * 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.command.exception; + +public class CommandInvalidStateException extends CommandErrorMessageException { + public CommandInvalidStateException(String reason) { + super(reason); + } +} diff --git a/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java b/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java new file mode 100644 index 00000000..0988774d --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.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.command.exception; + +import baritone.api.utils.command.argument.CommandArgument; + +public class CommandInvalidTypeException extends CommandInvalidArgumentException { + public CommandInvalidTypeException(CommandArgument arg, String expected) { + super(arg, String.format("Expected %s", expected)); + } + + public CommandInvalidTypeException(CommandArgument arg, String expected, Throwable cause) { + super(arg, String.format("Expected %s.\nMore details: %s", expected, cause.getMessage())); + } + + public CommandInvalidTypeException(CommandArgument arg, String expected, String got) { + super(arg, String.format("Expected %s, but got %s instead", expected, got)); + } + + public CommandInvalidTypeException(CommandArgument arg, String expected, String got, Throwable cause) { + super(arg, String.format("Expected %s, but got %s instead.\nMore details: %s", expected, got, cause.getMessage())); + } +} diff --git a/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java b/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java new file mode 100644 index 00000000..4dbbb962 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.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.command.exception; + +public class CommandNoParserForTypeException extends CommandErrorMessageException { + public final Class klass; + + public CommandNoParserForTypeException(Class klass) { + super(String.format("Could not find a handler for type %s", klass.getSimpleName())); + this.klass = klass; + } +} diff --git a/src/api/java/baritone/api/utils/command/exception/CommandNotEnoughArgumentsException.java b/src/api/java/baritone/api/utils/command/exception/CommandNotEnoughArgumentsException.java new file mode 100644 index 00000000..29d5d6ba --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/CommandNotEnoughArgumentsException.java @@ -0,0 +1,24 @@ +/* + * 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.command.exception; + +public class CommandNotEnoughArgumentsException extends CommandErrorMessageException { + public CommandNotEnoughArgumentsException(int minArgs) { + super(String.format("Not enough arguments (expected at least %d)", minArgs)); + } +} diff --git a/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java b/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java new file mode 100644 index 00000000..44d3b7b2 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java @@ -0,0 +1,39 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils.command.exception; + +import baritone.api.utils.command.Command; +import baritone.api.utils.command.argument.CommandArgument; + +import java.util.List; + +import static baritone.api.utils.Helper.HELPER; + +public class CommandNotFoundException extends CommandException { + public final String command; + + public CommandNotFoundException(String command) { + super(String.format("Command not found: %s", command)); + this.command = command; + } + + @Override + public void handle(Command command, List args) { + HELPER.logDirect(getMessage()); + } +} diff --git a/src/api/java/baritone/api/utils/command/exception/CommandTooManyArgumentsException.java b/src/api/java/baritone/api/utils/command/exception/CommandTooManyArgumentsException.java new file mode 100644 index 00000000..459940ab --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/CommandTooManyArgumentsException.java @@ -0,0 +1,24 @@ +/* + * 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.command.exception; + +public class CommandTooManyArgumentsException extends CommandErrorMessageException { + public CommandTooManyArgumentsException(int maxArgs) { + super(String.format("Too many arguments (expected at most %d)", maxArgs)); + } +} diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java new file mode 100644 index 00000000..849ace18 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -0,0 +1,83 @@ +/* + * 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.command.exception; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static java.util.Arrays.asList; + +public class CommandUnhandledException extends CommandErrorMessageException { + public static String getStackTrace(Throwable throwable) { + StringWriter sw = new StringWriter(); + throwable.printStackTrace(new PrintWriter(sw)); + return sw.toString(); + } + + public static String getBaritoneStackTrace(String stackTrace) { + List lines = Arrays.stream(stackTrace.split("\n")) + .collect(Collectors.toCollection(ArrayList::new)); + + int lastBaritoneLine = 0; + for (int i = 0; i < lines.size(); i++) { + if (lines.get(i).startsWith("\tat baritone.") && lines.get(i).contains("BaritoneChatControl")) { + lastBaritoneLine = i; + } + } + + return String.join("\n", lines.subList(0, lastBaritoneLine + 1)); + } + + public static String getBaritoneStackTrace(Throwable throwable) { + return getBaritoneStackTrace(getStackTrace(throwable)); + } + + public static String getFriendlierStackTrace(String stackTrace) { + List lines = asList(stackTrace.split("\n")); + + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + if (line.startsWith("\tat ")) { + if (line.startsWith("\tat baritone.")) { + line = line.replaceFirst("^\tat [a-z.]+?([A-Z])", "\tat $1"); + } + + // line = line.replaceFirst("\\(([^)]+)\\)$", "\n\t . $1"); + line = line.replaceFirst("\\([^:]+:(\\d+)\\)$", ":$1"); + lines.set(i, line); + } + } + + return String.join("\n", lines); + } + + public static String getFriendlierStackTrace(Throwable throwable) { + return getFriendlierStackTrace(getBaritoneStackTrace(throwable)); + } + + public CommandUnhandledException(Throwable cause) { + super(String.format( + "An unhandled exception has occurred:\n\n%s", + getFriendlierStackTrace(cause) + )); + } +} diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java new file mode 100644 index 00000000..2999666a --- /dev/null +++ b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java @@ -0,0 +1,113 @@ +/* + * 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.command.execution; + +import baritone.api.BaritoneAPI; +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.exception.CommandException; +import baritone.api.utils.command.exception.CommandUnhandledException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.manager.CommandManager; +import com.mojang.realmsclient.util.Pair; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Objects.isNull; + +public class CommandExecution { + /** + * The command itself + */ + private final Command command; + + /** + * The name this command was called with + */ + public final String label; + + /** + * The arg consumer + */ + public final ArgConsumer args; + + /** + * The Baritone settings + */ + public final Settings settings = BaritoneAPI.getSettings(); + + public CommandExecution(Command command, String label, ArgConsumer args) { + this.command = command; + this.label = label; + this.args = args; + } + + public static String getLabel(String string) { + return string.split("\\s", 2)[0]; + } + + public static Pair> expand(String string, boolean preserveEmptyLast) { + String label = getLabel(string); + List args = CommandArgument.from(string.substring(label.length()), preserveEmptyLast); + return Pair.of(label, args); + } + + public static Pair> expand(String string) { + return expand(string, false); + } + + public void execute() { + try { + command.execute(this); + } catch (CommandException e) { + e.handle(command, args.args); + } catch (Throwable t) { + t.printStackTrace(); + + new CommandUnhandledException(t).handle(command, args.args); + } + } + + public Stream tabComplete() { + return command.tabComplete(this); + } + + public static CommandExecution from(String label, ArgConsumer args) { + Command command = CommandManager.getCommand(label); + + if (isNull(command)) { + return null; + } + + return new CommandExecution( + command, + label, + args + ); + } + + public static CommandExecution from(Pair> pair) { + return from(pair.first(), new ArgConsumer(pair.second())); + } + + public static CommandExecution from(String string) { + return from(expand(string)); + } +} diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java new file mode 100644 index 00000000..6c9ef884 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -0,0 +1,310 @@ +/* + * 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.command.helpers.arguments; + +import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.datatypes.IDatatype; +import baritone.api.utils.command.datatypes.IDatatypeFor; +import baritone.api.utils.command.datatypes.IDatatypePost; +import baritone.api.utils.command.exception.CommandException; +import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; +import baritone.api.utils.command.exception.CommandTooManyArgumentsException; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.stream.Stream; + +public class ArgConsumer { + public final List args; + public final Deque consumed; + + private ArgConsumer(List args, Deque consumed) { + this.args = new ArrayList<>(args); + this.consumed = new LinkedList<>(consumed); + } + + public ArgConsumer(List args) { + this(args, new LinkedList<>()); + } + + public boolean has(int num) { + return args.size() >= num; + } + + public boolean has() { + return has(1); + } + + public boolean hasAtMost(int num) { + return args.size() <= num; + } + + public boolean hasAtMostOne() { + return hasAtMost(1); + } + + public boolean hasExactly(int num) { + return args.size() == num; + } + + public boolean hasExactlyOne() { + return hasExactly(1); + } + + public CommandArgument peek(int index) { + requireMin(1); + return args.get(index); + } + + public CommandArgument peek() { + return peek(0); + } + + public boolean is(Class type) { + return peek().is(type); + } + + public String peekS(int index) { + return peek(index).value; + } + + public String peekS() { + return peekS(0); + } + + public > E peekE(Class enumClass) { + return peek().getE(enumClass); + } + + public > E peekEOrNull(Class enumClass) { + try { + return peekE(enumClass); + } catch (NoSuchElementException e) { + return null; + } + } + + public T peekAs(Class type, int index) { + return peek(index).getAs(type); + } + + public T peekAs(Class type) { + return peekAs(type, 0); + } + + public T peekAsOrDefault(Class type, T def, int index) { + try { + return peekAs(type, index); + } catch (CommandInvalidTypeException e) { + return def; + } + } + + public T peekAsOrDefault(Class type, T def) { + return peekAsOrDefault(type, def, 0); + } + + public T peekAsOrNull(Class type, int index) { + return peekAsOrDefault(type, null, 0); + } + + public T peekAsOrNull(Class type) { + return peekAsOrNull(type, 0); + } + + public T peekDatatype(Class datatype) { + return clone().getDatatype(datatype); + } + + public T peekDatatypeOrNull(Class datatype) { + return new ArgConsumer(args, consumed).getDatatypeOrNull(datatype); + } + + public > T peekDatatypePost(Class datatype, O original) { + return new ArgConsumer(args, consumed).getDatatypePost(datatype, original); + } + + public > T peekDatatypePostOrDefault(Class datatype, O original, T def) { + return new ArgConsumer(args, consumed).getDatatypePostOrDefault(datatype, original, def); + } + + public > T peekDatatypePostOrNull(Class datatype, O original) { + return peekDatatypePostOrDefault(datatype, original, null); + } + + public > T peekDatatypeFor(Class datatype) { + return new ArgConsumer(args, consumed).peekDatatypeFor(datatype); + } + + public > T peekDatatypeForOrDefault(Class datatype, T def) { + return new ArgConsumer(args, consumed).peekDatatypeForOrDefault(datatype, def); + } + + public > T peekDatatypeForOrNull(Class datatype, T def) { + return peekDatatypeForOrDefault(datatype, null); + } + + public CommandArgument get() { + requireMin(1); + CommandArgument arg = args.remove(0); + consumed.add(arg); + return arg; + } + + public String getS() { + return get().value; + } + + public > E getE(Class enumClass) { + try { + return get().getE(enumClass); + } catch (NoSuchElementException e) { + throw new CommandInvalidTypeException(consumed(), enumClass.getSimpleName()); + } + } + + public > E getEOrNull(Class enumClass) { + try { + peekE(enumClass); + return getE(enumClass); + } catch (CommandInvalidTypeException e) { + return null; + } + } + + public T getAs(Class type) { + return get().getAs(type); + } + + public T getAsOrDefault(Class type, T def) { + try { + T val = peek().getAs(type); + get(); + return val; + } catch (CommandInvalidTypeException e) { + return def; + } + } + + public T getAsOrNull(Class type) { + return getAsOrDefault(type, null); + } + + public T getDatatype(Class datatype) { + try { + return datatype.getConstructor(ArgConsumer.class).newInstance(this); + } catch (RuntimeException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { + throw new CommandInvalidTypeException(has() ? peek() : consumed(), datatype.getSimpleName()); + } + } + + public T getDatatypeOrNull(Class datatype) { + try { + return getDatatype(datatype); + } catch (CommandInvalidTypeException e) { + return null; + } + } + + public > T getDatatypePost(Class datatype, O original) { + return getDatatype(datatype).apply(original); + } + + public > T getDatatypePostOrDefault(Class datatype, O original, T def) { + try { + return getDatatypePost(datatype, original); + } catch (CommandException e) { + return def; + } + } + + public > T getDatatypePostOrNull(Class datatype, O original) { + return getDatatypePostOrDefault(datatype, original, null); + } + + public > T getDatatypeFor(Class datatype) { + return getDatatype(datatype).get(); + } + + public > T getDatatypeForOrDefault(Class datatype, T def) { + try { + return getDatatypeFor(datatype); + } catch (CommandInvalidTypeException e) { + return def; + } + } + + public > T getDatatypeForOrNull(Class datatype) { + return getDatatypeForOrDefault(datatype, null); + } + + public Stream tabCompleteDatatype(Class datatype) { + try { + return datatype.getConstructor().newInstance().tabComplete(this); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + e.printStackTrace(); + } catch (CommandException ignored) { + } + + return Stream.empty(); + } + + public String rawRest() { + return args.size() > 0 ? args.get(0).rawRest : ""; + } + + public void requireMin(int min) { + if (args.size() < min) { + throw new CommandNotEnoughArgumentsException(min + consumed.size()); + } + } + + public void requireMax(int max) { + if (args.size() > max) { + throw new CommandTooManyArgumentsException(max + consumed.size()); + } + } + + public void requireExactly(int args) { + requireMin(args); + requireMax(args); + } + + public boolean hasConsumed() { + return !consumed.isEmpty(); + } + + public CommandArgument consumed() { + return consumed.size() > 0 ? consumed.getLast() : CommandArgument.unknown(); + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + @Override + public ArgConsumer clone() { + return new ArgConsumer(args, consumed); + } + + public static ArgConsumer from(String string) { + return new ArgConsumer(CommandArgument.from(string)); + } +} diff --git a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java new file mode 100644 index 00000000..db7942b6 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java @@ -0,0 +1,162 @@ +/* + * 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.command.helpers.pagination; + +import baritone.api.utils.Helper; +import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.event.ClickEvent; +import net.minecraft.util.text.event.HoverEvent; + +import java.util.List; +import java.util.function.Function; + +import static java.util.Objects.nonNull; + +public class Paginator implements Helper { + public final List entries; + public int pageSize = 8; + public int page = 1; + + public Paginator(List entries) { + this.entries = entries; + } + + public Paginator setPageSize(int pageSize) { + this.pageSize = pageSize; + + return this; + } + + public int getMaxPage() { + return (entries.size() - 1) / pageSize + 1; + } + + public boolean validPage(int page) { + return page > 0 && page <= getMaxPage(); + } + + public Paginator skipPages(int pages) { + page += pages; + + return this; + } + + public void display(Function transform, String commandFormat) { + int offset = (page - 1) * pageSize; + + for (int i = offset; i < offset + pageSize; i++) { + if (i < entries.size()) { + logDirect(transform.apply(entries.get(i))); + } else { + logDirect("--", TextFormatting.DARK_GRAY); + } + } + + boolean hasPrevPage = nonNull(commandFormat) && validPage(page - 1); + boolean hasNextPage = nonNull(commandFormat) && validPage(page + 1); + + logDirect(new TextComponentString("") {{ + getStyle().setColor(TextFormatting.GRAY); + + appendSibling(new TextComponentString("<<") {{ + if (hasPrevPage) { + getStyle() + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format(commandFormat, page - 1) + )) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to view previous page") + )); + } else { + getStyle().setColor(TextFormatting.DARK_GRAY); + } + }}); + + appendText(" | "); + + appendSibling(new TextComponentString(">>") {{ + if (hasNextPage) { + getStyle() + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format(commandFormat, page + 1) + )) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to view next page") + )); + } else { + getStyle().setColor(TextFormatting.DARK_GRAY); + } + }}); + + appendText(String.format(" %d/%d", page, getMaxPage())); + }}); + } + + public void display(Function transform) { + display(transform, null); + } + + public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform, String commandFormat) { + int page = 1; + + consumer.requireMax(1); + + if (consumer.has()) { + page = consumer.getAs(Integer.class); + + if (!pagi.validPage(page)) { + throw new CommandInvalidTypeException( + consumer.consumed(), + String.format( + "a valid page (1-%d)", + pagi.getMaxPage() + ), + consumer.consumed().value + ); + } + } + + pagi.skipPages(page - pagi.page); + + if (nonNull(pre)) { + pre.run(); + } + + pagi.display(transform, commandFormat); + } + + public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform, String commandName) { + paginate(consumer, pagi, null, transform, commandName); + } + + public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform) { + paginate(consumer, pagi, pre, transform, null); + } + + public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform) { + paginate(consumer, pagi, null, transform, null); + } +} diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java new file mode 100644 index 00000000..ce689b0b --- /dev/null +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -0,0 +1,158 @@ +/* + * 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.command.helpers.tabcomplete; + +import baritone.api.BaritoneAPI; +import baritone.api.Settings; +import baritone.api.utils.SettingsUtil; +import baritone.api.utils.command.manager.CommandManager; +import net.minecraft.util.ResourceLocation; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Stream; + +import static java.util.stream.Stream.concat; +import static java.util.stream.Stream.of; + +public class TabCompleteHelper { + private Stream stream; + + public TabCompleteHelper(String[] base) { + stream = Arrays.stream(base); + } + + public TabCompleteHelper(List base) { + stream = base.stream(); + } + + public TabCompleteHelper() { + this(new String[0]); + } + + public TabCompleteHelper append(Stream source) { + stream = concat(stream, source); + + return this; + } + + public TabCompleteHelper append(String... source) { + return append(of(source)); + } + + public TabCompleteHelper append(Class> num) { + return append( + Arrays.stream(num.getEnumConstants()) + .map(Enum::name) + .map(String::toLowerCase) + ); + } + + public TabCompleteHelper prepend(Stream source) { + stream = concat(source, stream); + + return this; + } + + public TabCompleteHelper prepend(String... source) { + return prepend(of(source)); + } + + public TabCompleteHelper prepend(Class> num) { + return prepend( + Arrays.stream(num.getEnumConstants()) + .map(Enum::name) + .map(String::toLowerCase) + ); + } + + public TabCompleteHelper map(Function transform) { + stream = stream.map(transform); + + return this; + } + + public TabCompleteHelper filter(Predicate filter) { + stream = stream.filter(filter); + + return this; + } + + public TabCompleteHelper sort(Comparator comparator) { + stream = stream.sorted(comparator); + + return this; + } + + public TabCompleteHelper sortAlphabetically() { + return sort(String.CASE_INSENSITIVE_ORDER); + } + + public TabCompleteHelper filterPrefix(String prefix) { + return filter(x -> x.toLowerCase(Locale.US).startsWith(prefix.toLowerCase(Locale.US))); + } + + public TabCompleteHelper filterPrefixNamespaced(String prefix) { + return filterPrefix(new ResourceLocation(prefix).toString()); + } + + public String[] build() { + return stream.toArray(String[]::new); + } + + public Stream stream() { + return stream; + } + + public TabCompleteHelper addCommands() { + return append( + CommandManager.REGISTRY.descendingStream() + .flatMap(command -> command.names.stream()) + .distinct() + ); + } + + public TabCompleteHelper addSettings() { + return append( + BaritoneAPI.getSettings().allSettings.stream() + .map(Settings.Setting::getName) + .filter(s -> !s.equalsIgnoreCase("logger")) + .sorted(String.CASE_INSENSITIVE_ORDER) + ); + } + + public TabCompleteHelper addModifiedSettings() { + return append( + SettingsUtil.modifiedSettings(BaritoneAPI.getSettings()).stream() + .map(Settings.Setting::getName) + .sorted(String.CASE_INSENSITIVE_ORDER) + ); + } + + public TabCompleteHelper addToggleableSettings() { + return append( + BaritoneAPI.getSettings().getAllValuesByType(Boolean.class).stream() + .map(Settings.Setting::getName) + .sorted(String.CASE_INSENSITIVE_ORDER) + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/manager/CommandManager.java b/src/api/java/baritone/api/utils/command/manager/CommandManager.java new file mode 100644 index 00000000..75dff566 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/manager/CommandManager.java @@ -0,0 +1,93 @@ +/* + * 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.command.manager; + +import baritone.api.utils.command.Command; +import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.defaults.DefaultCommands; +import baritone.api.utils.command.execution.CommandExecution; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import baritone.api.utils.command.registry.Registry; +import com.mojang.realmsclient.util.Pair; + +import java.util.List; +import java.util.Locale; +import java.util.stream.Stream; + +import static java.util.Objects.isNull; +import static java.util.Objects.nonNull; + +public class CommandManager { + public static final Registry REGISTRY = new Registry<>(); + + static { + DefaultCommands.commands.forEach(REGISTRY::register); + } + + /** + * @param name The command name to search for. + * @return The command, if found. + */ + public static Command getCommand(String name) { + for (Command command : REGISTRY.entries) { + if (command.names.contains(name.toLowerCase(Locale.US))) { + return command; + } + } + + return null; + } + + public static void execute(CommandExecution execution) { + execution.execute(); + } + + public static boolean execute(String string) { + CommandExecution execution = CommandExecution.from(string); + + if (nonNull(execution)) { + execution.execute(); + } + + return nonNull(execution); + } + + public static Stream tabComplete(CommandExecution execution) { + return execution.tabComplete(); + } + + public static Stream tabComplete(Pair> pair) { + CommandExecution execution = CommandExecution.from(pair); + return isNull(execution) ? Stream.empty() : tabComplete(execution); + } + + public static Stream tabComplete(String prefix) { + Pair> pair = CommandExecution.expand(prefix, true); + String label = pair.first(); + List args = pair.second(); + + if (args.isEmpty()) { + return new TabCompleteHelper() + .addCommands() + .filterPrefix(label) + .stream(); + } else { + return tabComplete(pair); + } + } +} diff --git a/src/api/java/baritone/api/utils/command/registry/Registry.java b/src/api/java/baritone/api/utils/command/registry/Registry.java new file mode 100644 index 00000000..c92d4d56 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/registry/Registry.java @@ -0,0 +1,148 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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.command.registry; + +import java.util.Collection; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Map; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Consumer; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +/** + * This registry class allows for registration and unregistration of a certain type. This is mainly designed for use by + * event handlers where newly registered ones are encountered first during iteration and can therefore override older + * ones. In Baritone, this is used for commands and argument parsers so that mods and addons can extend Baritone's + * functionality without resorting to hacks, wrappers, or mixins. + * + * @param The entry type that will be stored in this registry. This can be anything, really - preferably anything + * that works as a HashMap key, as that's what's used to keep track of which entries are registered or not. + */ +@SuppressWarnings({"unused", "UnusedReturnValue"}) +public class Registry { + /** + * An internal linked list of all the entries that are currently registered. This is a linked list so that entries + * can be inserted at the beginning, which means that newer entries are encountered first during iteration. This is + * an important property of the registry that makes it more useful than a simple list, and also the reason it does + * not just use a map. + */ + private final Deque _entries = new LinkedList<>(); + + /** + * A HashMap containing keys for every entry currently registered. Map entries are added to this map when something + * is registered and removed from the map when they are unregistered. An entry simply being present in this map + * indicates that it is currently registered and therefore can be removed and should not be reregistered. + */ + private final Map registered = new HashMap<>(); + + /** + * The collection of entries that are currently in this registry. This is a collection (and not a list) because, + * internally, entries are stored in a linked list, which is not the same as a normal list. + */ + public final Collection entries = Collections.unmodifiableCollection(_entries); + + /** + * @param entry The entry to check. + * @return If this entry is currently registered in this registry. + */ + public boolean registered(V entry) { + return registered.containsKey(entry); + } + + /** + * Ensures that the entry {@code entry} is registered. + * + * @param entry The entry to register. + * @return A boolean indicating whether or not this is a new registration. No matter the value of this boolean, the + * entry is always guaranteed to now be in this registry. This boolean simply indicates if the entry was not + * in the map prior to this method call. + */ + public boolean register(V entry) { + if (!registered(entry)) { + _entries.addFirst(entry); + registered.put(entry, true); + + return true; + } + + return false; + } + + /** + * Unregisters this entry from this registry. After this method call, the entry is guaranteed to be removed from the + * registry, since each entry only ever appears once. + * + * @param entry The entry to unregister. + */ + public void unregister(V entry) { + if (registered(entry)) { + return; + } + + _entries.remove(entry); + registered.remove(entry); + } + + /** + * Returns an iterator that iterates over each entry in this registry, with the newest elements iterated over first. + * Internally, as new elements are prepended to the registry rather than appended to the end, this order is the best + * way to search through the registry if you want to discover newer items first. + */ + public Iterator iterator() { + return _entries.iterator(); + } + + /** + * Returns an iterator that iterates over each entry in this registry, in the order they were added. Internally, + * this iterates through the registry backwards, as new elements are prepended to the registry rather than appended + * to the end. You should only do this when you need to, for example, list elements in order - it is almost always + * fine to simply use {@link Iterable#forEach(Consumer) forEach} on the {@link #entries} collection instead. + */ + public Iterator descendingIterator() { + return _entries.descendingIterator(); + } + + /** + * Returns a stream that contains each entry in this registry, with the newest elements ordered first. Internally, + * as new elements are prepended to the registry rather than appended to the end, this order is the best way to + * search through the registry if you want to discover newer items first. + */ + public Stream stream() { + return _entries.stream(); + } + + /** + * Returns a stream that returns each entry in this registry, in the order they were added. Internally, this orders + * the registry backwards, as new elements are prepended to the registry rather than appended to the end. You should + * only use this when you need to, for example, list elements in order - it is almost always fine to simply use the + * regular {@link #stream()} method instead. + */ + public Stream descendingStream() { + return StreamSupport.stream(Spliterators.spliterator( + descendingIterator(), + _entries.size(), + Spliterator.SIZED | Spliterator.SUBSIZED + ), false); + } +} diff --git a/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java new file mode 100644 index 00000000..8aabfd69 --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java @@ -0,0 +1,20 @@ +package baritone.launch.mixins; + +import net.minecraft.client.gui.GuiChat; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(GuiChat.ChatTabCompleter.class) +public abstract class MixinChatTabCompleter extends MixinTabCompleter { + @Inject(method = "*", at = @At("RETURN")) + private void onConstruction(CallbackInfo ci) { + isChatCompleter = true; + } + + @Inject(method = "complete", at = @At("HEAD"), cancellable = true) + private void onComplete(CallbackInfo ci) { + if (dontComplete) ci.cancel(); + } +} diff --git a/src/launch/java/baritone/launch/mixins/MixinGuiChat.java b/src/launch/java/baritone/launch/mixins/MixinGuiChat.java new file mode 100644 index 00000000..310bfd7c --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinGuiChat.java @@ -0,0 +1,23 @@ +package baritone.launch.mixins; + +import baritone.utils.accessor.ITabCompleter; +import net.minecraft.client.gui.GuiChat; +import net.minecraft.util.TabCompleter; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(GuiChat.class) +public abstract class MixinGuiChat implements net.minecraft.util.ITabCompleter { + @Shadow + private TabCompleter tabCompleter; + + @Inject(method = "setCompletions", at = @At("HEAD"), cancellable = true) + private void onSetCompletions(String[] newCompl, CallbackInfo ci) { + if (((ITabCompleter) tabCompleter).onGuiChatSetCompletions(newCompl)) { + ci.cancel(); + } + } +} diff --git a/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java b/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java new file mode 100644 index 00000000..0731df1f --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java @@ -0,0 +1,15 @@ +package baritone.launch.mixins; + +import baritone.api.utils.command.Lol; +import net.minecraft.client.gui.GuiScreen; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +import java.net.URI; + +@Mixin(GuiScreen.class) +public abstract class MixinGuiScreen implements Lol { + @Override + @Invoker("openWebLink") + public abstract void openLink(URI url); +} diff --git a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java new file mode 100644 index 00000000..4e36491b --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java @@ -0,0 +1,115 @@ +package baritone.launch.mixins; + +import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; +import baritone.api.event.events.TabCompleteEvent; +import baritone.utils.accessor.ITabCompleter; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.util.TabCompleter; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +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.callback.CallbackInfo; + +import static java.util.Objects.isNull; + +@Mixin(TabCompleter.class) +public abstract class MixinTabCompleter implements ITabCompleter { + @Shadow + @Final + protected GuiTextField textField; + + @Shadow + protected boolean requestedCompletions; + + @Shadow + public abstract void setCompletions(String... newCompl); + + @Unique + protected boolean isChatCompleter = false; + + @Unique + protected boolean dontComplete = false; + + @Override + public String getPrefix() { + return textField.getText().substring(0, textField.getCursorPosition()); + } + + @Override + public void setPrefix(String prefix) { + textField.setText(prefix + textField.getText().substring(textField.getCursorPosition())); + textField.setCursorPosition(prefix.length()); + } + + @Inject(method = "requestCompletions", at = @At("HEAD"), cancellable = true) + private void onRequestCompletions(String prefix, CallbackInfo ci) { + if (!isChatCompleter) { + return; + } + + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(Minecraft.getMinecraft().player); + + if (isNull(baritone)) { + return; + } + + TabCompleteEvent.Pre event = new TabCompleteEvent.Pre(prefix); + baritone.getGameEventHandler().onPreTabComplete(event); + + if (event.isCancelled()) { + ci.cancel(); + return; + } + + if (event.prefix.wasModified()) { + setPrefix(event.prefix.get()); + } + + if (event.completions.wasModified()) { + ci.cancel(); + + dontComplete = true; + + try { + requestedCompletions = true; + setCompletions(event.completions.get()); + } finally { + dontComplete = false; + } + } + } + + @Override + public boolean onGuiChatSetCompletions(String[] newCompl) { + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(Minecraft.getMinecraft().player); + + if (isNull(baritone)) { + return false; + } + + TabCompleteEvent.Post event = new TabCompleteEvent.Post(getPrefix(), newCompl); + baritone.getGameEventHandler().onPostTabComplete(event); + + if (event.isCancelled()) { + return true; + } + + if (event.prefix.wasModified()) { + String prefix = event.prefix.get(); + textField.setText(prefix + textField.getText().substring(textField.getCursorPosition())); + textField.setCursorPosition(prefix.length()); + } + + if (event.completions.wasModified()) { + setCompletions(event.completions.get()); + return true; + } + + return false; + } +} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index 3b5fa70c..66ef181d 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -23,6 +23,10 @@ "MixinRenderChunk", "MixinRenderList", "MixinVboRenderList", - "MixinWorldClient" + "MixinWorldClient", + "MixinTabCompleter", + "MixinGuiChat", + "MixinChatTabCompleter", + "MixinGuiScreen" ] } \ No newline at end of file diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index a4b2d436..d2aae776 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -21,7 +21,7 @@ import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.event.listener.IEventBus; -import baritone.api.utils.ExampleBaritoneControl; +import baritone.api.utils.command.BaritoneChatControl; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.behavior.*; @@ -109,7 +109,7 @@ public class Baritone implements IBaritone { memoryBehavior = new MemoryBehavior(this); inventoryBehavior = new InventoryBehavior(this); inputOverrideHandler = new InputOverrideHandler(this); - new ExampleBaritoneControl(this); + new BaritoneChatControl(this); } this.pathingControlManager = new PathingControlManager(this); diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 7219175e..d1d9a7d5 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -19,7 +19,11 @@ package baritone.behavior; import baritone.Baritone; import baritone.api.behavior.IPathingBehavior; -import baritone.api.event.events.*; +import baritone.api.event.events.PathEvent; +import baritone.api.event.events.PlayerUpdateEvent; +import baritone.api.event.events.RenderEvent; +import baritone.api.event.events.SprintStateEvent; +import baritone.api.event.events.TickEvent; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; @@ -55,6 +59,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private boolean safeToCancel; private boolean pauseRequestedLastTick; private boolean unpausedLastTick; + private boolean pausedThisTick; private boolean cancelRequested; private boolean calcFailedLastTick; @@ -108,6 +113,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } private void tickPath() { + pausedThisTick = false; if (pauseRequestedLastTick && safeToCancel) { pauseRequestedLastTick = false; if (unpausedLastTick) { @@ -115,6 +121,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); } unpausedLastTick = false; + pausedThisTick = true; return; } unpausedLastTick = true; @@ -130,8 +137,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, BetterBlockPos calcFrom = inProgress.getStart(); Optional currentBest = inProgress.bestPathSoFar(); if ((current == null || !current.getPath().getDest().equals(calcFrom)) // if current ends in inProgress's start, then we're ok - && !calcFrom.equals(ctx.playerFeet()) && !calcFrom.equals(expectedSegmentStart) // if current starts in our playerFeet or pathStart, then we're ok - && (!currentBest.isPresent() || (!currentBest.get().positions().contains(ctx.playerFeet()) && !currentBest.get().positions().contains(expectedSegmentStart))) // if + && !calcFrom.equals(ctx.playerFeet()) && !calcFrom.equals(expectedSegmentStart) // if current starts in our playerFeet or pathStart, then we're ok + && (!currentBest.isPresent() || (!currentBest.get().positions().contains(ctx.playerFeet()) && !currentBest.get().positions().contains(expectedSegmentStart))) // if ) { // when it was *just* started, currentBest will be empty so we need to also check calcFrom since that's always present inProgress.cancel(); // cancellation doesn't dispatch any events @@ -279,6 +286,16 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return goal; } + @Override + public boolean isPathing() { + return hasPath() && !pausedThisTick; + } + + @Override + public boolean hasPath() { + return current != null; + } + @Override public PathExecutor getCurrent() { return current; diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index d6cf69c3..22c042f7 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -18,6 +18,7 @@ package baritone.cache; import baritone.api.cache.IWorldScanner; +import baritone.api.utils.IBlockFilter; import baritone.api.utils.IPlayerContext; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -38,14 +39,8 @@ public enum WorldScanner implements IWorldScanner { private static final int[] DEFAULT_COORDINATE_ITERATION_ORDER = IntStream.range(0, 16).toArray(); @Override - public List scanChunkRadius(IPlayerContext ctx, List blocks, int max, int yLevelThreshold, int maxSearchRadius) { - if (blocks.contains(null)) { - throw new IllegalStateException("Invalid block name should have been caught earlier: " + blocks.toString()); - } + public List scanChunkRadius(IPlayerContext ctx, IBlockFilter filter, int max, int yLevelThreshold, int maxSearchRadius) { ArrayList res = new ArrayList<>(); - if (blocks.isEmpty()) { - return res; - } ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); int maxSearchRadiusSq = maxSearchRadius * maxSearchRadius; @@ -75,7 +70,7 @@ public enum WorldScanner implements IWorldScanner { continue; } allUnloaded = false; - if (scanChunkInto(chunkX << 4, chunkZ << 4, chunk, blocks, res, max, yLevelThreshold, playerY, coordinateIterationOrder)) { + if (scanChunkInto(chunkX << 4, chunkZ << 4, chunk, filter, res, max, yLevelThreshold, playerY, coordinateIterationOrder)) { foundWithinY = true; } } @@ -91,11 +86,7 @@ public enum WorldScanner implements IWorldScanner { } @Override - public List scanChunk(IPlayerContext ctx, List blocks, ChunkPos pos, int max, int yLevelThreshold) { - if (blocks.isEmpty()) { - return Collections.emptyList(); - } - + public List scanChunk(IPlayerContext ctx, IBlockFilter filter, ChunkPos pos, int max, int yLevelThreshold) { ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); Chunk chunk = chunkProvider.getLoadedChunk(pos.x, pos.z); int playerY = ctx.playerFeet().getY(); @@ -105,11 +96,11 @@ public enum WorldScanner implements IWorldScanner { } ArrayList res = new ArrayList<>(); - scanChunkInto(pos.x << 4, pos.z << 4, chunk, blocks, res, max, yLevelThreshold, playerY, DEFAULT_COORDINATE_ITERATION_ORDER); + scanChunkInto(pos.x << 4, pos.z << 4, chunk, filter, res, max, yLevelThreshold, playerY, DEFAULT_COORDINATE_ITERATION_ORDER); return res; } - private boolean scanChunkInto(int chunkX, int chunkZ, Chunk chunk, List search, Collection result, int max, int yLevelThreshold, int playerY, int[] coordinateIterationOrder) { + private boolean scanChunkInto(int chunkX, int chunkZ, Chunk chunk, IBlockFilter filter, Collection result, int max, int yLevelThreshold, int playerY, int[] coordinateIterationOrder) { ExtendedBlockStorage[] chunkInternalStorageArray = chunk.getBlockStorageArray(); boolean foundWithinY = false; for (int yIndex = 0; yIndex < 16; yIndex++) { @@ -126,7 +117,7 @@ public enum WorldScanner implements IWorldScanner { for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) { IBlockState state = bsc.get(x, y, z); - if (search.contains(state.getBlock())) { + if (filter.selected(state)) { int yy = yReal | y; if (result.size() >= max) { if (Math.abs(yy - playerY) < yLevelThreshold) { diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 2ff688ad..76ae0b4e 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -69,6 +69,16 @@ public final class GameEventHandler implements IEventBus, Helper { listeners.forEach(l -> l.onSendChatMessage(event)); } + @Override + public void onPreTabComplete(TabCompleteEvent.Pre event) { + listeners.forEach(l -> l.onPreTabComplete(event)); + } + + @Override + public void onPostTabComplete(TabCompleteEvent.Post event) { + listeners.forEach(l -> l.onPostTabComplete(event)); + } + @Override public final void onChunkEvent(ChunkEvent event) { EventState state = event.getState(); diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 84ea8da3..0c37ac16 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -92,6 +92,11 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil paused = true; } + @Override + public boolean isPaused() { + return paused; + } + @Override public boolean build(String name, File schematic, Vec3i origin) { NBTTagCompound tag; diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index 00273a9f..e78c0ce1 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -24,6 +24,7 @@ import baritone.api.pathing.goals.GoalComposite; import baritone.api.process.IFarmProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; +import baritone.api.utils.BlockListFilter; import baritone.api.utils.RayTraceUtils; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; @@ -180,7 +181,7 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro } 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 = WorldScanner.INSTANCE.scanChunkRadius(ctx, new BlockListFilter(scan), 256, 10, 10)); } if (locations == null) { return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 4fb4d540..755f27c2 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -22,6 +22,7 @@ import baritone.api.pathing.goals.*; import baritone.api.process.IGetToBlockProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; +import baritone.api.utils.BlockListFilter; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; @@ -171,7 +172,7 @@ public final class GetToBlockProcess extends BaritoneProcessHelper implements IG } private synchronized void rescan(List known, CalculationContext context) { - List positions = MineProcess.searchWorld(context, Collections.singletonList(gettingTo), 64, known, blacklist); + List positions = MineProcess.searchWorld(context, new BlockListFilter(gettingTo), 64, known, blacklist); positions.removeIf(blacklist::contains); knownLocations = positions; } diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index f3b1d20b..1b3ef0f1 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -22,7 +22,10 @@ import baritone.api.pathing.goals.*; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; +import baritone.api.utils.BlockSelector; import baritone.api.utils.BlockUtils; +import baritone.api.utils.CompositeBlockFilter; +import baritone.api.utils.IBlockFilter; import baritone.api.utils.IPlayerContext; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; @@ -59,7 +62,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro private static final int ORE_LOCATIONS_COUNT = 64; - private List mining; + private IBlockFilter filter; private List knownOreLocations; private List blacklist; // inaccessible private BlockPos branchPoint; @@ -73,28 +76,29 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro @Override public boolean isActive() { - return mining != null; + return filter != null; } @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (desiredQuantity > 0) { - Item item = mining.get(0).getItemDropped(mining.get(0).getDefaultState(), new Random(), 0); - int curr = ctx.player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum(); - System.out.println("Currently have " + curr + " " + item); + int curr = ctx.player().inventory.mainInventory.stream() + .filter(stack -> filter.selected(BlockSelector.stateFromItem(stack))) + .mapToInt(ItemStack::getCount).sum(); + System.out.println("Currently have " + curr + " valid items"); if (curr >= desiredQuantity) { - logDirect("Have " + curr + " " + item.getItemStackDisplayName(new ItemStack(item, 1))); + logDirect("Have " + curr + " valid items"); cancel(); return null; } } if (calcFailed) { if (!knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) { - logDirect("Unable to find any path to " + mining + ", blacklisting presumably unreachable closest instance..."); + logDirect("Unable to find any path to " + filter + ", blacklisting presumably unreachable closest instance..."); knownOreLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(blacklist::add); knownOreLocations.removeIf(blacklist::contains); } else { - logDirect("Unable to find any path to " + mining + ", canceling Mine"); + logDirect("Unable to find any path to " + filter + ", canceling mine"); cancel(); return null; } @@ -146,19 +150,19 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro @Override public void onLostControl() { - mine(0, (Block[]) null); + mine(0, (IBlockFilter) null); } @Override public String displayName0() { - return "Mine " + mining; + return "Mine " + filter; } private PathingCommand updateGoal() { boolean legit = Baritone.settings().legitMine.value; List locs = knownOreLocations; if (!locs.isEmpty()) { - List locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT, blacklist); + List locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), filter, ORE_LOCATIONS_COUNT, blacklist); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new)); knownOreLocations = locs2; @@ -194,16 +198,16 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } private void rescan(List already, CalculationContext context) { - if (mining == null) { + if (filter == null) { return; } if (Baritone.settings().legitMine.value) { return; } - List locs = searchWorld(context, mining, ORE_LOCATIONS_COUNT, already, blacklist); - locs.addAll(droppedItemsScan(mining, ctx.world())); + List locs = searchWorld(context, filter, ORE_LOCATIONS_COUNT, already, blacklist); + locs.addAll(droppedItemsScan(filter, ctx.world())); if (locs.isEmpty()) { - logDirect("No locations for " + mining + " known, cancelling"); + logDirect("No locations for " + filter + " known, cancelling"); cancel(); return; } @@ -215,11 +219,11 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (locs.contains(pos)) { return true; } - Block block = BlockStateInterface.getBlock(ctx, pos); - if (Baritone.settings().internalMiningAirException.value && block instanceof BlockAir) { + IBlockState state = BlockStateInterface.get(ctx, pos); + if (Baritone.settings().internalMiningAirException.value && state.getBlock() instanceof BlockAir) { return true; } - return mining.contains(block); + return filter.selected(state); } private Goal coalesce(BlockPos loc, List locs) { @@ -284,22 +288,18 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } - public static List droppedItemsScan(List mining, World world) { + public static List droppedItemsScan(IBlockFilter filter, World world) { if (!Baritone.settings().mineScanDroppedItems.value) { return Collections.emptyList(); } - Set searchingFor = new HashSet<>(); - for (Block block : mining) { - Item drop = block.getItemDropped(block.getDefaultState(), new Random(), 0); - Item ore = Item.getItemFromBlock(block); - searchingFor.add(drop); - searchingFor.add(ore); - } List ret = new ArrayList<>(); for (Entity entity : world.loadedEntityList) { if (entity instanceof EntityItem) { EntityItem ei = (EntityItem) entity; - if (searchingFor.contains(ei.getItem().getItem())) { + ItemStack stack = ei.getItem(); + Item item = stack.getItem(); + //noinspection deprecation + if (filter.selected(Block.getBlockFromItem(item).getStateFromMeta(stack.getItemDamage()))) { ret.add(new BlockPos(entity)); } } @@ -307,30 +307,16 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return ret; } - public static List searchWorld(CalculationContext ctx, List mining, int max, List alreadyKnown, List blacklist) { + public static List searchWorld(CalculationContext ctx, IBlockFilter filter, int max, List alreadyKnown, List blacklist) { List locs = new ArrayList<>(); - List uninteresting = new ArrayList<>(); - for (Block m : mining) { - if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(m)) { - // maxRegionDistanceSq 2 means adjacent directly or adjacent diagonally; nothing further than that - locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(BlockUtils.blockToString(m), Baritone.settings().maxCachedWorldScanCount.value, ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2)); - } else { - uninteresting.add(m); - } - } - locs = prune(ctx, locs, mining, max, blacklist); - if (locs.isEmpty() || (Baritone.settings().extendCacheOnThreshold.value && locs.size() < max)) { - uninteresting = mining; - } - if (!uninteresting.isEmpty()) { - locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), uninteresting, max, 10, 32)); // maxSearchRadius is NOT sq - } + locs = prune(ctx, locs, filter, max, blacklist); + locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), filter, max, 10, 32)); // maxSearchRadius is NOT sq locs.addAll(alreadyKnown); - return prune(ctx, locs, mining, max, blacklist); + return prune(ctx, locs, filter, max, blacklist); } private void addNearby() { - knownOreLocations.addAll(droppedItemsScan(mining, ctx.world())); + knownOreLocations.addAll(droppedItemsScan(filter, ctx.world())); BlockPos playerFeet = ctx.playerFeet(); BlockStateInterface bsi = new BlockStateInterface(ctx); int searchDist = 10; @@ -340,7 +326,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) { // crucial to only add blocks we can see because otherwise this // is an x-ray and it'll get caught - if (mining.contains(bsi.get0(x, y, z).getBlock())) { + if (filter.selected(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()) { knownOreLocations.add(pos); @@ -349,14 +335,14 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } } - knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, mining, ORE_LOCATIONS_COUNT, blacklist); + knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, filter, ORE_LOCATIONS_COUNT, blacklist); } - private static List prune(CalculationContext ctx, List locs2, List mining, int max, List blacklist) { - List dropped = droppedItemsScan(mining, ctx.world); + private static List prune(CalculationContext ctx, List locs2, IBlockFilter filter, int max, List blacklist) { + List dropped = droppedItemsScan(filter, ctx.world); dropped.removeIf(drop -> { for (BlockPos pos : locs2) { - if (pos.distanceSq(drop) <= 9 && mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) && MineProcess.plausibleToBreak(ctx, pos)) { // TODO maybe drop also has to be supported? no lava below? + if (pos.distanceSq(drop) <= 9 && filter.selected(ctx.get(pos.getX(), pos.getY(), pos.getZ())) && MineProcess.plausibleToBreak(ctx, pos)) { // TODO maybe drop also has to be supported? no lava below? return true; } } @@ -367,7 +353,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro .distinct() // remove any that are within loaded chunks that aren't actually what we want - .filter(pos -> !ctx.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ()) || mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos)) + .filter(pos -> !ctx.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ()) || filter.selected(ctx.get(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos)) // remove any that are implausible to mine (encased in bedrock, or touching lava) .filter(pos -> MineProcess.plausibleToBreak(ctx, pos)) @@ -394,22 +380,26 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro @Override public void mineByName(int quantity, String... blocks) { - mine(quantity, blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(BlockUtils::stringToBlockRequired).toArray(Block[]::new)); + mine(quantity, new CompositeBlockFilter( + Arrays.stream(Objects.requireNonNull(blocks)) + .map(BlockSelector::new) + .toArray(IBlockFilter[]::new) + )); } @Override - public void mine(int quantity, Block... blocks) { - this.mining = blocks == null || blocks.length == 0 ? null : Arrays.asList(blocks); - if (mining != null && !Baritone.settings().allowBreak.value) { + public void mine(int quantity, IBlockFilter filter) { + this.filter = filter; + if (filter != null && !Baritone.settings().allowBreak.value) { logDirect("Unable to mine when allowBreak is false!"); - mining = null; + filter = null; } this.desiredQuantity = quantity; this.knownOreLocations = new ArrayList<>(); this.blacklist = new ArrayList<>(); this.branchPoint = null; this.branchPointRunaway = null; - if (mining != null) { + if (filter != null) { rescan(new ArrayList<>(), new CalculationContext(baritone)); } } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index b0157247..cb5e7be0 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -185,12 +185,17 @@ public final class PathRenderer implements Helper { double d0 = mc.getRenderManager().viewerPosX; double d1 = mc.getRenderManager().viewerPosY; double d2 = mc.getRenderManager().viewerPosZ; - BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); + boolean renderPathAsFrickinThingy = !Baritone.settings().renderPathAsLine.value; + + BUFFER.begin(renderPathAsFrickinThingy ? GL_LINE_STRIP : GL_LINES, DefaultVertexFormats.POSITION); BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex(); BUFFER.pos(bp2x + 0.5D - d0, bp2y + 0.5D - d1, bp2z + 0.5D - d2).endVertex(); - BUFFER.pos(bp2x + 0.5D - d0, bp2y + 0.53D - d1, bp2z + 0.5D - d2).endVertex(); - BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.53D - d1, bp1z + 0.5D - d2).endVertex(); - BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex(); + + if (renderPathAsFrickinThingy) { + BUFFER.pos(bp2x + 0.5D - d0, bp2y + 0.53D - d1, bp2z + 0.5D - d2).endVertex(); + BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.53D - d1, bp1z + 0.5D - d2).endVertex(); + BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex(); + } } public static void drawManySelectionBoxes(Entity player, Collection positions, Color color) { @@ -334,6 +339,9 @@ public final class PathRenderer implements Helper { drawDankLitGoalBox(player, g, partialTicks, color); } return; + } else if (goal instanceof GoalInverted) { + drawDankLitGoalBox(player, ((GoalInverted) goal).origin, partialTicks, Baritone.settings().colorInvertedGoalBox.value); + return; } else if (goal instanceof GoalYLevel) { GoalYLevel goalpos = (GoalYLevel) goal; minX = player.posX - Baritone.settings().yLevelBoxSize.value - renderPosX; diff --git a/src/main/java/baritone/utils/accessor/ITabCompleter.java b/src/main/java/baritone/utils/accessor/ITabCompleter.java new file mode 100644 index 00000000..72733f27 --- /dev/null +++ b/src/main/java/baritone/utils/accessor/ITabCompleter.java @@ -0,0 +1,9 @@ +package baritone.utils.accessor; + +public interface ITabCompleter { + String getPrefix(); + + void setPrefix(String prefix); + + boolean onGuiChatSetCompletions(String[] newCompl); +} From 4354d09c2020d5a0d2357c8c9809b06dbd11f8f8 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 12:25:59 -0700 Subject: [PATCH 565/682] some efficiency fixes to filters + qol for leijurv --- .../baritone/api/utils/BlockListFilter.java | 4 +-- .../baritone/api/utils/BlockSelector.java | 5 ++-- .../api/utils/CompositeBlockFilter.java | 27 +++++++++---------- .../utils/command/BaritoneChatControl.java | 8 +++--- .../command/argument/CommandArgument.java | 2 +- .../utils/command/datatypes/BlockById.java | 4 +-- .../command/datatypes/EntityClassById.java | 4 +-- .../command/datatypes/ForBlockSelector.java | 2 +- .../command/datatypes/PlayerByUsername.java | 4 +-- .../command/datatypes/RelativeCoordinate.java | 4 +-- .../utils/command/datatypes/RelativeFile.java | 4 +-- .../utils/command/defaults/BuildCommand.java | 2 +- .../defaults/ExploreFilterCommand.java | 2 +- .../utils/command/defaults/FollowCommand.java | 8 +++--- .../utils/command/defaults/GoalCommand.java | 4 +-- .../utils/command/defaults/HelpCommand.java | 4 +-- .../utils/command/defaults/PathCommand.java | 2 +- .../utils/command/defaults/ProcCommand.java | 8 +++--- .../utils/command/defaults/SetCommand.java | 18 ++++++------- .../helpers/arguments/ArgConsumer.java | 26 +++++++++--------- .../launch/mixins/MixinChatTabCompleter.java | 17 ++++++++++++ .../baritone/launch/mixins/MixinGuiChat.java | 17 ++++++++++++ .../launch/mixins/MixinGuiScreen.java | 17 ++++++++++++ .../launch/mixins/MixinTabCompleter.java | 19 ++++++++++++- src/launch/resources/mixins.baritone.json | 10 +++---- 25 files changed, 145 insertions(+), 77 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockListFilter.java b/src/api/java/baritone/api/utils/BlockListFilter.java index 7168687d..6116f22b 100644 --- a/src/api/java/baritone/api/utils/BlockListFilter.java +++ b/src/api/java/baritone/api/utils/BlockListFilter.java @@ -22,12 +22,12 @@ public class BlockListFilter implements IBlockFilter { @Override public boolean selected(@Nonnull IBlockState blockstate) { - return false; + return blocks.contains(blockstate.getBlock()); } @Override public List blocks() { - return null; + return blocks; } @Override diff --git a/src/api/java/baritone/api/utils/BlockSelector.java b/src/api/java/baritone/api/utils/BlockSelector.java index c711d725..54f85ecd 100644 --- a/src/api/java/baritone/api/utils/BlockSelector.java +++ b/src/api/java/baritone/api/utils/BlockSelector.java @@ -17,6 +17,7 @@ import static java.util.Objects.isNull; public class BlockSelector implements IBlockFilter { private final Block block; private final IBlockState blockstate; + private final int damage; private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); public BlockSelector(@Nonnull String selector) { @@ -38,12 +39,12 @@ public class BlockSelector implements IBlockFilter { block = Block.REGISTRY.getObject(id); //noinspection deprecation blockstate = hasData ? block.getStateFromMeta(Integer.parseInt(matchResult.group(2))) : null; + damage = block.damageDropped(blockstate); } @Override public boolean selected(@Nonnull IBlockState blockstate) { - return blockstate.getBlock() == block && (isNull(this.blockstate) || - block.damageDropped(blockstate) == block.damageDropped(this.blockstate)); + return blockstate.getBlock() == block && (isNull(this.blockstate) || block.damageDropped(blockstate) == damage); } @Override diff --git a/src/api/java/baritone/api/utils/CompositeBlockFilter.java b/src/api/java/baritone/api/utils/CompositeBlockFilter.java index 39b52f21..d2297d3b 100644 --- a/src/api/java/baritone/api/utils/CompositeBlockFilter.java +++ b/src/api/java/baritone/api/utils/CompositeBlockFilter.java @@ -5,37 +5,36 @@ import net.minecraft.block.state.IBlockState; import javax.annotation.Nonnull; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; -import static java.util.Arrays.asList; - public class CompositeBlockFilter implements IBlockFilter { - List filters = new ArrayList<>(); - - public CompositeBlockFilter() { - } + private IBlockFilter[] filters; public CompositeBlockFilter(List filters) { - this.filters.addAll(filters); + this.filters = filters.toArray(new IBlockFilter[0]); } public CompositeBlockFilter(IBlockFilter... filters) { - this.filters.addAll(asList(filters)); + this.filters = filters; } @Override public boolean selected(@Nonnull IBlockState blockstate) { - return filters.stream() - .map(f -> f.selected(blockstate)) - .filter(Boolean::valueOf).findFirst() - .orElse(false); + for (IBlockFilter filter : filters) { + if (filter.selected(blockstate)) { + return true; + } + } + + return false; } @Override public List blocks() { - return filters.stream() + return Arrays.stream(filters) .map(IBlockFilter::blocks) .flatMap(Collection::stream) .collect(Collectors.toCollection(ArrayList::new)); @@ -45,7 +44,7 @@ public class CompositeBlockFilter implements IBlockFilter { public String toString() { return String.format( "CompositeBlockFilter{%s}", - String.join(",", filters.stream().map(Object::toString).toArray(String[]::new)) + String.join(",", Arrays.stream(filters).map(Object::toString).toArray(String[]::new)) ); } } diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index 3de8a7eb..753f8249 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -151,7 +151,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (setting.getName().equalsIgnoreCase(pair.first())) { logRanCommand(msg); - CommandManager.execute(String.format("set %s %s", setting.getName(), argc.getS())); + CommandManager.execute(String.format("set %s %s", setting.getName(), argc.getString())); return true; } } @@ -203,11 +203,11 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { return new TabCompleteHelper() .addCommands() .addSettings() - .filterPrefix(argc.getS()) + .filterPrefix(argc.getString()) .stream(); } - Settings.Setting setting = settings.byLowerName.get(argc.getS().toLowerCase(Locale.US)); + Settings.Setting setting = settings.byLowerName.get(argc.getString().toLowerCase(Locale.US)); if (nonNull(setting)) { if (setting.getValueClass() == Boolean.class) { @@ -219,7 +219,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { helper.append(of("false", "true")); } - return helper.filterPrefix(argc.getS()).stream(); + return helper.filterPrefix(argc.getString()).stream(); } else { return of(SettingsUtil.settingValueToString(setting)); } diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index 5b507fcd..8309e696 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -39,7 +39,7 @@ public class CommandArgument { this.rawRest = rawRest; } - public > E getE(Class enumClass) { + public > E getEnum(Class enumClass) { //noinspection OptionalGetWithoutIsPresent return Arrays.stream(enumClass.getEnumConstants()) .filter(e -> e.name().equalsIgnoreCase(value)) diff --git a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java index c8cfe274..469e9caf 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java @@ -16,7 +16,7 @@ public class BlockById implements IDatatypeFor { } public BlockById(ArgConsumer consumer) { - ResourceLocation id = new ResourceLocation(consumer.getS()); + ResourceLocation id = new ResourceLocation(consumer.getString()); if ((block = Block.REGISTRY.getObject(id)) == Blocks.AIR) { throw new RuntimeException("no block found by that id"); @@ -36,7 +36,7 @@ public class BlockById implements IDatatypeFor { .stream() .map(Object::toString) ) - .filterPrefixNamespaced(consumer.getS()) + .filterPrefixNamespaced(consumer.getString()) .sortAlphabetically() .stream(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java index eb841724..dc9d0bae 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java @@ -18,7 +18,7 @@ public class EntityClassById implements IDatatypeFor> { } public EntityClassById(ArgConsumer consumer) { - ResourceLocation id = new ResourceLocation(consumer.getS()); + ResourceLocation id = new ResourceLocation(consumer.getString()); if (isNull(entity = EntityList.REGISTRY.getObject(id))) { throw new RuntimeException("no entity found by that id"); @@ -38,7 +38,7 @@ public class EntityClassById implements IDatatypeFor> { .stream() .map(Object::toString) ) - .filterPrefixNamespaced(consumer.getS()) + .filterPrefixNamespaced(consumer.getString()) .sortAlphabetically() .stream(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java b/src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java index 7b7dbf72..eb4047dc 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java @@ -13,7 +13,7 @@ public class ForBlockSelector implements IDatatypeFor { } public ForBlockSelector(ArgConsumer consumer) { - selector = new BlockSelector(consumer.getS()); + selector = new BlockSelector(consumer.getString()); } @Override diff --git a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java index 07e765e5..1d9a48dd 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java +++ b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java @@ -20,7 +20,7 @@ public class PlayerByUsername implements IDatatypeFor { } public PlayerByUsername(ArgConsumer consumer) { - String username = consumer.getS(); + String username = consumer.getString(); if (isNull( player = players @@ -46,7 +46,7 @@ public class PlayerByUsername implements IDatatypeFor { .stream() .map(EntityPlayer::getName) ) - .filterPrefix(consumer.getS()) + .filterPrefix(consumer.getString()) .sortAlphabetically() .stream(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java index 9516fea7..3213a033 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java @@ -23,7 +23,7 @@ public class RelativeCoordinate implements IDatatypePost { throw new RuntimeException("relative coordinate requires an argument"); } - Matcher matcher = PATTERN.matcher(consumer.getS()); + Matcher matcher = PATTERN.matcher(consumer.getString()); if (!matcher.matches()) { throw new RuntimeException("pattern doesn't match"); @@ -48,7 +48,7 @@ public class RelativeCoordinate implements IDatatypePost { @Override public Stream tabComplete(ArgConsumer consumer) { - if (!consumer.has(2) && consumer.getS().matches("^(~|$)")) { + if (!consumer.has(2) && consumer.getString().matches("^(~|$)")) { return Stream.of("~"); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index 58013f4f..41b6ff55 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -20,7 +20,7 @@ public class RelativeFile implements IDatatypePost { public RelativeFile(ArgConsumer consumer) { try { - path = FileSystems.getDefault().getPath(consumer.getS()); + path = FileSystems.getDefault().getPath(consumer.getString()); } catch (InvalidPathException e) { throw new RuntimeException("invalid path"); } @@ -32,7 +32,7 @@ public class RelativeFile implements IDatatypePost { } public static Stream tabComplete(ArgConsumer consumer, File base) { - String currentPathStringThing = consumer.getS(); + String currentPathStringThing = consumer.getString(); Path currentPath = FileSystems.getDefault().getPath(currentPathStringThing); Path basePath = currentPath.isAbsolute() ? currentPath.getRoot() : base.toPath(); boolean useParent = !currentPathStringThing.isEmpty() && !currentPathStringThing.endsWith(File.separator); diff --git a/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java b/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java index ab6b3371..e7fd614e 100644 --- a/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java @@ -36,7 +36,7 @@ public class BuildCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { - String filename = String.format("%s.schematic", args.getS()); + String filename = String.format("%s.schematic", args.getString()); BetterBlockPos origin = ctx.playerFeet(); BetterBlockPos buildOrigin; diff --git a/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java b/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java index 2bd41ae4..6b257012 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java @@ -44,7 +44,7 @@ public class ExploreFilterCommand extends Command { boolean invert = false; if (args.has()) { - if (args.getS().equalsIgnoreCase("invert")) { + if (args.getString().equalsIgnoreCase("invert")) { invert = true; } else { throw new CommandInvalidTypeException(args.consumed(), "either \"invert\" or nothing"); diff --git a/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java b/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java index a2ae8951..201346e6 100644 --- a/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java @@ -57,13 +57,13 @@ public class FollowCommand extends Command { List> classes = new ArrayList<>(); if (args.hasExactlyOne()) { - baritone.getFollowProcess().follow((group = args.getE(FollowGroup.class)).filter); + baritone.getFollowProcess().follow((group = args.getEnum(FollowGroup.class)).filter); list = null; } else { args.requireMin(2); group = null; - list = args.getE(FollowList.class); + list = args.getEnum(FollowList.class); while (args.has()) { //noinspection unchecked @@ -109,13 +109,13 @@ public class FollowCommand extends Command { return new TabCompleteHelper() .append(FollowGroup.class) .append(FollowList.class) - .filterPrefix(args.getS()) + .filterPrefix(args.getString()) .stream(); } else { Class followType; try { - followType = args.getE(FollowList.class).datatype; + followType = args.getEnum(FollowList.class).datatype; } catch (NullPointerException e) { return Stream.empty(); } diff --git a/src/api/java/baritone/api/utils/command/defaults/GoalCommand.java b/src/api/java/baritone/api/utils/command/defaults/GoalCommand.java index cb6a2fbf..692d6422 100644 --- a/src/api/java/baritone/api/utils/command/defaults/GoalCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/GoalCommand.java @@ -43,7 +43,7 @@ public class GoalCommand extends Command { protected void executed(String label, ArgConsumer args, Settings settings) { ICustomGoalProcess goalProcess = baritone.getCustomGoalProcess(); - if (args.has() && asList("reset", "clear", "none").contains(args.peekS())) { + if (args.has() && asList("reset", "clear", "none").contains(args.peekString())) { args.requireMax(1); if (nonNull(goalProcess.getGoal())) { @@ -83,7 +83,7 @@ public class GoalCommand extends Command { } } - return helper.filterPrefix(args.getS()).stream(); + return helper.filterPrefix(args.getString()).stream(); } @Override diff --git a/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java b/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java index e96bf5eb..efe0d0e2 100644 --- a/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java @@ -89,7 +89,7 @@ public class HelpCommand extends Command { FORCE_COMMAND_PREFIX + "help %d" ); } else { - String commandName = args.getS().toLowerCase(); + String commandName = args.getString().toLowerCase(); Command command = getCommand(commandName); if (isNull(command)) { @@ -112,7 +112,7 @@ public class HelpCommand extends Command { @Override protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { if (args.hasExactlyOne()) { - return new TabCompleteHelper().addCommands().filterPrefix(args.getS()).stream(); + return new TabCompleteHelper().addCommands().filterPrefix(args.getString()).stream(); } return Stream.empty(); diff --git a/src/api/java/baritone/api/utils/command/defaults/PathCommand.java b/src/api/java/baritone/api/utils/command/defaults/PathCommand.java index 2eafe55c..c184db7f 100644 --- a/src/api/java/baritone/api/utils/command/defaults/PathCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/PathCommand.java @@ -68,7 +68,7 @@ public class PathCommand extends Command { if (!args.has(2)) { return new TabCompleteHelper() .append("~") - .filterPrefix(args.getS()) + .filterPrefix(args.getString()) .stream(); } } diff --git a/src/api/java/baritone/api/utils/command/defaults/ProcCommand.java b/src/api/java/baritone/api/utils/command/defaults/ProcCommand.java index 68dbc339..fdbb0a40 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ProcCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/ProcCommand.java @@ -49,13 +49,13 @@ public class ProcCommand extends Command { logDirect(String.format( "Class: %s\n" + - "Priority: %s\n" + - "Temporary: %s\n" + + "Priority: %f\n" + + "Temporary: %b\n" + "Display name: %s\n" + "Last command: %s", process.getClass().getTypeName(), - Double.toString(process.priority()), - Boolean.toString(process.isTemporary()), + process.priority(), + process.isTemporary(), process.displayName(), pathingControlManager .mostRecentCommand() diff --git a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java b/src/api/java/baritone/api/utils/command/defaults/SetCommand.java index e9541131..6a23c2a4 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SetCommand.java @@ -51,12 +51,12 @@ public class SetCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { - String arg = args.has() ? args.getS().toLowerCase(Locale.US) : "list"; + String arg = args.has() ? args.getString().toLowerCase(Locale.US) : "list"; boolean viewModified = asList("m", "mod", "modified").contains(arg); boolean viewAll = asList("all", "l", "list").contains(arg); boolean paginate = viewModified | viewAll; if (paginate) { - String search = args.has() && args.peekAsOrNull(Integer.class) == null ? args.getS() : ""; + String search = args.has() && args.peekAsOrNull(Integer.class) == null ? args.getString() : ""; args.requireMax(1); List toPaginate = @@ -122,7 +122,7 @@ public class SetCommand extends Command { logDirect("Please specify 'all' as an argument to reset to confirm you'd really like to do this"); logDirect("ALL settings will be reset. Use the 'set modified' or 'modified' commands to see what will be reset."); logDirect("Specify a setting name instead of 'all' to only reset one setting"); - } else if (args.peekS().equalsIgnoreCase("all")) { + } else if (args.peekString().equalsIgnoreCase("all")) { SettingsUtil.modifiedSettings(settings).forEach(Settings.Setting::reset); logDirect("All settings have been reset to their default values"); @@ -134,7 +134,7 @@ public class SetCommand extends Command { args.requireMin(1); } - String settingName = doingSomething ? args.getS() : arg; + String settingName = doingSomething ? args.getString() : arg; Settings.Setting setting = settings.allSettings.stream() .filter(s -> s.getName().equalsIgnoreCase(settingName)) .findFirst() @@ -166,7 +166,7 @@ public class SetCommand extends Command { Boolean.toString((Boolean) setting.value) )); } else { - String newValue = args.getS(); + String newValue = args.getString(); try { SettingsUtil.parseAndApply(settings, arg, newValue); @@ -210,19 +210,19 @@ public class SetCommand extends Command { @Override protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { if (args.has()) { - String arg = args.getS(); + String arg = args.getString(); if (args.hasExactlyOne()) { if (arg.equalsIgnoreCase("reset")) { return new TabCompleteHelper() .addModifiedSettings() .prepend("all") - .filterPrefix(args.getS()) + .filterPrefix(args.getString()) .stream(); } else if (arg.equalsIgnoreCase("toggle")) { return new TabCompleteHelper() .addToggleableSettings() - .filterPrefix(args.getS()) + .filterPrefix(args.getString()) .stream(); } @@ -238,7 +238,7 @@ public class SetCommand extends Command { helper.append(of("false", "true")); } - return helper.filterPrefix(args.getS()).stream(); + return helper.filterPrefix(args.getString()).stream(); } else { return Stream.of(settingValueToString(setting)); } diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index 6c9ef884..8f6b91f0 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -84,21 +84,21 @@ public class ArgConsumer { return peek().is(type); } - public String peekS(int index) { + public String peekString(int index) { return peek(index).value; } - public String peekS() { - return peekS(0); + public String peekString() { + return peekString(0); } - public > E peekE(Class enumClass) { - return peek().getE(enumClass); + public > E peekEnum(Class enumClass) { + return peek().getEnum(enumClass); } - public > E peekEOrNull(Class enumClass) { + public > E peekEnumOrNull(Class enumClass) { try { - return peekE(enumClass); + return peekEnum(enumClass); } catch (NoSuchElementException e) { return null; } @@ -171,22 +171,22 @@ public class ArgConsumer { return arg; } - public String getS() { + public String getString() { return get().value; } - public > E getE(Class enumClass) { + public > E getEnum(Class enumClass) { try { - return get().getE(enumClass); + return get().getEnum(enumClass); } catch (NoSuchElementException e) { throw new CommandInvalidTypeException(consumed(), enumClass.getSimpleName()); } } - public > E getEOrNull(Class enumClass) { + public > E getEnumOrNull(Class enumClass) { try { - peekE(enumClass); - return getE(enumClass); + peekEnum(enumClass); + return getEnum(enumClass); } catch (CommandInvalidTypeException e) { return null; } diff --git a/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java index 8aabfd69..39fbb19d 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java +++ b/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java @@ -1,3 +1,20 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + package baritone.launch.mixins; import net.minecraft.client.gui.GuiChat; diff --git a/src/launch/java/baritone/launch/mixins/MixinGuiChat.java b/src/launch/java/baritone/launch/mixins/MixinGuiChat.java index 310bfd7c..9af0a3e9 100644 --- a/src/launch/java/baritone/launch/mixins/MixinGuiChat.java +++ b/src/launch/java/baritone/launch/mixins/MixinGuiChat.java @@ -1,3 +1,20 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + package baritone.launch.mixins; import baritone.utils.accessor.ITabCompleter; diff --git a/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java b/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java index 0731df1f..35fcc38b 100644 --- a/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java +++ b/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java @@ -1,3 +1,20 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + package baritone.launch.mixins; import baritone.api.utils.command.Lol; diff --git a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java index 4e36491b..6046ed21 100644 --- a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java +++ b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java @@ -1,3 +1,20 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + package baritone.launch.mixins; import baritone.api.BaritoneAPI; @@ -86,7 +103,7 @@ public abstract class MixinTabCompleter implements ITabCompleter { @Override public boolean onGuiChatSetCompletions(String[] newCompl) { - IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(Minecraft.getMinecraft().player); + IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone(); if (isNull(baritone)) { return false; diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index 66ef181d..1d1c356b 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -10,6 +10,7 @@ "client": [ "MixinAnvilChunkLoader", "MixinBlockPos", + "MixinChatTabCompleter", "MixinChunkProviderClient", "MixinChunkProviderServer", "MixinChunkRenderContainer", @@ -17,16 +18,15 @@ "MixinEntityLivingBase", "MixinEntityPlayerSP", "MixinEntityRenderer", + "MixinGuiChat", + "MixinGuiScreen", "MixinMinecraft", "MixinNetHandlerPlayClient", "MixinNetworkManager", "MixinRenderChunk", "MixinRenderList", - "MixinVboRenderList", - "MixinWorldClient", "MixinTabCompleter", - "MixinGuiChat", - "MixinChatTabCompleter", - "MixinGuiScreen" + "MixinVboRenderList", + "MixinWorldClient" ] } \ No newline at end of file From d687e1203aebd16885d3e21c4244d8c0f8f59676 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 15:38:15 -0700 Subject: [PATCH 566/682] BlockOptionalMeta --- .../baritone/api/cache/IWorldScanner.java | 14 ++- .../baritone/api/process/IMineProcess.java | 38 ++++++-- .../baritone/api/utils/BlockListFilter.java | 46 --------- .../baritone/api/utils/BlockOptionalMeta.java | 95 +++++++++++++++++++ .../api/utils/BlockOptionalMetaLookup.java | 78 +++++++++++++++ .../baritone/api/utils/BlockSelector.java | 64 ------------- .../api/utils/CompositeBlockFilter.java | 50 ---------- .../java/baritone/api/utils/IBlockFilter.java | 22 ----- ...elector.java => ForBlockOptionalMeta.java} | 14 +-- .../utils/command/defaults/MineCommand.java | 15 ++- .../command/defaults/PauseResumeCommands.java | 1 + .../baritone/launch/mixins/MixinBitArray.java | 62 ++++++++++++ .../mixins/MixinBlockStateContainer.java | 42 ++++++++ src/launch/resources/mixins.baritone.json | 2 + .../java/baritone/cache/WorldScanner.java | 23 +++-- .../java/baritone/process/FarmProcess.java | 3 +- .../baritone/process/GetToBlockProcess.java | 4 +- .../java/baritone/process/MineProcess.java | 72 +++++++------- .../utils/accessor/IBlockStateContainer.java | 13 +++ 19 files changed, 399 insertions(+), 259 deletions(-) delete mode 100644 src/api/java/baritone/api/utils/BlockListFilter.java create mode 100644 src/api/java/baritone/api/utils/BlockOptionalMeta.java create mode 100644 src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java delete mode 100644 src/api/java/baritone/api/utils/BlockSelector.java delete mode 100644 src/api/java/baritone/api/utils/CompositeBlockFilter.java delete mode 100644 src/api/java/baritone/api/utils/IBlockFilter.java rename src/api/java/baritone/api/utils/command/datatypes/{ForBlockSelector.java => ForBlockOptionalMeta.java} (51%) create mode 100644 src/launch/java/baritone/launch/mixins/MixinBitArray.java create mode 100644 src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java create mode 100644 src/main/java/baritone/utils/accessor/IBlockStateContainer.java diff --git a/src/api/java/baritone/api/cache/IWorldScanner.java b/src/api/java/baritone/api/cache/IWorldScanner.java index 6f4349ac..009268fb 100644 --- a/src/api/java/baritone/api/cache/IWorldScanner.java +++ b/src/api/java/baritone/api/cache/IWorldScanner.java @@ -17,7 +17,7 @@ package baritone.api.cache; -import baritone.api.utils.IBlockFilter; +import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.IPlayerContext; import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; @@ -36,26 +36,30 @@ public interface IWorldScanner { * * @param ctx The {@link IPlayerContext} containing player and world info that the * scan is based upon - * @param filter The block filter to scan for + * @param filter The blocks to scan for * @param max The maximum number of blocks to scan before cutoff * @param yLevelThreshold If a block is found within this Y level, the current result will be * returned, if the value is negative, then this condition doesn't apply. * @param maxSearchRadius The maximum chunk search radius * @return The matching block positions */ - List scanChunkRadius(IPlayerContext ctx, IBlockFilter filter, int max, int yLevelThreshold, int maxSearchRadius); + List scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLookup filter, int max, int yLevelThreshold, int maxSearchRadius); + + default List scanChunkRadius(IPlayerContext ctx, List filter, int max, int yLevelThreshold, int maxSearchRadius) { + return scanChunkRadius(ctx, new BlockOptionalMetaLookup(filter.toArray(new Block[0])), max, yLevelThreshold, maxSearchRadius); + } /** * Scans a single chunk for the specified blocks. * * @param ctx The {@link IPlayerContext} containing player and world info that the * scan is based upon - * @param filter The block filter to scan for + * @param filter The blocks to scan for * @param pos The position of the target chunk * @param max The maximum number of blocks to scan before cutoff * @param yLevelThreshold If a block is found within this Y level, the current result will be * returned, if the value is negative, then this condition doesn't apply. * @return The matching block positions */ - List scanChunk(IPlayerContext ctx, IBlockFilter filter, ChunkPos pos, int max, int yLevelThreshold); + List scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold); } diff --git a/src/api/java/baritone/api/process/IMineProcess.java b/src/api/java/baritone/api/process/IMineProcess.java index 4885e32f..aa01aa5a 100644 --- a/src/api/java/baritone/api/process/IMineProcess.java +++ b/src/api/java/baritone/api/process/IMineProcess.java @@ -17,10 +17,12 @@ package baritone.api.process; -import baritone.api.utils.BlockListFilter; -import baritone.api.utils.IBlockFilter; +import baritone.api.utils.BlockOptionalMeta; +import baritone.api.utils.BlockOptionalMetaLookup; import net.minecraft.block.Block; +import java.util.Arrays; + /** * @author Brady * @since 9/23/2018 @@ -42,16 +44,16 @@ public interface IMineProcess extends IBaritoneProcess { * are mined. This is based on the first target block to mine. * * @param quantity The number of items to get from blocks mined - * @param filter The filter to run blocks through + * @param filter The blocks to mine */ - void mine(int quantity, IBlockFilter filter); + void mine(int quantity, BlockOptionalMetaLookup filter); /** * Begin to search for and mine the specified blocks. * - * @param filter The filter to run blocks through + * @param filter The blocks to mine */ - default void mine(IBlockFilter filter) { + default void mine(BlockOptionalMetaLookup filter) { mine(0, filter); } @@ -64,6 +66,24 @@ public interface IMineProcess extends IBaritoneProcess { mineByName(0, blocks); } + /** + * Begin to search for and mine the specified blocks. + * + * @param boms The blocks to mine + */ + default void mine(int quantity, BlockOptionalMeta... boms) { + mine(quantity, new BlockOptionalMetaLookup(boms)); + } + + /** + * Begin to search for and mine the specified blocks. + * + * @param boms The blocks to mine + */ + default void mine(BlockOptionalMeta... boms) { + mine(0, boms); + } + /** * Begin to search for and mine the specified blocks. * @@ -71,7 +91,11 @@ public interface IMineProcess extends IBaritoneProcess { * @param blocks The blocks to mine */ default void mine(int quantity, Block... blocks) { - mine(quantity, new BlockListFilter(blocks)); + mine(quantity, new BlockOptionalMetaLookup( + Arrays.stream(blocks) + .map(BlockOptionalMeta::new) + .toArray(BlockOptionalMeta[]::new) + )); } /** diff --git a/src/api/java/baritone/api/utils/BlockListFilter.java b/src/api/java/baritone/api/utils/BlockListFilter.java deleted file mode 100644 index 6116f22b..00000000 --- a/src/api/java/baritone/api/utils/BlockListFilter.java +++ /dev/null @@ -1,46 +0,0 @@ -package baritone.api.utils; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.ResourceLocation; - -import javax.annotation.Nonnull; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class BlockListFilter implements IBlockFilter { - private final List blocks = new ArrayList<>(); - - public BlockListFilter(List blocks) { - this.blocks.addAll(blocks); - } - - public BlockListFilter(Block... blocks) { - this.blocks.addAll(Arrays.asList(blocks)); - } - - @Override - public boolean selected(@Nonnull IBlockState blockstate) { - return blocks.contains(blockstate.getBlock()); - } - - @Override - public List blocks() { - return blocks; - } - - @Override - public String toString() { - return String.format( - "BlockListFilter{%s}", - String.join( - ",", - blocks.stream() - .map(Block.REGISTRY::getNameForObject) - .map(ResourceLocation::toString) - .toArray(String[]::new) - ) - ); - } -} diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java new file mode 100644 index 00000000..b77bf541 --- /dev/null +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -0,0 +1,95 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.regex.MatchResult; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static java.util.Objects.isNull; + +public final class BlockOptionalMeta { + private final Block block; + private final int meta; + private final boolean noMeta; + private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); + + public BlockOptionalMeta(@Nonnull Block block, @Nullable Integer meta) { + this.block = block; + this.noMeta = isNull(meta); + this.meta = noMeta ? 0 : meta; + } + + public BlockOptionalMeta(@Nonnull Block block) { + this(block, null); + } + + public BlockOptionalMeta(@Nonnull String selector) { + Matcher matcher = pattern.matcher(selector); + + if (!matcher.find()) { + throw new IllegalArgumentException("invalid block selector"); + } + + MatchResult matchResult = matcher.toMatchResult(); + noMeta = matchResult.groupCount() < 2; + + ResourceLocation id = new ResourceLocation(matchResult.group(1)); + + if (!Block.REGISTRY.containsKey(id)) { + throw new IllegalArgumentException("Invalid block ID"); + } + + block = Block.REGISTRY.getObject(id); + meta = noMeta ? 0 : Integer.parseInt(matchResult.group(2)); + } + + public Block getBlock() { + return block; + } + + public Integer getMeta() { + return meta; + } + + public boolean matches(@Nonnull Block block, int meta) { + // & instead of && is intentional + return block == this.block & (noMeta || meta == this.meta); + } + + public boolean matches(@Nonnull IBlockState blockstate) { + return matches(blockstate.getBlock(), block.damageDropped(blockstate)); + } + + @Override + public String toString() { + return String.format("BlockOptionalMeta{block=%s,meta=%s}", block, meta); + } + + public static IBlockState blockStateFromStack(ItemStack stack) { + //noinspection deprecation + return Block.getBlockFromItem(stack.getItem()).getStateFromMeta(stack.getMetadata()); + } +} diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java new file mode 100644 index 00000000..eafe49e1 --- /dev/null +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -0,0 +1,78 @@ +package baritone.api.utils; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import org.apache.commons.lang3.ArrayUtils; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class BlockOptionalMetaLookup { + private final Map lookup = new HashMap<>(); + + public BlockOptionalMetaLookup() { + } + + public BlockOptionalMetaLookup(BlockOptionalMeta... boms) { + put(boms); + } + + public BlockOptionalMetaLookup(Block... blocks) { + put(blocks); + } + + public BlockOptionalMetaLookup(List blocks) { + put(blocks); + } + + public void put(BlockOptionalMeta bom) { + final int[] metaArr = new int[] {bom.getMeta()}; + lookup.compute(bom.getBlock(), (__, arr) -> arr == null ? metaArr : ArrayUtils.addAll(arr, metaArr)); + } + + public void put(BlockOptionalMeta... boms) { + for (BlockOptionalMeta bom : boms) { + put(bom); + } + } + + public void put(Block... blocks) { + for (Block block : blocks) { + put(new BlockOptionalMeta(block)); + } + } + + public void put(List blocks) { + for (Block block : blocks) { + put(new BlockOptionalMeta(block)); + } + } + + public boolean has(Block block) { + return lookup.containsKey(block); + } + + public boolean has(IBlockState state) { + Block block = state.getBlock(); + int[] arr = lookup.get(block); + + if (arr == null) { + return false; + } + + int meta = block.damageDropped(state); + for (int value : arr) { + if (value == meta) { + return true; + } + } + + return false; + } + + public Set blocks() { + return lookup.keySet(); + } +} diff --git a/src/api/java/baritone/api/utils/BlockSelector.java b/src/api/java/baritone/api/utils/BlockSelector.java deleted file mode 100644 index 54f85ecd..00000000 --- a/src/api/java/baritone/api/utils/BlockSelector.java +++ /dev/null @@ -1,64 +0,0 @@ -package baritone.api.utils; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - -import javax.annotation.Nonnull; -import java.util.Collections; -import java.util.List; -import java.util.regex.MatchResult; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static java.util.Objects.isNull; - -public class BlockSelector implements IBlockFilter { - private final Block block; - private final IBlockState blockstate; - private final int damage; - private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); - - public BlockSelector(@Nonnull String selector) { - Matcher matcher = pattern.matcher(selector); - - if (!matcher.find()) { - throw new RuntimeException("invalid block selector"); - } - - MatchResult matchResult = matcher.toMatchResult(); - boolean hasData = matchResult.groupCount() > 1; - - ResourceLocation id = new ResourceLocation(matchResult.group(1)); - - if (!Block.REGISTRY.containsKey(id)) { - throw new IllegalArgumentException("Invalid block ID"); - } - - block = Block.REGISTRY.getObject(id); - //noinspection deprecation - blockstate = hasData ? block.getStateFromMeta(Integer.parseInt(matchResult.group(2))) : null; - damage = block.damageDropped(blockstate); - } - - @Override - public boolean selected(@Nonnull IBlockState blockstate) { - return blockstate.getBlock() == block && (isNull(this.blockstate) || block.damageDropped(blockstate) == damage); - } - - @Override - public List blocks() { - return Collections.singletonList(block); - } - - @Override - public String toString() { - return String.format("BlockSelector{block=%s,blockstate=%s}", block, blockstate); - } - - public static IBlockState stateFromItem(ItemStack stack) { - //noinspection deprecation - return Block.getBlockFromItem(stack.getItem()).getStateFromMeta(stack.getMetadata()); - } -} diff --git a/src/api/java/baritone/api/utils/CompositeBlockFilter.java b/src/api/java/baritone/api/utils/CompositeBlockFilter.java deleted file mode 100644 index d2297d3b..00000000 --- a/src/api/java/baritone/api/utils/CompositeBlockFilter.java +++ /dev/null @@ -1,50 +0,0 @@ -package baritone.api.utils; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; - -import javax.annotation.Nonnull; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -public class CompositeBlockFilter implements IBlockFilter { - private IBlockFilter[] filters; - - public CompositeBlockFilter(List filters) { - this.filters = filters.toArray(new IBlockFilter[0]); - } - - public CompositeBlockFilter(IBlockFilter... filters) { - this.filters = filters; - } - - @Override - public boolean selected(@Nonnull IBlockState blockstate) { - for (IBlockFilter filter : filters) { - if (filter.selected(blockstate)) { - return true; - } - } - - return false; - } - - @Override - public List blocks() { - return Arrays.stream(filters) - .map(IBlockFilter::blocks) - .flatMap(Collection::stream) - .collect(Collectors.toCollection(ArrayList::new)); - } - - @Override - public String toString() { - return String.format( - "CompositeBlockFilter{%s}", - String.join(",", Arrays.stream(filters).map(Object::toString).toArray(String[]::new)) - ); - } -} diff --git a/src/api/java/baritone/api/utils/IBlockFilter.java b/src/api/java/baritone/api/utils/IBlockFilter.java deleted file mode 100644 index 2ad44823..00000000 --- a/src/api/java/baritone/api/utils/IBlockFilter.java +++ /dev/null @@ -1,22 +0,0 @@ -package baritone.api.utils; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; - -import javax.annotation.Nonnull; -import java.util.List; - -public interface IBlockFilter { - /** - * @param blockstate The blockstate of the block to test. - * @return If that blockstate passes this filter. - */ - boolean selected(@Nonnull IBlockState blockstate); - - /** - * @return A possibly incomplete list of blocks this filter selects. Not all states of each block may be selected, - * and this may not contain all selected blocks, but every block on this list is guaranteed to have a selected - * state. - */ - List blocks(); -} diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java b/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java similarity index 51% rename from src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java rename to src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java index eb4047dc..7226d0cb 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForBlockSelector.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java @@ -1,23 +1,23 @@ package baritone.api.utils.command.datatypes; -import baritone.api.utils.BlockSelector; +import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; -public class ForBlockSelector implements IDatatypeFor { - public final BlockSelector selector; +public class ForBlockOptionalMeta implements IDatatypeFor { + public final BlockOptionalMeta selector; - public ForBlockSelector() { + public ForBlockOptionalMeta() { selector = null; } - public ForBlockSelector(ArgConsumer consumer) { - selector = new BlockSelector(consumer.getString()); + public ForBlockOptionalMeta(ArgConsumer consumer) { + selector = new BlockOptionalMeta(consumer.getString()); } @Override - public BlockSelector get() { + public BlockOptionalMeta get() { return selector; } diff --git a/src/api/java/baritone/api/utils/command/defaults/MineCommand.java b/src/api/java/baritone/api/utils/command/defaults/MineCommand.java index ec87dd75..1cd869d8 100644 --- a/src/api/java/baritone/api/utils/command/defaults/MineCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/MineCommand.java @@ -18,12 +18,10 @@ package baritone.api.utils.command.defaults; import baritone.api.Settings; -import baritone.api.utils.BlockSelector; -import baritone.api.utils.CompositeBlockFilter; -import baritone.api.utils.IBlockFilter; +import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.BlockById; -import baritone.api.utils.command.datatypes.ForBlockSelector; +import baritone.api.utils.command.datatypes.ForBlockOptionalMeta; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.ArrayList; @@ -41,15 +39,14 @@ public class MineCommand extends Command { protected void executed(String label, ArgConsumer args, Settings settings) { int quantity = args.getAsOrDefault(Integer.class, 0); args.requireMin(1); - List selectors = new ArrayList<>(); + List boms = new ArrayList<>(); while (args.has()) { - selectors.add(args.getDatatypeFor(ForBlockSelector.class)); + boms.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); } - IBlockFilter filter = new CompositeBlockFilter(selectors); - baritone.getMineProcess().mine(quantity, filter); - logDirect(String.format("Mining %s", filter.toString())); + baritone.getMineProcess().mine(quantity, boms.toArray(new BlockOptionalMeta[0])); + logDirect(String.format("Mining %s", boms.toString())); } @Override diff --git a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java b/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java index d7746623..b0d2e1b5 100644 --- a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java +++ b/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java @@ -28,6 +28,7 @@ public class PauseResumeCommands { public static Command pausedCommand; static { + // array for mutability, non-field so reflection can't touch it final boolean[] paused = {false}; BaritoneAPI.getProvider().getPrimaryBaritone().getPathingControlManager().registerProcess( diff --git a/src/launch/java/baritone/launch/mixins/MixinBitArray.java b/src/launch/java/baritone/launch/mixins/MixinBitArray.java new file mode 100644 index 00000000..54ead39a --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinBitArray.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.launch.mixins; + +import net.minecraft.util.BitArray; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(BitArray.class) +public abstract class MixinBitArray { + @Shadow + @Final + private long[] longArray; + + @Shadow + @Final + private int bitsPerEntry; + + @Shadow + @Final + private long maxEntryValue; + + /** + * why did mojang divide by 64 instead of shifting right by 6 (2^6=64)? + * why did mojang modulo by 64 instead of ANDing with 63? + * also removed validation check + * + * @author LoganDark + */ + @Overwrite + public int getAt(int index) { + final int b = bitsPerEntry; + final int i = index * b; + final int j = i >> 6; + final int l = i & 63; + final int k = ((index + 1) * b - 1) >> 6; + + if (j == k) { + return (int) (this.longArray[j] >>> l & maxEntryValue); + } else { + int i1 = 64 - l; + return (int) ((this.longArray[j] >>> l | longArray[k] << i1) & maxEntryValue); + } + } +} diff --git a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java new file mode 100644 index 00000000..b419952d --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java @@ -0,0 +1,42 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import baritone.utils.accessor.IBlockStateContainer; +import net.minecraft.block.state.IBlockState; +import net.minecraft.util.BitArray; +import net.minecraft.world.chunk.BlockStateContainer; +import net.minecraft.world.chunk.IBlockStatePalette; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(BlockStateContainer.class) +public abstract class MixinBlockStateContainer implements IBlockStateContainer { + @Accessor + public abstract IBlockStatePalette getPalette(); + + @Accessor + public abstract BitArray getStorage(); + + @Override + @Unique + public IBlockState getFast(int x, int y, int z) { + return getPalette().getBlockState(getStorage().getAt(y << 8 | z << 4 | x)); + } +} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index 1d1c356b..c1116279 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -9,7 +9,9 @@ }, "client": [ "MixinAnvilChunkLoader", + "MixinBitArray", "MixinBlockPos", + "MixinBlockStateContainer", "MixinChatTabCompleter", "MixinChunkProviderClient", "MixinChunkProviderServer", diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index 22c042f7..365c8bf7 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -18,18 +18,21 @@ package baritone.cache; import baritone.api.cache.IWorldScanner; -import baritone.api.utils.IBlockFilter; +import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.IPlayerContext; -import net.minecraft.block.Block; +import baritone.utils.accessor.IBlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.client.multiplayer.ChunkProviderClient; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.chunk.BlockStateContainer; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import java.util.stream.IntStream; public enum WorldScanner implements IWorldScanner { @@ -39,7 +42,7 @@ public enum WorldScanner implements IWorldScanner { private static final int[] DEFAULT_COORDINATE_ITERATION_ORDER = IntStream.range(0, 16).toArray(); @Override - public List scanChunkRadius(IPlayerContext ctx, IBlockFilter filter, int max, int yLevelThreshold, int maxSearchRadius) { + public List scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLookup filter, int max, int yLevelThreshold, int maxSearchRadius) { ArrayList res = new ArrayList<>(); ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); @@ -86,7 +89,7 @@ public enum WorldScanner implements IWorldScanner { } @Override - public List scanChunk(IPlayerContext ctx, IBlockFilter filter, ChunkPos pos, int max, int yLevelThreshold) { + public List scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold) { ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); Chunk chunk = chunkProvider.getLoadedChunk(pos.x, pos.z); int playerY = ctx.playerFeet().getY(); @@ -100,7 +103,7 @@ public enum WorldScanner implements IWorldScanner { return res; } - private boolean scanChunkInto(int chunkX, int chunkZ, Chunk chunk, IBlockFilter filter, Collection result, int max, int yLevelThreshold, int playerY, int[] coordinateIterationOrder) { + private boolean scanChunkInto(int chunkX, int chunkZ, Chunk chunk, BlockOptionalMetaLookup filter, Collection result, int max, int yLevelThreshold, int playerY, int[] coordinateIterationOrder) { ExtendedBlockStorage[] chunkInternalStorageArray = chunk.getBlockStorageArray(); boolean foundWithinY = false; for (int yIndex = 0; yIndex < 16; yIndex++) { @@ -110,14 +113,14 @@ public enum WorldScanner implements IWorldScanner { continue; } int yReal = y0 << 4; - BlockStateContainer bsc = extendedblockstorage.getData(); + IBlockStateContainer bsc = (IBlockStateContainer) extendedblockstorage.getData(); // the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x; // for better cache locality, iterate in that order for (int y = 0; y < 16; y++) { for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) { - IBlockState state = bsc.get(x, y, z); - if (filter.selected(state)) { + IBlockState state = bsc.getFast(x, y, z); + if (filter.has(state)) { int yy = yReal | y; if (result.size() >= max) { if (Math.abs(yy - playerY) < yLevelThreshold) { diff --git a/src/main/java/baritone/process/FarmProcess.java b/src/main/java/baritone/process/FarmProcess.java index e78c0ce1..00273a9f 100644 --- a/src/main/java/baritone/process/FarmProcess.java +++ b/src/main/java/baritone/process/FarmProcess.java @@ -24,7 +24,6 @@ import baritone.api.pathing.goals.GoalComposite; import baritone.api.process.IFarmProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.api.utils.BlockListFilter; import baritone.api.utils.RayTraceUtils; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; @@ -181,7 +180,7 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro } if (Baritone.settings().mineGoalUpdateInterval.value != 0 && tickCount++ % Baritone.settings().mineGoalUpdateInterval.value == 0) { - Baritone.getExecutor().execute(() -> locations = WorldScanner.INSTANCE.scanChunkRadius(ctx, new BlockListFilter(scan), 256, 10, 10)); + Baritone.getExecutor().execute(() -> locations = WorldScanner.INSTANCE.scanChunkRadius(ctx, scan, 256, 10, 10)); } if (locations == null) { return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 755f27c2..c891f109 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -22,7 +22,7 @@ import baritone.api.pathing.goals.*; import baritone.api.process.IGetToBlockProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.api.utils.BlockListFilter; +import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; @@ -172,7 +172,7 @@ public final class GetToBlockProcess extends BaritoneProcessHelper implements IG } private synchronized void rescan(List known, CalculationContext context) { - List positions = MineProcess.searchWorld(context, new BlockListFilter(gettingTo), 64, known, blacklist); + List positions = MineProcess.searchWorld(context, new BlockOptionalMetaLookup(gettingTo), 64, known, blacklist); positions.removeIf(blacklist::contains); knownLocations = positions; } diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 1b3ef0f1..7e59bc92 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -18,37 +18,42 @@ package baritone.process; import baritone.Baritone; -import baritone.api.pathing.goals.*; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalBlock; +import baritone.api.pathing.goals.GoalComposite; +import baritone.api.pathing.goals.GoalRunAway; +import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.api.utils.BlockSelector; -import baritone.api.utils.BlockUtils; -import baritone.api.utils.CompositeBlockFilter; -import baritone.api.utils.IBlockFilter; +import baritone.api.utils.BlockOptionalMeta; +import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.IPlayerContext; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; -import baritone.cache.CachedChunk; import baritone.cache.WorldScanner; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; -import net.minecraft.block.Block; import net.minecraft.block.BlockAir; import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import java.util.stream.Collectors; import static baritone.api.pathing.movement.ActionCosts.COST_INF; @@ -59,10 +64,9 @@ import static baritone.api.pathing.movement.ActionCosts.COST_INF; * @author leijurv */ public final class MineProcess extends BaritoneProcessHelper implements IMineProcess { - private static final int ORE_LOCATIONS_COUNT = 64; - private IBlockFilter filter; + private BlockOptionalMetaLookup filter; private List knownOreLocations; private List blacklist; // inaccessible private BlockPos branchPoint; @@ -83,7 +87,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (desiredQuantity > 0) { int curr = ctx.player().inventory.mainInventory.stream() - .filter(stack -> filter.selected(BlockSelector.stateFromItem(stack))) + .filter(stack -> filter.has(BlockOptionalMeta.blockStateFromStack(stack))) .mapToInt(ItemStack::getCount).sum(); System.out.println("Currently have " + curr + " valid items"); if (curr >= desiredQuantity) { @@ -150,7 +154,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro @Override public void onLostControl() { - mine(0, (IBlockFilter) null); + mine(0, (BlockOptionalMetaLookup) null); } @Override @@ -223,7 +227,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (Baritone.settings().internalMiningAirException.value && state.getBlock() instanceof BlockAir) { return true; } - return filter.selected(state); + return filter.has(state); } private Goal coalesce(BlockPos loc, List locs) { @@ -288,7 +292,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } - public static List droppedItemsScan(IBlockFilter filter, World world) { + public static List droppedItemsScan(BlockOptionalMetaLookup filter, World world) { if (!Baritone.settings().mineScanDroppedItems.value) { return Collections.emptyList(); } @@ -297,9 +301,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (entity instanceof EntityItem) { EntityItem ei = (EntityItem) entity; ItemStack stack = ei.getItem(); - Item item = stack.getItem(); - //noinspection deprecation - if (filter.selected(Block.getBlockFromItem(item).getStateFromMeta(stack.getItemDamage()))) { + if (filter.has(BlockOptionalMeta.blockStateFromStack(stack))) { ret.add(new BlockPos(entity)); } } @@ -307,7 +309,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return ret; } - public static List searchWorld(CalculationContext ctx, IBlockFilter filter, int max, List alreadyKnown, List blacklist) { + public static List searchWorld(CalculationContext ctx, BlockOptionalMetaLookup filter, int max, List alreadyKnown, List blacklist) { List locs = new ArrayList<>(); locs = prune(ctx, locs, filter, max, blacklist); locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), filter, max, 10, 32)); // maxSearchRadius is NOT sq @@ -326,7 +328,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) { // crucial to only add blocks we can see because otherwise this // is an x-ray and it'll get caught - if (filter.selected(bsi.get0(x, y, z))) { + 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()) { knownOreLocations.add(pos); @@ -338,30 +340,30 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, filter, ORE_LOCATIONS_COUNT, blacklist); } - private static List prune(CalculationContext ctx, List locs2, IBlockFilter filter, int max, List blacklist) { + private static List prune(CalculationContext ctx, List locs2, BlockOptionalMetaLookup filter, int max, List blacklist) { List dropped = droppedItemsScan(filter, ctx.world); dropped.removeIf(drop -> { for (BlockPos pos : locs2) { - if (pos.distanceSq(drop) <= 9 && filter.selected(ctx.get(pos.getX(), pos.getY(), pos.getZ())) && MineProcess.plausibleToBreak(ctx, pos)) { // TODO maybe drop also has to be supported? no lava below? + if (pos.distanceSq(drop) <= 9 && filter.has(ctx.get(pos.getX(), pos.getY(), pos.getZ())) && MineProcess.plausibleToBreak(ctx, pos)) { // TODO maybe drop also has to be supported? no lava below? return true; } } return false; }); List locs = locs2 - .stream() - .distinct() + .stream() + .distinct() - // remove any that are within loaded chunks that aren't actually what we want - .filter(pos -> !ctx.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ()) || filter.selected(ctx.get(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos)) + // remove any that are within loaded chunks that aren't actually what we want + .filter(pos -> !ctx.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ()) || filter.has(ctx.get(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos)) - // remove any that are implausible to mine (encased in bedrock, or touching lava) - .filter(pos -> MineProcess.plausibleToBreak(ctx, pos)) + // remove any that are implausible to mine (encased in bedrock, or touching lava) + .filter(pos -> MineProcess.plausibleToBreak(ctx, pos)) - .filter(pos -> !blacklist.contains(pos)) + .filter(pos -> !blacklist.contains(pos)) - .sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().player()::getDistanceSq)) - .collect(Collectors.toList()); + .sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().player()::getDistanceSq)) + .collect(Collectors.toList()); if (locs.size() > max) { return locs.subList(0, max); @@ -380,15 +382,15 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro @Override public void mineByName(int quantity, String... blocks) { - mine(quantity, new CompositeBlockFilter( + mine(quantity, new BlockOptionalMetaLookup( Arrays.stream(Objects.requireNonNull(blocks)) - .map(BlockSelector::new) - .toArray(IBlockFilter[]::new) + .map(BlockOptionalMeta::new) + .toArray(BlockOptionalMeta[]::new) )); } @Override - public void mine(int quantity, IBlockFilter filter) { + public void mine(int quantity, BlockOptionalMetaLookup filter) { this.filter = filter; if (filter != null && !Baritone.settings().allowBreak.value) { logDirect("Unable to mine when allowBreak is false!"); diff --git a/src/main/java/baritone/utils/accessor/IBlockStateContainer.java b/src/main/java/baritone/utils/accessor/IBlockStateContainer.java new file mode 100644 index 00000000..735e183a --- /dev/null +++ b/src/main/java/baritone/utils/accessor/IBlockStateContainer.java @@ -0,0 +1,13 @@ +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 getFast(int x, int y, int z); +} From fe47245b7388327bfd421fed17c07c98f8381830 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 17:12:05 -0700 Subject: [PATCH 567/682] Fix searchWorld cache and also speed and stuff --- .../baritone/api/utils/BlockOptionalMeta.java | 10 +-- .../api/utils/BlockOptionalMetaLookup.java | 83 ++++++++----------- .../baritone/api/utils/IPlayerContext.java | 9 +- .../mixins/MixinBlockStateContainer.java | 15 +++- src/main/java/baritone/cache/CachedChunk.java | 10 +++ .../java/baritone/process/MineProcess.java | 43 ++++++++-- 6 files changed, 104 insertions(+), 66 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index b77bf541..dcfda0f8 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -54,7 +54,7 @@ public final class BlockOptionalMeta { } MatchResult matchResult = matcher.toMatchResult(); - noMeta = matchResult.groupCount() < 2; + noMeta = matchResult.group(2) == null; ResourceLocation id = new ResourceLocation(matchResult.group(1)); @@ -74,13 +74,13 @@ public final class BlockOptionalMeta { return meta; } - public boolean matches(@Nonnull Block block, int meta) { - // & instead of && is intentional - return block == this.block & (noMeta || meta == this.meta); + public boolean matches(@Nonnull Block block) { + return block == this.block; } public boolean matches(@Nonnull IBlockState blockstate) { - return matches(blockstate.getBlock(), block.damageDropped(blockstate)); + Block block = blockstate.getBlock(); + return block == this.block && (noMeta || block.damageDropped(blockstate) == this.meta); } @Override diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index eafe49e1..2457484f 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -2,69 +2,34 @@ package baritone.api.utils; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; -import org.apache.commons.lang3.ArrayUtils; -import java.util.HashMap; +import java.util.Arrays; import java.util.List; -import java.util.Map; -import java.util.Set; + +import static java.util.Arrays.asList; public class BlockOptionalMetaLookup { - private final Map lookup = new HashMap<>(); - - public BlockOptionalMetaLookup() { - } + private final BlockOptionalMeta[] boms; public BlockOptionalMetaLookup(BlockOptionalMeta... boms) { - put(boms); + this.boms = boms; } public BlockOptionalMetaLookup(Block... blocks) { - put(blocks); + this.boms = Arrays.stream(blocks) + .map(BlockOptionalMeta::new) + .toArray(BlockOptionalMeta[]::new); } public BlockOptionalMetaLookup(List blocks) { - put(blocks); - } - - public void put(BlockOptionalMeta bom) { - final int[] metaArr = new int[] {bom.getMeta()}; - lookup.compute(bom.getBlock(), (__, arr) -> arr == null ? metaArr : ArrayUtils.addAll(arr, metaArr)); - } - - public void put(BlockOptionalMeta... boms) { - for (BlockOptionalMeta bom : boms) { - put(bom); - } - } - - public void put(Block... blocks) { - for (Block block : blocks) { - put(new BlockOptionalMeta(block)); - } - } - - public void put(List blocks) { - for (Block block : blocks) { - put(new BlockOptionalMeta(block)); - } + this.boms = blocks.stream() + .map(BlockOptionalMeta::new) + .toArray(BlockOptionalMeta[]::new); } public boolean has(Block block) { - return lookup.containsKey(block); - } - - public boolean has(IBlockState state) { - Block block = state.getBlock(); - int[] arr = lookup.get(block); - - if (arr == null) { - return false; - } - - int meta = block.damageDropped(state); - for (int value : arr) { - if (value == meta) { + for (BlockOptionalMeta bom : boms) { + if (bom.getBlock() == block) { return true; } } @@ -72,7 +37,25 @@ public class BlockOptionalMetaLookup { return false; } - public Set blocks() { - return lookup.keySet(); + public boolean has(IBlockState state) { + for (BlockOptionalMeta bom : boms) { + if (bom.matches(state)) { + return true; + } + } + + return false; + } + + public List blocks() { + return asList(boms); + } + + @Override + public String toString() { + return String.format( + "BlockOptionalMetaLookup{%s}", + Arrays.toString(boms) + ); } } diff --git a/src/api/java/baritone/api/utils/IPlayerContext.java b/src/api/java/baritone/api/utils/IPlayerContext.java index 9acb2ad9..a9f7cdf7 100644 --- a/src/api/java/baritone/api/utils/IPlayerContext.java +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -47,9 +47,14 @@ public interface IPlayerContext { default BetterBlockPos playerFeet() { // TODO find a better way to deal with soul sand!!!!! BetterBlockPos feet = new BetterBlockPos(player().posX, player().posY + 0.1251, player().posZ); - if (world().getBlockState(feet).getBlock() instanceof BlockSlab) { - return feet.up(); + + try { + if (world().getBlockState(feet).getBlock() instanceof BlockSlab) { + return feet.up(); + } + } catch (NullPointerException ignored) { } + return feet; } diff --git a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java index b419952d..343bdda6 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java @@ -23,20 +23,29 @@ import net.minecraft.util.BitArray; import net.minecraft.world.chunk.BlockStateContainer; import net.minecraft.world.chunk.IBlockStatePalette; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.gen.Accessor; @Mixin(BlockStateContainer.class) public abstract class MixinBlockStateContainer implements IBlockStateContainer { - @Accessor - public abstract IBlockStatePalette getPalette(); + @Shadow + protected BitArray storage; + @Shadow + protected IBlockStatePalette palette; + + @Override @Accessor public abstract BitArray getStorage(); + @Override + @Accessor + public abstract IBlockStatePalette getPalette(); + @Override @Unique public IBlockState getFast(int x, int y, int z) { - return getPalette().getBlockState(getStorage().getAt(y << 8 | z << 4 | x)); + return palette.getBlockState(storage.getAt(y << 8 | z << 4 | x)); } } diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 67ac6942..148b21e7 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -91,6 +91,16 @@ public final class CachedChunk { Blocks.VINE ); + public static boolean tracked(Block block) { + for (Block tracked : BLOCKS_TO_KEEP_TRACK_OF) { + if (tracked == block) { + return true; + } + } + + return false; + } + /** * The size of the chunk data in bits. Equal to 16 KiB. diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 7e59bc92..75648ae1 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -26,17 +26,21 @@ import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.BlockOptionalMetaLookup; +import baritone.api.utils.BlockUtils; import baritone.api.utils.IPlayerContext; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; +import baritone.cache.CachedChunk; import baritone.cache.WorldScanner; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; +import net.minecraft.block.Block; import net.minecraft.block.BlockAir; import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; @@ -122,10 +126,10 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro addNearby(); } Optional shaft = curr.stream() - .filter(pos -> pos.getX() == ctx.playerFeet().getX() && pos.getZ() == ctx.playerFeet().getZ()) - .filter(pos -> pos.getY() >= ctx.playerFeet().getY()) - .filter(pos -> !(BlockStateInterface.get(ctx, pos).getBlock() instanceof BlockAir)) // after breaking a block, it takes mineGoalUpdateInterval ticks for it to actually update this list =( - .min(Comparator.comparingDouble(ctx.player()::getDistanceSq)); + .filter(pos -> pos.getX() == ctx.playerFeet().getX() && pos.getZ() == ctx.playerFeet().getZ()) + .filter(pos -> pos.getY() >= ctx.playerFeet().getY()) + .filter(pos -> !(BlockStateInterface.get(ctx, pos).getBlock() instanceof BlockAir)) // after breaking a block, it takes mineGoalUpdateInterval ticks for it to actually update this list =( + .min(Comparator.comparingDouble(ctx.player()::getDistanceSq)); baritone.getInputOverrideHandler().clearAllKeys(); if (shaft.isPresent() && ctx.player().onGround) { BlockPos pos = shaft.get(); @@ -311,9 +315,36 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro public static List searchWorld(CalculationContext ctx, BlockOptionalMetaLookup filter, int max, List alreadyKnown, List blacklist) { List locs = new ArrayList<>(); - locs = prune(ctx, locs, filter, max, blacklist); - locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), filter, max, 10, 32)); // maxSearchRadius is NOT sq + List untracked = new ArrayList<>(); + for (BlockOptionalMeta bom : filter.blocks()) { + Block block = bom.getBlock(); + if (CachedChunk.tracked(block)) { + BetterBlockPos pf = ctx.baritone.getPlayerContext().playerFeet(); + + locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf( + BlockUtils.blockToString(block), + Baritone.settings().maxCachedWorldScanCount.value, + pf.x, + pf.z, + 2 + )); + } else { + untracked.add(block); + } + } + + if (!untracked.isEmpty()) { + locs.addAll(WorldScanner.INSTANCE.scanChunkRadius( + ctx.getBaritone().getPlayerContext(), + filter, + max, + 10, + 32 + )); // maxSearchRadius is NOT sq + } + locs.addAll(alreadyKnown); + return prune(ctx, locs, filter, max, blacklist); } From b6c91b506207e81059f24e57914d699a62500b0c Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 17:13:09 -0700 Subject: [PATCH 568/682] speed up cache stuff --- src/main/java/baritone/cache/CachedChunk.java | 10 ---------- src/main/java/baritone/process/MineProcess.java | 2 +- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 148b21e7..67ac6942 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -91,16 +91,6 @@ public final class CachedChunk { Blocks.VINE ); - public static boolean tracked(Block block) { - for (Block tracked : BLOCKS_TO_KEEP_TRACK_OF) { - if (tracked == block) { - return true; - } - } - - return false; - } - /** * The size of the chunk data in bits. Equal to 16 KiB. diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 75648ae1..c253cdf8 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -318,7 +318,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro List untracked = new ArrayList<>(); for (BlockOptionalMeta bom : filter.blocks()) { Block block = bom.getBlock(); - if (CachedChunk.tracked(block)) { + if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(block)) { BetterBlockPos pf = ctx.baritone.getPlayerContext().playerFeet(); locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf( From a6726f4e96b28741f008445779dd7aed03243db0 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 17:19:44 -0700 Subject: [PATCH 569/682] extend cache on threshold --- 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 c253cdf8..fd62c5cf 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -333,7 +333,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } - if (!untracked.isEmpty()) { + if (!untracked.isEmpty() || (Baritone.settings().extendCacheOnThreshold.value && locs.size() < max)) { locs.addAll(WorldScanner.INSTANCE.scanChunkRadius( ctx.getBaritone().getPlayerContext(), filter, From 69ca48287e5b30c425fb07f6357cfb7023ad1a85 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 17:20:20 -0700 Subject: [PATCH 570/682] prune before checking size --- src/main/java/baritone/process/MineProcess.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index fd62c5cf..18c7a7b1 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -333,6 +333,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } + locs = prune(ctx, locs, filter, max, blacklist); + if (!untracked.isEmpty() || (Baritone.settings().extendCacheOnThreshold.value && locs.size() < max)) { locs.addAll(WorldScanner.INSTANCE.scanChunkRadius( ctx.getBaritone().getPlayerContext(), From 172ce3a05459ef3a891d04542d974ff48005f877 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 18:00:34 -0700 Subject: [PATCH 571/682] click --- .../utils/command/defaults/ClickCommand.java | 55 +++++++++++++++++++ .../command/defaults/DefaultCommands.java | 3 +- .../command/defaults/PauseResumeCommands.java | 3 +- 3 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 src/api/java/baritone/api/utils/command/defaults/ClickCommand.java diff --git a/src/api/java/baritone/api/utils/command/defaults/ClickCommand.java b/src/api/java/baritone/api/utils/command/defaults/ClickCommand.java new file mode 100644 index 00000000..120b5867 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ClickCommand.java @@ -0,0 +1,55 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class ClickCommand extends Command { + public ClickCommand() { + super("click", "Open click"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireMax(0); + baritone.openClick(); + logDirect("aight dude"); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "Opens click dude", + "", + "Usage:", + "> click" + ); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java b/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java index 18e0bc9d..fac6422f 100644 --- a/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java +++ b/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java @@ -59,6 +59,7 @@ public class DefaultCommands { new ExploreCommand(), new BlacklistCommand(), new FindCommand(), - new MineCommand() + new MineCommand(), + new ClickCommand() )); } diff --git a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java b/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java index b0d2e1b5..ff8bc783 100644 --- a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java +++ b/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java @@ -19,8 +19,7 @@ import static java.util.Arrays.asList; * * This thing is scoped to hell, private so far you can't even access it using reflection, because you AREN'T SUPPOSED * TO USE THIS to pause and resume Baritone. Make your own process that returns {@link PathingCommandType#REQUEST_PAUSE - * REQUEST_PAUSE} - * as needed. + * REQUEST_PAUSE} as needed. */ public class PauseResumeCommands { public static Command pauseCommand; From c938983ff556c01e4a750be3cde76871224eb68b Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 22:27:30 -0700 Subject: [PATCH 572/682] thisway command + fixed fromDirection for you + fixed double/float argparsers --- .../baritone/api/pathing/goals/GoalXZ.java | 2 +- .../command/argparser/DefaultArgParsers.java | 4 +- .../command/defaults/DefaultCommands.java | 3 +- .../command/defaults/ThisWayCommand.java | 63 +++++++++++++++++++ 4 files changed, 68 insertions(+), 4 deletions(-) create mode 100644 src/api/java/baritone/api/utils/command/defaults/ThisWayCommand.java diff --git a/src/api/java/baritone/api/pathing/goals/GoalXZ.java b/src/api/java/baritone/api/pathing/goals/GoalXZ.java index 5ad23336..86511b54 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalXZ.java +++ b/src/api/java/baritone/api/pathing/goals/GoalXZ.java @@ -93,7 +93,7 @@ public class GoalXZ implements Goal { float theta = (float) Math.toRadians(yaw); double x = origin.x - MathHelper.sin(theta) * distance; double z = origin.z + MathHelper.cos(theta) * distance; - return new GoalXZ((int) x, (int) z); + return new GoalXZ(MathHelper.floor(x), MathHelper.floor(z)); } public int getX() { diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index 301ad891..03d3b5c9 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -50,7 +50,7 @@ public class DefaultArgParsers { public Float parseArg(CommandArgument arg) throws RuntimeException { String value = arg.value; - if (!value.matches("^[+-]?\\d+(?:\\.\\d+)$")) { + if (!value.matches("^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$")) { throw new RuntimeException("failed float format check"); } @@ -69,7 +69,7 @@ public class DefaultArgParsers { public Double parseArg(CommandArgument arg) throws RuntimeException { String value = arg.value; - if (!value.matches("^[+-]?\\d+(?:\\.\\d+)$")) { + if (!value.matches("^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$")) { throw new RuntimeException("failed double format check"); } diff --git a/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java b/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java index fac6422f..9d260e76 100644 --- a/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java +++ b/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java @@ -60,6 +60,7 @@ public class DefaultCommands { new BlacklistCommand(), new FindCommand(), new MineCommand(), - new ClickCommand() + new ClickCommand(), + new ThisWayCommand() )); } diff --git a/src/api/java/baritone/api/utils/command/defaults/ThisWayCommand.java b/src/api/java/baritone/api/utils/command/defaults/ThisWayCommand.java new file mode 100644 index 00000000..5eeeeba9 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/ThisWayCommand.java @@ -0,0 +1,63 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.pathing.goals.GoalXZ; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class ThisWayCommand extends Command { + public ThisWayCommand() { + super(asList("thisway", "forward"), "Travel in your current direction"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + args.requireExactly(1); + + GoalXZ goal = GoalXZ.fromDirection( + ctx.playerFeetAsVec(), + ctx.player().rotationYawHead, + args.getAs(Double.class) + ); + + baritone.getCustomGoalProcess().setGoal(goal); + logDirect(String.format("Goal: %s", goal)); + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "Creates a GoalXZ some amount of blocks in the direction you're currently looking", + "", + "Usage:", + "> thisway - makes a GoalXZ distance blocks in front of you" + ); + } +} From 9f3eaac3dfbd9eabac882ace9c766d57c880306b Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 22:52:20 -0700 Subject: [PATCH 573/682] increase efficiency of scanChunkInto by ~25% --- .../mixins/MixinBlockStateContainer.java | 4 +-- .../java/baritone/cache/WorldScanner.java | 31 +++++++++---------- .../utils/accessor/IBlockStateContainer.java | 6 +++- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java index 343bdda6..e3b7cbeb 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java @@ -45,7 +45,7 @@ public abstract class MixinBlockStateContainer implements IBlockStateContainer { @Override @Unique - public IBlockState getFast(int x, int y, int z) { - return palette.getBlockState(storage.getAt(y << 8 | z << 4 | x)); + public IBlockState getFast(int index) { + return palette.getBlockState(storage.getAt(index)); } } diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index 365c8bf7..3c314e71 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -116,26 +116,23 @@ public enum WorldScanner implements IWorldScanner { IBlockStateContainer bsc = (IBlockStateContainer) extendedblockstorage.getData(); // the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x; // for better cache locality, iterate in that order - for (int y = 0; y < 16; y++) { - for (int z = 0; z < 16; z++) { - for (int x = 0; x < 16; x++) { - IBlockState state = bsc.getFast(x, y, z); - if (filter.has(state)) { - int yy = yReal | y; - if (result.size() >= max) { - if (Math.abs(yy - playerY) < yLevelThreshold) { - foundWithinY = true; - } else { - if (foundWithinY) { - // have found within Y in this chunk, so don't need to consider outside Y - // TODO continue iteration to one more sorted Y coordinate block - return true; - } - } + int imax = 1 << 12; + for (int i = 0; i < imax; i++) { + IBlockState state = bsc.getFast(i); + if (filter.has(state)) { + int y = yReal | (i >> 8 & 15); + if (result.size() >= max) { + if (Math.abs(y - playerY) < yLevelThreshold) { + foundWithinY = true; + } else { + if (foundWithinY) { + // have found within Y in this chunk, so don't need to consider outside Y + // TODO continue iteration to one more sorted Y coordinate block + return true; } - result.add(new BlockPos(chunkX | x, yy, chunkZ | z)); } } + result.add(new BlockPos(chunkX | (i & 15), y, chunkZ | (i >> 4 & 15))); } } } diff --git a/src/main/java/baritone/utils/accessor/IBlockStateContainer.java b/src/main/java/baritone/utils/accessor/IBlockStateContainer.java index 735e183a..ad602f37 100644 --- a/src/main/java/baritone/utils/accessor/IBlockStateContainer.java +++ b/src/main/java/baritone/utils/accessor/IBlockStateContainer.java @@ -9,5 +9,9 @@ public interface IBlockStateContainer { BitArray getStorage(); - IBlockState getFast(int x, int y, int z); + IBlockState getFast(int index); + + default IBlockState getFast(int x, int y, int z) { + return getFast(y << 8 | z << 4 | x); + }; } From ae6ee5688cf80627dfda97ed5d1c314e5614afff Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 00:51:42 -0700 Subject: [PATCH 574/682] add toArray, scanChunkInto usage coming soon --- .../baritone/launch/mixins/MixinBitArray.java | 48 +++++++++++++++++-- .../mixins/MixinBlockStateContainer.java | 11 +++++ .../baritone/utils/accessor/IBitArray.java | 5 ++ .../utils/accessor/IBlockStateContainer.java | 6 +-- 4 files changed, 63 insertions(+), 7 deletions(-) create mode 100644 src/main/java/baritone/utils/accessor/IBitArray.java diff --git a/src/launch/java/baritone/launch/mixins/MixinBitArray.java b/src/launch/java/baritone/launch/mixins/MixinBitArray.java index 54ead39a..614ec351 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBitArray.java +++ b/src/launch/java/baritone/launch/mixins/MixinBitArray.java @@ -17,14 +17,18 @@ package baritone.launch.mixins; +import baritone.utils.accessor.IBitArray; import net.minecraft.util.BitArray; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; + +import java.util.Arrays; @Mixin(BitArray.class) -public abstract class MixinBitArray { +public abstract class MixinBitArray implements IBitArray { @Shadow @Final private long[] longArray; @@ -37,6 +41,10 @@ public abstract class MixinBitArray { @Final private long maxEntryValue; + @Shadow + @Final + private int arraySize; + /** * why did mojang divide by 64 instead of shifting right by 6 (2^6=64)? * why did mojang modulo by 64 instead of ANDing with 63? @@ -47,16 +55,48 @@ public abstract class MixinBitArray { @Overwrite public int getAt(int index) { final int b = bitsPerEntry; + final long mev = maxEntryValue; final int i = index * b; final int j = i >> 6; final int l = i & 63; final int k = ((index + 1) * b - 1) >> 6; if (j == k) { - return (int) (this.longArray[j] >>> l & maxEntryValue); + return (int) (this.longArray[j] >>> l & mev); } else { - int i1 = 64 - l; - return (int) ((this.longArray[j] >>> l | longArray[k] << i1) & maxEntryValue); + return (int) ((this.longArray[j] >>> l | longArray[k] << (64 - l)) & mev); } } + + @Unique + public int[] toArrayBad() { + int[] out = new int[arraySize]; + + for (int i = 0; i < arraySize; i++) { + out[i] = getAt(i); + } + + return out; + } + + @Override + public int[] toArray() { + int[] out = new int[arraySize]; + + 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) { + out[idx] = (int) (jl & maxEntryValue); + } else { + out[idx] = (int) ((jl | longArray[k] << (64 - l)) & maxEntryValue); + } + } + + return out; + } } diff --git a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java index e3b7cbeb..8a1b000f 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java @@ -17,6 +17,7 @@ package baritone.launch.mixins; +import baritone.utils.accessor.IBitArray; import baritone.utils.accessor.IBlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.util.BitArray; @@ -48,4 +49,14 @@ public abstract class MixinBlockStateContainer implements IBlockStateContainer { public IBlockState getFast(int index) { return palette.getBlockState(storage.getAt(index)); } + + @Override + public IBlockState getAtPalette(int index) { + return palette.getBlockState(index); + } + + @Override + public int[] storageArray() { + return ((IBitArray) storage).toArray(); + } } diff --git a/src/main/java/baritone/utils/accessor/IBitArray.java b/src/main/java/baritone/utils/accessor/IBitArray.java new file mode 100644 index 00000000..fef08044 --- /dev/null +++ b/src/main/java/baritone/utils/accessor/IBitArray.java @@ -0,0 +1,5 @@ +package baritone.utils.accessor; + +public interface IBitArray { + int[] toArray(); +} diff --git a/src/main/java/baritone/utils/accessor/IBlockStateContainer.java b/src/main/java/baritone/utils/accessor/IBlockStateContainer.java index ad602f37..aa2eaab4 100644 --- a/src/main/java/baritone/utils/accessor/IBlockStateContainer.java +++ b/src/main/java/baritone/utils/accessor/IBlockStateContainer.java @@ -11,7 +11,7 @@ public interface IBlockStateContainer { IBlockState getFast(int index); - default IBlockState getFast(int x, int y, int z) { - return getFast(y << 8 | z << 4 | x); - }; + IBlockState getAtPalette(int index); + + int[] storageArray(); } From efa243386cedd2b0f05617fe4432021b4aa90fc5 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 01:00:37 -0700 Subject: [PATCH 575/682] Make scanChunkInto even faster --- src/main/java/baritone/cache/WorldScanner.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index 3c314e71..b5ca6a6a 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -116,9 +116,10 @@ public enum WorldScanner implements IWorldScanner { IBlockStateContainer bsc = (IBlockStateContainer) extendedblockstorage.getData(); // the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x; // for better cache locality, iterate in that order + int[] storage = bsc.storageArray(); int imax = 1 << 12; for (int i = 0; i < imax; i++) { - IBlockState state = bsc.getFast(i); + IBlockState state = bsc.getAtPalette(storage[i]); if (filter.has(state)) { int y = yReal | (i >> 8 & 15); if (result.size() >= max) { From 5e0b333cfd3d5297addbcd4e2600ce0f7a618838 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 01:04:22 -0700 Subject: [PATCH 576/682] fix comment & make final int final --- src/main/java/baritone/cache/WorldScanner.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index b5ca6a6a..3acd9661 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -114,10 +114,10 @@ public enum WorldScanner implements IWorldScanner { } int yReal = y0 << 4; IBlockStateContainer bsc = (IBlockStateContainer) extendedblockstorage.getData(); - // the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x; - // for better cache locality, iterate in that order + // storageArray uses an optimized algorithm that's faster than getAt + // creating this array and then using getAtPalette is faster than even getFast(int index) int[] storage = bsc.storageArray(); - int imax = 1 << 12; + final int imax = 1 << 12; for (int i = 0; i < imax; i++) { IBlockState state = bsc.getAtPalette(storage[i]); if (filter.has(state)) { From 15e9d756b7a4a14be777efc5971a77e90aa74438 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 01:59:45 -0700 Subject: [PATCH 577/682] Remove unused toArrayBad function... --- .../java/baritone/launch/mixins/MixinBitArray.java | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinBitArray.java b/src/launch/java/baritone/launch/mixins/MixinBitArray.java index 614ec351..d3a3f167 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBitArray.java +++ b/src/launch/java/baritone/launch/mixins/MixinBitArray.java @@ -68,17 +68,6 @@ public abstract class MixinBitArray implements IBitArray { } } - @Unique - public int[] toArrayBad() { - int[] out = new int[arraySize]; - - for (int i = 0; i < arraySize; i++) { - out[i] = getAt(i); - } - - return out; - } - @Override public int[] toArray() { int[] out = new int[arraySize]; From b924e8511b8eeae0217a5db943e2d2e5e17c1dbb Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 02:14:38 -0700 Subject: [PATCH 578/682] fix imports --- src/launch/java/baritone/launch/mixins/MixinBitArray.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinBitArray.java b/src/launch/java/baritone/launch/mixins/MixinBitArray.java index d3a3f167..5bb738a2 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBitArray.java +++ b/src/launch/java/baritone/launch/mixins/MixinBitArray.java @@ -23,9 +23,6 @@ import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; - -import java.util.Arrays; @Mixin(BitArray.class) public abstract class MixinBitArray implements IBitArray { From 2ee313a7953fe638f2765089837dfcda91bd43bf Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 06:38:36 -0700 Subject: [PATCH 579/682] Don't break Forge world loading --- .../command/defaults/WaypointCommand.java | 53 +++++++++++++++++++ .../baritone/launch/mixins/MixinBitArray.java | 7 ++- .../mixins/MixinBlockStateContainer.java | 2 +- .../baritone/utils/accessor/IBitArray.java | 2 + 4 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 src/api/java/baritone/api/utils/command/defaults/WaypointCommand.java diff --git a/src/api/java/baritone/api/utils/command/defaults/WaypointCommand.java b/src/api/java/baritone/api/utils/command/defaults/WaypointCommand.java new file mode 100644 index 00000000..22438277 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/WaypointCommand.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.utils.command.defaults; + +import baritone.api.Settings; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class WaypointCommand extends Command { + public WaypointCommand() { + super(asList("name1", "name2"), "Short description"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + ; + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "", + "", + "Usage:", + "> " + ); + } +} diff --git a/src/launch/java/baritone/launch/mixins/MixinBitArray.java b/src/launch/java/baritone/launch/mixins/MixinBitArray.java index 5bb738a2..e0782803 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBitArray.java +++ b/src/launch/java/baritone/launch/mixins/MixinBitArray.java @@ -23,6 +23,7 @@ import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; @Mixin(BitArray.class) public abstract class MixinBitArray implements IBitArray { @@ -49,8 +50,9 @@ public abstract class MixinBitArray implements IBitArray { * * @author LoganDark */ - @Overwrite - public int getAt(int index) { + @Override + @Unique + public int getAtFast(int index) { final int b = bitsPerEntry; final long mev = maxEntryValue; final int i = index * b; @@ -66,6 +68,7 @@ public abstract class MixinBitArray implements IBitArray { } @Override + @Unique public int[] toArray() { int[] out = new int[arraySize]; diff --git a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java index 8a1b000f..d3de16f0 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java @@ -47,7 +47,7 @@ public abstract class MixinBlockStateContainer implements IBlockStateContainer { @Override @Unique public IBlockState getFast(int index) { - return palette.getBlockState(storage.getAt(index)); + return palette.getBlockState(((IBitArray) storage).getAtFast(index)); } @Override diff --git a/src/main/java/baritone/utils/accessor/IBitArray.java b/src/main/java/baritone/utils/accessor/IBitArray.java index fef08044..1fd912a2 100644 --- a/src/main/java/baritone/utils/accessor/IBitArray.java +++ b/src/main/java/baritone/utils/accessor/IBitArray.java @@ -1,5 +1,7 @@ package baritone.utils.accessor; public interface IBitArray { + int getAtFast(int index); + int[] toArray(); } From ee71819bb2f67eaf20da0af0b284986b34bd1326 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 06:42:16 -0700 Subject: [PATCH 580/682] remove unnecessary import --- src/launch/java/baritone/launch/mixins/MixinBitArray.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinBitArray.java b/src/launch/java/baritone/launch/mixins/MixinBitArray.java index e0782803..2719cfa7 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBitArray.java +++ b/src/launch/java/baritone/launch/mixins/MixinBitArray.java @@ -21,7 +21,6 @@ import baritone.utils.accessor.IBitArray; import net.minecraft.util.BitArray; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; From d54e846f917b257a57b922c4d2c6dbf11dae7c75 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 07:16:02 -0700 Subject: [PATCH 581/682] Proguard likes to fuck up my command framework in the build. This error makes it more clear when that happens --- .../api/utils/command/helpers/arguments/ArgConsumer.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index 8f6b91f0..e050239c 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -25,6 +25,7 @@ import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.exception.CommandTooManyArgumentsException; +import baritone.api.utils.command.exception.CommandUnhandledException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -213,8 +214,10 @@ public class ArgConsumer { public T getDatatype(Class datatype) { try { return datatype.getConstructor(ArgConsumer.class).newInstance(this); - } catch (RuntimeException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { + } catch (RuntimeException e) { throw new CommandInvalidTypeException(has() ? peek() : consumed(), datatype.getSimpleName()); + } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { + throw new CommandUnhandledException(e); } } From 90fb17b89f21e3d4b714155b7ee977f9f3bf1299 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 07:36:23 -0700 Subject: [PATCH 582/682] Told Proguard not to touch things it doesn't understand --- scripts/proguard.pro | 5 +++++ .../utils/command/exception/CommandUnhandledException.java | 1 + .../api/utils/command/helpers/arguments/ArgConsumer.java | 4 ++-- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 4ac0f723..53ab195d 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -17,6 +17,11 @@ -keep class baritone.api.** { *; } # this is the keep api +# Proguard does not know the commands framework better than I do +# It needs its empty constructors and simple names to work correctly +-keep class baritone.api.utils.command.** { *; } +-keepclasseswithmembernames class baritone.api.utils.command.** { *; } + # service provider needs these class names -keep class baritone.BaritoneProvider -keep class baritone.api.IBaritoneProvider diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java index 849ace18..dba4513e 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -63,6 +63,7 @@ public class CommandUnhandledException extends CommandErrorMessageException { // line = line.replaceFirst("\\(([^)]+)\\)$", "\n\t . $1"); line = line.replaceFirst("\\([^:]+:(\\d+)\\)$", ":$1"); + line = line.replaceFirst("\\(Unknown Source\\)$", ""); lines.set(i, line); } } diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index e050239c..9cec8d1f 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -214,9 +214,9 @@ public class ArgConsumer { public T getDatatype(Class datatype) { try { return datatype.getConstructor(ArgConsumer.class).newInstance(this); - } catch (RuntimeException e) { + } catch (InvocationTargetException e) { throw new CommandInvalidTypeException(has() ? peek() : consumed(), datatype.getSimpleName()); - } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { + } catch (NoSuchMethodException | IllegalAccessException | InstantiationException e) { throw new CommandUnhandledException(e); } } From 84f45ebb48ecefac19b3ec6e2e0f406113f227f3 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 07:55:24 -0700 Subject: [PATCH 583/682] Fix file tab completion in production environments --- .../api/utils/command/datatypes/RelativeFile.java | 12 ++++++++++++ .../utils/command/defaults/ExploreFilterCommand.java | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index 41b6ff55..b612e342 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -11,6 +11,8 @@ import java.util.Locale; import java.util.Objects; import java.util.stream.Stream; +import static baritone.api.utils.Helper.HELPER; + public class RelativeFile implements IDatatypePost { private final Path path; @@ -48,4 +50,14 @@ public class RelativeFile implements IDatatypePost { public File apply(File original) { return original.toPath().resolve(path).toFile(); } + + public static File gameDir() { + File gameDir = HELPER.mc.gameDir.getAbsoluteFile(); + + if (gameDir.getName().equals(".")) { + return gameDir.getParentFile(); + } + + return gameDir; + } } diff --git a/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java b/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java index 6b257012..1dd48512 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java @@ -67,7 +67,7 @@ public class ExploreFilterCommand extends Command { @Override protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { if (args.hasExactlyOne()) { - return RelativeFile.tabComplete(args, MC.gameDir.getAbsoluteFile().getParentFile()); + return RelativeFile.tabComplete(args, RelativeFile.gameDir()); } return Stream.empty(); From 6ed86cb3c7d076571126bdeaa9b421c399447b93 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 10:28:01 -0700 Subject: [PATCH 584/682] Hopefully speed up BlockOptionalMeta --- .../baritone/api/utils/BlockOptionalMeta.java | 21 ++++++- .../mixins/MixinStateImplementation.java | 58 +++++++++++++++++++ src/launch/resources/mixins.baritone.json | 1 + 3 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 src/launch/java/baritone/launch/mixins/MixinStateImplementation.java diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index dcfda0f8..5bfabb4c 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -17,16 +17,21 @@ 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; import net.minecraft.util.ResourceLocation; +import net.minecraft.util.Rotation; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; import static java.util.Objects.isNull; @@ -34,12 +39,25 @@ public final class BlockOptionalMeta { private final Block block; private final int meta; private final boolean noMeta; + private final ImmutableSet stateMetas; private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); + private static ImmutableSet getStateMetas(@Nonnull Block block, @Nullable Integer meta) { + List blockstates = block.getBlockState().getValidStates(); + + return ImmutableSet.copyOf( + (ArrayList) blockstates.stream() + .filter(blockstate -> meta == null || block.getMetaFromState(blockstate.withRotation(Rotation.NONE)) == meta) + .map(IBlockState::hashCode) + .collect(Collectors.toCollection(ArrayList::new)) + ); + } + public BlockOptionalMeta(@Nonnull Block block, @Nullable Integer meta) { this.block = block; this.noMeta = isNull(meta); this.meta = noMeta ? 0 : meta; + this.stateMetas = getStateMetas(block, meta); } public BlockOptionalMeta(@Nonnull Block block) { @@ -64,6 +82,7 @@ public final class BlockOptionalMeta { block = Block.REGISTRY.getObject(id); meta = noMeta ? 0 : Integer.parseInt(matchResult.group(2)); + stateMetas = getStateMetas(block, noMeta ? null : meta); } public Block getBlock() { @@ -80,7 +99,7 @@ public final class BlockOptionalMeta { public boolean matches(@Nonnull IBlockState blockstate) { Block block = blockstate.getBlock(); - return block == this.block && (noMeta || block.damageDropped(blockstate) == this.meta); + return block == this.block && stateMetas.contains(blockstate.hashCode()); } @Override diff --git a/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java b/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java new file mode 100644 index 00000000..8d0f770e --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java @@ -0,0 +1,58 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import com.google.common.collect.ImmutableMap; +import net.minecraft.block.properties.IProperty; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +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.callback.CallbackInfo; + +@Mixin(targets = "net.minecraft.block.state.BlockStateContainer$StateImplementation") +public abstract class MixinStateImplementation { + @Shadow + @Final + private ImmutableMap, Comparable> properties; + + /** + * Block states are fucking immutable + */ + @Unique + private int hashCode; + + @Inject(method = "*", at = @At("RETURN")) + private void onInit(CallbackInfo ci) { + hashCode = properties.hashCode(); + } + + /** + * Cache this instead of using the fucking map every time + * + * @author LoganDark + */ + @Override + @Overwrite + public int hashCode() { + return hashCode; + } +} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index c1116279..ff4cc584 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -27,6 +27,7 @@ "MixinNetworkManager", "MixinRenderChunk", "MixinRenderList", + "MixinStateImplementation", "MixinTabCompleter", "MixinVboRenderList", "MixinWorldClient" From 8fc80a285cebefeb10f121b15295774fb162b994 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 18:52:24 -0700 Subject: [PATCH 585/682] Waypoint hashcode + removed one unused line from followcommand --- src/api/java/baritone/api/cache/Waypoint.java | 2 +- .../java/baritone/api/utils/command/defaults/FollowCommand.java | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/cache/Waypoint.java b/src/api/java/baritone/api/cache/Waypoint.java index 2b9a7232..ac57ea34 100644 --- a/src/api/java/baritone/api/cache/Waypoint.java +++ b/src/api/java/baritone/api/cache/Waypoint.java @@ -55,7 +55,7 @@ public class Waypoint implements IWaypoint { @Override public int hashCode() { - return name.hashCode() + tag.hashCode() + location.hashCode(); //lol + return name.hashCode() * tag.hashCode() * location.hashCode(); //lol } @Override diff --git a/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java b/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java index 201346e6..6cfaa59b 100644 --- a/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java @@ -58,7 +58,6 @@ public class FollowCommand extends Command { if (args.hasExactlyOne()) { baritone.getFollowProcess().follow((group = args.getEnum(FollowGroup.class)).filter); - list = null; } else { args.requireMin(2); From 544ae24b64663f298fcf27ed9d8265327c598636 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 19:08:43 -0700 Subject: [PATCH 586/682] YES I DID IT --- src/api/java/baritone/api/utils/Helper.java | 3 +-- src/api/java/baritone/api/utils/IPlayerContext.java | 3 +-- .../java/baritone/api/utils/command/BaritoneChatControl.java | 3 +-- .../api/utils/command/defaults/PauseResumeCommands.java | 3 +-- .../api/utils/command/helpers/arguments/ArgConsumer.java | 3 +-- 5 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/api/java/baritone/api/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java index 7b36a716..9bb573be 100755 --- a/src/api/java/baritone/api/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -36,8 +36,7 @@ public interface Helper { /** * Instance of {@link Helper}. Used for static-context reference. */ - Helper HELPER = new Helper() { - }; + Helper HELPER = new Helper() {}; static ITextComponent getPrefix() { return new TextComponentString("") {{ diff --git a/src/api/java/baritone/api/utils/IPlayerContext.java b/src/api/java/baritone/api/utils/IPlayerContext.java index a9f7cdf7..457af87b 100644 --- a/src/api/java/baritone/api/utils/IPlayerContext.java +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -52,8 +52,7 @@ public interface IPlayerContext { if (world().getBlockState(feet).getBlock() instanceof BlockSlab) { return feet.up(); } - } catch (NullPointerException ignored) { - } + } catch (NullPointerException ignored) {} return feet; } diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index 753f8249..be390e2a 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -112,8 +112,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } else if (msg.trim().equalsIgnoreCase("orderpizza")) { try { ((Lol) mc.currentScreen).openLink(new URI("https://www.dominos.com/en/pages/order/")); - } catch (NullPointerException | URISyntaxException ignored) { - } + } catch (NullPointerException | URISyntaxException ignored) {} return false; } diff --git a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java b/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java index ff8bc783..283aba68 100644 --- a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java +++ b/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java @@ -48,8 +48,7 @@ public class PauseResumeCommands { } @Override - public void onLostControl() { - } + public void onLostControl() {} @Override public double priority() { diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index 9cec8d1f..df20d3b4 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -266,8 +266,7 @@ public class ArgConsumer { return datatype.getConstructor().newInstance().tabComplete(this); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); - } catch (CommandException ignored) { - } + } catch (CommandException ignored) {} return Stream.empty(); } From 4bca6cc1a5b0ecc365683f5b37488449227b3cfa Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 20:43:03 -0700 Subject: [PATCH 587/682] Scan ItemStacks correctly --- .../baritone/api/accessor/IItemStack.java | 5 ++ .../baritone/api/utils/BlockOptionalMeta.java | 51 ++++++++++++---- .../api/utils/BlockOptionalMetaLookup.java | 11 ++++ .../command/defaults/WaypointCommand.java | 53 ---------------- .../launch/mixins/MixinItemStack.java | 61 +++++++++++++++++++ src/launch/resources/mixins.baritone.json | 1 + .../java/baritone/process/MineProcess.java | 5 +- 7 files changed, 120 insertions(+), 67 deletions(-) create mode 100644 src/api/java/baritone/api/accessor/IItemStack.java delete mode 100644 src/api/java/baritone/api/utils/command/defaults/WaypointCommand.java create mode 100644 src/launch/java/baritone/launch/mixins/MixinItemStack.java diff --git a/src/api/java/baritone/api/accessor/IItemStack.java b/src/api/java/baritone/api/accessor/IItemStack.java new file mode 100644 index 00000000..68439905 --- /dev/null +++ b/src/api/java/baritone/api/accessor/IItemStack.java @@ -0,0 +1,5 @@ +package baritone.api.accessor; + +public interface IItemStack { + int getBaritoneHash(); +} diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index 5bfabb4c..836cbbc5 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -17,6 +17,7 @@ package baritone.api.utils; +import baritone.api.accessor.IItemStack; import com.google.common.collect.ImmutableSet; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -26,8 +27,9 @@ import net.minecraft.util.Rotation; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.List; +import java.util.HashSet; +import java.util.Random; +import java.util.Set; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -39,17 +41,35 @@ public final class BlockOptionalMeta { private final Block block; private final int meta; private final boolean noMeta; - private final ImmutableSet stateMetas; + private final Set blockstates; + private final ImmutableSet stateHashes; + private final ImmutableSet stackHashes; private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); - private static ImmutableSet getStateMetas(@Nonnull Block block, @Nullable Integer meta) { - List blockstates = block.getBlockState().getValidStates(); + private static Set getStates(@Nonnull Block block, @Nullable Integer meta) { + return block.getBlockState().getValidStates().stream() + .filter(blockstate -> meta == null || block.getMetaFromState(blockstate.withRotation(Rotation.NONE)) == meta) + .collect(Collectors.toCollection(HashSet::new)); + } + private static ImmutableSet getStateHashes(Set blockstates) { return ImmutableSet.copyOf( - (ArrayList) blockstates.stream() - .filter(blockstate -> meta == null || block.getMetaFromState(blockstate.withRotation(Rotation.NONE)) == meta) + blockstates.stream() .map(IBlockState::hashCode) - .collect(Collectors.toCollection(ArrayList::new)) + .toArray(Integer[]::new) + ); + } + + private static ImmutableSet getStackHashes(Set blockstates) { + //noinspection ConstantConditions + return ImmutableSet.copyOf( + blockstates.stream() + .map(state -> new ItemStack( + state.getBlock().getItemDropped(state, new Random(), 0), + state.getBlock().damageDropped(state) + )) + .map(stack -> ((IItemStack) (Object) stack).getBaritoneHash()) + .toArray(Integer[]::new) ); } @@ -57,7 +77,9 @@ public final class BlockOptionalMeta { this.block = block; this.noMeta = isNull(meta); this.meta = noMeta ? 0 : meta; - this.stateMetas = getStateMetas(block, meta); + this.blockstates = getStates(block, meta); + this.stateHashes = getStateHashes(blockstates); + this.stackHashes = getStackHashes(blockstates); } public BlockOptionalMeta(@Nonnull Block block) { @@ -82,7 +104,9 @@ public final class BlockOptionalMeta { block = Block.REGISTRY.getObject(id); meta = noMeta ? 0 : Integer.parseInt(matchResult.group(2)); - stateMetas = getStateMetas(block, noMeta ? null : meta); + blockstates = getStates(block, noMeta ? null : meta); + stateHashes = getStateHashes(blockstates); + stackHashes = getStackHashes(blockstates); } public Block getBlock() { @@ -99,7 +123,12 @@ public final class BlockOptionalMeta { public boolean matches(@Nonnull IBlockState blockstate) { Block block = blockstate.getBlock(); - return block == this.block && stateMetas.contains(blockstate.hashCode()); + return block == this.block && stateHashes.contains(blockstate.hashCode()); + } + + public boolean matches(ItemStack stack) { + //noinspection ConstantConditions + return stackHashes.contains(((IItemStack) (Object) stack).getBaritoneHash()); } @Override diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index 2457484f..2e7cf42e 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -2,6 +2,7 @@ package baritone.api.utils; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; +import net.minecraft.item.ItemStack; import java.util.Arrays; import java.util.List; @@ -47,6 +48,16 @@ public class BlockOptionalMetaLookup { return false; } + public boolean has(ItemStack stack) { + for (BlockOptionalMeta bom : boms) { + if (bom.matches(stack)) { + return true; + } + } + + return false; + } + public List blocks() { return asList(boms); } diff --git a/src/api/java/baritone/api/utils/command/defaults/WaypointCommand.java b/src/api/java/baritone/api/utils/command/defaults/WaypointCommand.java deleted file mode 100644 index 22438277..00000000 --- a/src/api/java/baritone/api/utils/command/defaults/WaypointCommand.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.utils.command.defaults; - -import baritone.api.Settings; -import baritone.api.utils.command.Command; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; - -import java.util.List; -import java.util.stream.Stream; - -import static java.util.Arrays.asList; - -public class WaypointCommand extends Command { - public WaypointCommand() { - super(asList("name1", "name2"), "Short description"); - } - - @Override - protected void executed(String label, ArgConsumer args, Settings settings) { - ; - } - - @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { - return Stream.empty(); - } - - @Override - public List getLongDesc() { - return asList( - "", - "", - "Usage:", - "> " - ); - } -} diff --git a/src/launch/java/baritone/launch/mixins/MixinItemStack.java b/src/launch/java/baritone/launch/mixins/MixinItemStack.java new file mode 100644 index 00000000..a53e452b --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinItemStack.java @@ -0,0 +1,61 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import baritone.api.accessor.IItemStack; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +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.callback.CallbackInfo; + +@Mixin(ItemStack.class) +public abstract class MixinItemStack implements IItemStack { + @Shadow + @Final + private Item item; + + @Shadow + private int itemDamage; + + @Unique + private int baritoneHash; + + private void recalculateHash() { + baritoneHash = item == null ? -1 : item.hashCode() * itemDamage; + } + + @Inject(method = "*", at = @At("RETURN")) + private void onInit(CallbackInfo ci) { + recalculateHash(); + } + + @Inject(method = "setItemDamage", at = @At("TAIL")) + private void onItemDamageSet(CallbackInfo ci) { + recalculateHash(); + } + + @Override + public int getBaritoneHash() { + return baritoneHash; + } +} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index ff4cc584..0211d1f0 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -22,6 +22,7 @@ "MixinEntityRenderer", "MixinGuiChat", "MixinGuiScreen", + "MixinItemStack", "MixinMinecraft", "MixinNetHandlerPlayClient", "MixinNetworkManager", diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 18c7a7b1..b7eb2bb8 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -91,7 +91,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (desiredQuantity > 0) { int curr = ctx.player().inventory.mainInventory.stream() - .filter(stack -> filter.has(BlockOptionalMeta.blockStateFromStack(stack))) + .filter(stack -> filter.has(stack)) .mapToInt(ItemStack::getCount).sum(); System.out.println("Currently have " + curr + " valid items"); if (curr >= desiredQuantity) { @@ -304,8 +304,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro for (Entity entity : world.loadedEntityList) { if (entity instanceof EntityItem) { EntityItem ei = (EntityItem) entity; - ItemStack stack = ei.getItem(); - if (filter.has(BlockOptionalMeta.blockStateFromStack(stack))) { + if (filter.has(ei.getItem())) { ret.add(new BlockPos(entity)); } } From bb2f4da6b6d63d458dba798fde84f256038b088e Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 20:53:58 -0700 Subject: [PATCH 588/682] Fix baritoneHash calculation --- src/launch/java/baritone/launch/mixins/MixinItemStack.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinItemStack.java b/src/launch/java/baritone/launch/mixins/MixinItemStack.java index a53e452b..4f27152d 100644 --- a/src/launch/java/baritone/launch/mixins/MixinItemStack.java +++ b/src/launch/java/baritone/launch/mixins/MixinItemStack.java @@ -41,7 +41,7 @@ public abstract class MixinItemStack implements IItemStack { private int baritoneHash; private void recalculateHash() { - baritoneHash = item == null ? -1 : item.hashCode() * itemDamage; + baritoneHash = item == null ? -1 : item.hashCode() + itemDamage; } @Inject(method = "*", at = @At("RETURN")) From cf12cbbcf48011525407639264c41e626bbce0b3 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 20:58:22 -0700 Subject: [PATCH 589/682] Don't care about meta in bom if we have none --- .../java/baritone/api/utils/BlockOptionalMeta.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index 836cbbc5..098dc269 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -104,7 +104,7 @@ public final class BlockOptionalMeta { block = Block.REGISTRY.getObject(id); meta = noMeta ? 0 : Integer.parseInt(matchResult.group(2)); - blockstates = getStates(block, noMeta ? null : meta); + blockstates = getStates(block, getMeta()); stateHashes = getStateHashes(blockstates); stackHashes = getStackHashes(blockstates); } @@ -114,7 +114,7 @@ public final class BlockOptionalMeta { } public Integer getMeta() { - return meta; + return noMeta ? null : meta; } public boolean matches(@Nonnull Block block) { @@ -128,12 +128,18 @@ public final class BlockOptionalMeta { public boolean matches(ItemStack stack) { //noinspection ConstantConditions - return stackHashes.contains(((IItemStack) (Object) stack).getBaritoneHash()); + int hash = ((IItemStack) (Object) stack).getBaritoneHash(); + + if (noMeta) { + hash -= stack.getItemDamage(); + } + + return stackHashes.contains(hash); } @Override public String toString() { - return String.format("BlockOptionalMeta{block=%s,meta=%s}", block, meta); + return String.format("BlockOptionalMeta{block=%s,meta=%s}", block, getMeta()); } public static IBlockState blockStateFromStack(ItemStack stack) { From 444cde1ee93da31f2c235d741b7f8feb0ff44f01 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 31 Aug 2019 23:08:51 -0700 Subject: [PATCH 590/682] Improve blockstate filter in BlockOptionalMeta --- .../baritone/api/utils/BlockOptionalMeta.java | 60 ++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index 098dc269..ac817e27 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -20,16 +20,26 @@ package baritone.api.utils; import baritone.api.accessor.IItemStack; import com.google.common.collect.ImmutableSet; import net.minecraft.block.Block; +import net.minecraft.block.BlockDoor; +import net.minecraft.block.BlockDoublePlant; +import net.minecraft.block.BlockLever; +import net.minecraft.block.BlockSlab; +import net.minecraft.block.BlockStairs; +import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Rotation; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import java.util.HashMap; import java.util.HashSet; +import java.util.Map; import java.util.Random; import java.util.Set; +import java.util.function.Consumer; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -45,10 +55,58 @@ public final class BlockOptionalMeta { private final ImmutableSet stateHashes; private final ImmutableSet stackHashes; private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); + private static final Map, Enum> normalizations; + + static { + Map, Enum> _normalizations = new HashMap<>(); + Consumer put = instance -> _normalizations.put(instance.getClass(), instance); + put.accept(EnumFacing.NORTH); + put.accept(EnumFacing.Axis.Y); + put.accept(BlockStairs.EnumHalf.BOTTOM); + put.accept(BlockStairs.EnumShape.STRAIGHT); + put.accept(BlockLever.EnumOrientation.DOWN_X); + put.accept(BlockDoublePlant.EnumBlockHalf.LOWER); + put.accept(BlockSlab.EnumBlockHalf.BOTTOM); + put.accept(BlockDoor.EnumDoorHalf.LOWER); + normalizations = _normalizations; + } + + private static , P extends IProperty> P castToIProperty(Object value) { + //noinspection unchecked + return (P) value; + } + + @SuppressWarnings("unused") + private static , P extends IProperty> C castToIPropertyValue(P iproperty, Object value) { + //noinspection unchecked + return (C) value; + } + + public static IBlockState normalize(IBlockState state) { + IBlockState newState = state; + + for (IProperty property : state.getProperties().keySet()) { + Class valueClass = property.getValueClass(); + if (normalizations.containsKey(valueClass)) { + try { + newState = newState.withProperty( + castToIProperty(property), + castToIPropertyValue(property, normalizations.get(valueClass)) + ); + } catch (IllegalArgumentException ignored) {} + } + } + + return newState; + } + + public static int stateMeta(IBlockState state) { + return state.getBlock().getMetaFromState(normalize(state)); + } private static Set getStates(@Nonnull Block block, @Nullable Integer meta) { return block.getBlockState().getValidStates().stream() - .filter(blockstate -> meta == null || block.getMetaFromState(blockstate.withRotation(Rotation.NONE)) == meta) + .filter(blockstate -> meta == null || stateMeta(blockstate) == meta) .collect(Collectors.toCollection(HashSet::new)); } From 44ec969203eb09142eca2df2aedadda972c5d618 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 00:17:42 -0700 Subject: [PATCH 591/682] yeah --- .../baritone/api/utils/BlockOptionalMeta.java | 127 +++++++++++++++++- 1 file changed, 123 insertions(+), 4 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index ac817e27..90d163d8 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -20,17 +20,40 @@ package baritone.api.utils; import baritone.api.accessor.IItemStack; import com.google.common.collect.ImmutableSet; import net.minecraft.block.Block; +import net.minecraft.block.BlockBanner; +import net.minecraft.block.BlockBed; +import net.minecraft.block.BlockBrewingStand; +import net.minecraft.block.BlockButton; +import net.minecraft.block.BlockChorusPlant; +import net.minecraft.block.BlockDirt; import net.minecraft.block.BlockDoor; import net.minecraft.block.BlockDoublePlant; +import net.minecraft.block.BlockFence; +import net.minecraft.block.BlockFire; +import net.minecraft.block.BlockGrass; +import net.minecraft.block.BlockHorizontal; +import net.minecraft.block.BlockLeaves; import net.minecraft.block.BlockLever; +import net.minecraft.block.BlockLog; +import net.minecraft.block.BlockPane; +import net.minecraft.block.BlockQuartz; +import net.minecraft.block.BlockRailBase; +import net.minecraft.block.BlockRedstoneWire; +import net.minecraft.block.BlockSapling; +import net.minecraft.block.BlockSkull; import net.minecraft.block.BlockSlab; import net.minecraft.block.BlockStairs; +import net.minecraft.block.BlockStandingSign; +import net.minecraft.block.BlockStem; +import net.minecraft.block.BlockTrapDoor; +import net.minecraft.block.BlockTripWire; +import net.minecraft.block.BlockVine; +import net.minecraft.block.BlockWall; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; -import net.minecraft.util.Rotation; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -55,19 +78,101 @@ public final class BlockOptionalMeta { private final ImmutableSet stateHashes; private final ImmutableSet stackHashes; private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); - private static final Map, Enum> normalizations; + private static final Map normalizations; static { - Map, Enum> _normalizations = new HashMap<>(); + Map _normalizations = new HashMap<>(); Consumer put = instance -> _normalizations.put(instance.getClass(), instance); put.accept(EnumFacing.NORTH); put.accept(EnumFacing.Axis.Y); + put.accept(BlockLog.EnumAxis.Y); put.accept(BlockStairs.EnumHalf.BOTTOM); put.accept(BlockStairs.EnumShape.STRAIGHT); put.accept(BlockLever.EnumOrientation.DOWN_X); put.accept(BlockDoublePlant.EnumBlockHalf.LOWER); put.accept(BlockSlab.EnumBlockHalf.BOTTOM); put.accept(BlockDoor.EnumDoorHalf.LOWER); + put.accept(BlockDoor.EnumHingePosition.LEFT); + put.accept(BlockBed.EnumPartType.HEAD); + put.accept(BlockRailBase.EnumRailDirection.NORTH_SOUTH); + put.accept(BlockTrapDoor.DoorHalf.BOTTOM); + _normalizations.put(BlockBanner.ROTATION, 0); + _normalizations.put(BlockBed.OCCUPIED, false); + _normalizations.put(BlockBrewingStand.HAS_BOTTLE[0], false); + _normalizations.put(BlockBrewingStand.HAS_BOTTLE[1], false); + _normalizations.put(BlockBrewingStand.HAS_BOTTLE[2], false); + _normalizations.put(BlockButton.POWERED, false); + // _normalizations.put(BlockCactus.AGE, 0); + // _normalizations.put(BlockCauldron.LEVEL, 0); + // _normalizations.put(BlockChorusFlower.AGE, 0); + _normalizations.put(BlockChorusPlant.NORTH, false); + _normalizations.put(BlockChorusPlant.EAST, false); + _normalizations.put(BlockChorusPlant.SOUTH, false); + _normalizations.put(BlockChorusPlant.WEST, false); + _normalizations.put(BlockChorusPlant.UP, false); + _normalizations.put(BlockChorusPlant.DOWN, false); + // _normalizations.put(BlockCocoa.AGE, 0); + // _normalizations.put(BlockCrops.AGE, 0); + _normalizations.put(BlockDirt.SNOWY, false); + _normalizations.put(BlockDoor.OPEN, false); + _normalizations.put(BlockDoor.POWERED, false); + // _normalizations.put(BlockFarmland.MOISTURE, 0); + _normalizations.put(BlockFence.NORTH, false); + _normalizations.put(BlockFence.EAST, false); + _normalizations.put(BlockFence.WEST, false); + _normalizations.put(BlockFence.SOUTH, false); + // _normalizations.put(BlockFenceGate.POWERED, false); + // _normalizations.put(BlockFenceGate.IN_WALL, false); + _normalizations.put(BlockFire.AGE, 0); + _normalizations.put(BlockFire.NORTH, false); + _normalizations.put(BlockFire.EAST, false); + _normalizations.put(BlockFire.SOUTH, false); + _normalizations.put(BlockFire.WEST, false); + _normalizations.put(BlockFire.UPPER, false); + // _normalizations.put(BlockFrostedIce.AGE, 0); + _normalizations.put(BlockGrass.SNOWY, false); + // _normalizations.put(BlockHopper.ENABLED, true); + // _normalizations.put(BlockLever.POWERED, false); + // _normalizations.put(BlockLiquid.LEVEL, 0); + // _normalizations.put(BlockMycelium.SNOWY, false); + // _normalizations.put(BlockNetherWart.AGE, false); + _normalizations.put(BlockLeaves.CHECK_DECAY, false); + // _normalizations.put(BlockLeaves.DECAYABLE, false); + // _normalizations.put(BlockObserver.POWERED, false); + _normalizations.put(BlockPane.NORTH, false); + _normalizations.put(BlockPane.EAST, false); + _normalizations.put(BlockPane.WEST, false); + _normalizations.put(BlockPane.SOUTH, false); + // _normalizations.put(BlockPistonBase.EXTENDED, false); + // _normalizations.put(BlockPressurePlate.POWERED, false); + // _normalizations.put(BlockPressurePlateWeighted.POWER, false); + _normalizations.put(BlockQuartz.EnumType.LINES_X, BlockQuartz.EnumType.LINES_Y); + _normalizations.put(BlockQuartz.EnumType.LINES_Z, BlockQuartz.EnumType.LINES_Y); + // _normalizations.put(BlockRailDetector.POWERED, false); + // _normalizations.put(BlockRailPowered.POWERED, false); + _normalizations.put(BlockRedstoneWire.NORTH, false); + _normalizations.put(BlockRedstoneWire.EAST, false); + _normalizations.put(BlockRedstoneWire.SOUTH, false); + _normalizations.put(BlockRedstoneWire.WEST, false); + // _normalizations.put(BlockReed.AGE, false); + _normalizations.put(BlockSapling.STAGE, 0); + _normalizations.put(BlockSkull.NODROP, false); + _normalizations.put(BlockStandingSign.ROTATION, 0); + _normalizations.put(BlockStem.AGE, 0); + _normalizations.put(BlockTripWire.NORTH, false); + _normalizations.put(BlockTripWire.EAST, false); + _normalizations.put(BlockTripWire.WEST, false); + _normalizations.put(BlockTripWire.SOUTH, false); + _normalizations.put(BlockVine.NORTH, false); + _normalizations.put(BlockVine.EAST, false); + _normalizations.put(BlockVine.SOUTH, false); + _normalizations.put(BlockVine.WEST, false); + _normalizations.put(BlockVine.UP, false); + _normalizations.put(BlockWall.UP, false); + _normalizations.put(BlockWall.NORTH, false); + _normalizations.put(BlockWall.EAST, false); + _normalizations.put(BlockWall.WEST, false); + _normalizations.put(BlockWall.SOUTH, false); normalizations = _normalizations; } @@ -87,7 +192,21 @@ public final class BlockOptionalMeta { for (IProperty property : state.getProperties().keySet()) { Class valueClass = property.getValueClass(); - if (normalizations.containsKey(valueClass)) { + if (normalizations.containsKey(property)) { + try { + newState = newState.withProperty( + castToIProperty(property), + castToIPropertyValue(property, normalizations.get(property)) + ); + } catch (IllegalArgumentException ignored) {} + } else if (normalizations.containsKey(state.getValue(property))) { + try { + newState = newState.withProperty( + castToIProperty(property), + castToIPropertyValue(property, normalizations.get(state.getValue(property))) + ); + } catch (IllegalArgumentException ignored) {} + } else if (normalizations.containsKey(valueClass)) { try { newState = newState.withProperty( castToIProperty(property), From 445037b614a1cd8078bb0f8d7565aa3342bfd9d0 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 09:47:27 -0700 Subject: [PATCH 592/682] Coordinate censoring --- src/api/java/baritone/api/Settings.java | 10 +++++++ src/api/java/baritone/api/cache/Waypoint.java | 8 +++++- .../baritone/api/pathing/goals/GoalBlock.java | 8 +++++- .../api/pathing/goals/GoalGetToBlock.java | 8 +++++- .../baritone/api/pathing/goals/GoalNear.java | 14 +++++----- .../api/pathing/goals/GoalRunAway.java | 7 ++++- .../pathing/goals/GoalStrictDirection.java | 16 ++++++----- .../api/pathing/goals/GoalTwoBlocks.java | 8 +++++- .../baritone/api/pathing/goals/GoalXZ.java | 7 ++++- .../api/pathing/goals/GoalYLevel.java | 6 ++++- .../baritone/api/utils/BetterBlockPos.java | 27 +++++++++++++++++++ .../api/utils/ExampleBaritoneControlOld.java | 2 +- .../java/baritone/api/utils/SettingsUtil.java | 9 +++++++ .../utils/command/BaritoneChatControl.java | 16 ++++++----- .../utils/command/defaults/ChestsCommand.java | 4 ++- .../baritone/behavior/MemoryBehavior.java | 8 +++--- 16 files changed, 127 insertions(+), 31 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 6ff01352..316d6e47 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -616,6 +616,16 @@ public final class Settings { */ public final Setting echoCommands = new Setting<>(true); + /** + * Censor coordinates in goals and block positions + */ + public final Setting censorCoordinates = new Setting<>(false); + + /** + * Censor arguments to ran commands, to hide, for example, coordinates to #goal + */ + public final Setting censorRanCommands = new Setting<>(false); + /** * Don't stop walking forward when you need to break blocks in your way */ diff --git a/src/api/java/baritone/api/cache/Waypoint.java b/src/api/java/baritone/api/cache/Waypoint.java index ac57ea34..720e835e 100644 --- a/src/api/java/baritone/api/cache/Waypoint.java +++ b/src/api/java/baritone/api/cache/Waypoint.java @@ -17,6 +17,7 @@ package baritone.api.cache; +import baritone.api.utils.BetterBlockPos; import net.minecraft.util.math.BlockPos; import java.util.Date; @@ -80,7 +81,12 @@ public class Waypoint implements IWaypoint { @Override public String toString() { - return name + " " + location.toString() + " " + new Date(creationTimestamp).toString(); + return String.format( + "%s %s %s", + name, + BetterBlockPos.from(location).toString(), + new Date(creationTimestamp).toString() + ); } @Override diff --git a/src/api/java/baritone/api/pathing/goals/GoalBlock.java b/src/api/java/baritone/api/pathing/goals/GoalBlock.java index 89dd6304..55385f46 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.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -67,7 +68,12 @@ public class GoalBlock implements Goal, IGoalRenderPos { @Override public String toString() { - return "GoalBlock{x=" + x + ",y=" + y + ",z=" + z + "}"; + return String.format( + "GoalBlock{x=%s,y=%s,z=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z) + ); } /** diff --git a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java index fb2a07aa..6bf4d026 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.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -61,6 +62,11 @@ public class GoalGetToBlock implements Goal, IGoalRenderPos { @Override public String toString() { - return "GoalGetToBlock{x=" + x + ",y=" + y + ",z=" + z + "}"; + return String.format( + "GoalGetToBlock{x=%s,y=%s,z=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z) + ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalNear.java b/src/api/java/baritone/api/pathing/goals/GoalNear.java index 4f75aba7..94a02ba5 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.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -56,11 +57,12 @@ public class GoalNear implements Goal, IGoalRenderPos { @Override public String toString() { - return "GoalNear{" + - "x=" + x + - ", y=" + y + - ", z=" + z + - ", rangeSq=" + rangeSq + - "}"; + return String.format( + "GoalNear{x=%s, y=%s, z=%s, rangeSq=%d}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z), + rangeSq + ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index 3f4a02de..85e294a3 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -17,6 +17,7 @@ package baritone.api.pathing.goals; +import baritone.api.utils.SettingsUtil; import net.minecraft.util.math.BlockPos; import java.util.Arrays; @@ -82,7 +83,11 @@ public class GoalRunAway implements Goal { @Override public String toString() { if (maintainY != null) { - return "GoalRunAwayFromMaintainY y=" + maintainY + ", " + Arrays.asList(from); + return String.format( + "GoalRunAwayFromMaintainY y=%s, %s", + SettingsUtil.possiblyCensorCoordinate(maintainY), + Arrays.asList(from) + ); } else { return "GoalRunAwayFrom" + Arrays.asList(from); } diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java index 24ae385a..167a00a6 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.SettingsUtil; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -64,12 +65,13 @@ public class GoalStrictDirection implements Goal { @Override public String toString() { - return "GoalStrictDirection{" + - "x=" + x + - ", y=" + y + - ", z=" + z + - ", dx=" + dx + - ", dz=" + dz + - "}"; + return String.format( + "GoalStrictDirection{x=%s, y=%s, z=%s, dx=%s, dz=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z), + SettingsUtil.possiblyCensorCoordinate(dx), + SettingsUtil.possiblyCensorCoordinate(dz) + ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java index f1026ab5..d0b51e17 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.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -73,6 +74,11 @@ public class GoalTwoBlocks implements Goal, IGoalRenderPos { @Override public String toString() { - return "GoalTwoBlocks{x=" + x + ",y=" + y + ",z=" + z + "}"; + return String.format( + "GoalTwoBlocks{x=%s,y=%s,z=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z) + ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalXZ.java b/src/api/java/baritone/api/pathing/goals/GoalXZ.java index 86511b54..aeb301b0 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalXZ.java +++ b/src/api/java/baritone/api/pathing/goals/GoalXZ.java @@ -19,6 +19,7 @@ package baritone.api.pathing.goals; import baritone.api.BaritoneAPI; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.SettingsUtil; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; @@ -65,7 +66,11 @@ public class GoalXZ implements Goal { @Override public String toString() { - return "GoalXZ{x=" + x + ",z=" + z + "}"; + return String.format( + "GoalXZ{x=%s,z=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(z) + ); } public static double calculate(double xDiff, double zDiff) { diff --git a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java index 9add7176..fed62c74 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java +++ b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java @@ -18,6 +18,7 @@ package baritone.api.pathing.goals; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.utils.SettingsUtil; /** * Useful for mining (getting to diamond / iron level) @@ -59,6 +60,9 @@ public class GoalYLevel implements Goal, ActionCosts { @Override public String toString() { - return "GoalYLevel{y=" + level + "}"; + return String.format( + "GoalYLevel{y=%s}", + SettingsUtil.possiblyCensorCoordinate(level) + ); } } diff --git a/src/api/java/baritone/api/utils/BetterBlockPos.java b/src/api/java/baritone/api/utils/BetterBlockPos.java index 3b94a833..b0f536e5 100644 --- a/src/api/java/baritone/api/utils/BetterBlockPos.java +++ b/src/api/java/baritone/api/utils/BetterBlockPos.java @@ -22,6 +22,8 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3i; +import javax.annotation.Nonnull; + /** * A better BlockPos that has fewer hash collisions (and slightly more performant offsets) *

@@ -51,6 +53,20 @@ public final class BetterBlockPos extends BlockPos { this(pos.getX(), pos.getY(), pos.getZ()); } + /** + * Like constructor but returns null if pos is null, good if you just need to possibly censor coordinates + * + * @param pos The BlockPos, possibly null, to convert + * @return A BetterBlockPos or null if pos was null + */ + public static BetterBlockPos from(BlockPos pos) { + if (pos == null) { + return null; + } + + return new BetterBlockPos(pos); + } + @Override public int hashCode() { return (int) longHash(x, y, z); @@ -182,4 +198,15 @@ public final class BetterBlockPos extends BlockPos { public BetterBlockPos west(int amt) { return amt == 0 ? this : new BetterBlockPos(x - amt, y, z); } + + @Override + @Nonnull + public String toString() { + return String.format( + "BetterBlockPos{x=%s,y=%s,z=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z) + ); + } } diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java b/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java index e37dea19..56f6976b 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java @@ -386,7 +386,7 @@ public class ExampleBaritoneControlOld implements Helper, AbstractGameEventListe } if (msg.equals("chests")) { for (Map.Entry entry : baritone.getWorldProvider().getCurrentWorld().getContainerMemory().getRememberedInventories().entrySet()) { - logDirect(entry.getKey() + ""); + logDirect(BetterBlockPos.from(entry.getKey()) + ""); log(entry.getValue().getContents()); } return true; diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 17387aa0..3a2f4f1f 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -17,6 +17,7 @@ package baritone.api.utils; +import baritone.api.BaritoneAPI; import baritone.api.Settings; import net.minecraft.block.Block; import net.minecraft.item.Item; @@ -145,6 +146,14 @@ public class SettingsUtil { return settingValueToString(setting, setting.defaultValue); } + public static String possiblyCensorCoordinate(int coord) { + if (BaritoneAPI.getSettings().censorCoordinates.value) { + return ""; + } + + return Integer.toString(coord); + } + public static String settingToString(Settings.Setting setting) throws IllegalStateException { if (setting.getName().equals("logger")) { return "logger"; diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index be390e2a..a06887b2 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -88,9 +88,11 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } } - private void logRanCommand(String msg) { + private void logRanCommand(String command, String rest) { if (settings.echoCommands.value) { - logDirect(new TextComponentString(String.format("> %s", msg)) {{ + String msg = command + rest; + String toDisplay = settings.censorRanCommands.value ? command + " ..." : msg; + logDirect(new TextComponentString(String.format("> %s", toDisplay)) {{ getStyle() .setColor(TextFormatting.WHITE) .setHoverEvent(new HoverEvent( @@ -122,6 +124,8 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } Pair> pair = CommandExecution.expand(msg); + String command = pair.first(); + String rest = msg.substring(pair.first().length()); ArgConsumer argc = new ArgConsumer(pair.second()); if (!argc.has()) { @@ -130,8 +134,8 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { continue; } - if (setting.getName().equalsIgnoreCase(pair.first())) { - logRanCommand(msg); + if (setting.getName().equalsIgnoreCase(command)) { + logRanCommand(command, rest); if (setting.getValueClass() == Boolean.class) { CommandManager.execute(String.format("set toggle %s", setting.getName())); @@ -149,7 +153,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } if (setting.getName().equalsIgnoreCase(pair.first())) { - logRanCommand(msg); + logRanCommand(command, rest); CommandManager.execute(String.format("set %s %s", setting.getName(), argc.getString())); return true; } @@ -162,7 +166,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { return false; } - logRanCommand(msg); + logRanCommand(command, rest); CommandManager.execute(execution); return true; diff --git a/src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java b/src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java index 300cf974..a9ca11fb 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java @@ -19,6 +19,7 @@ package baritone.api.utils.command.defaults; import baritone.api.Settings; import baritone.api.cache.IRememberedInventory; +import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -49,7 +50,8 @@ public class ChestsCommand extends Command { } for (Map.Entry entry : entries) { - BlockPos pos = entry.getKey(); + // betterblockpos has censoring + BetterBlockPos pos = new BetterBlockPos(entry.getKey()); IRememberedInventory inv = entry.getValue(); logDirect(pos.toString()); diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index d98e3237..5caee6a3 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -24,6 +24,7 @@ import baritone.api.event.events.PacketEvent; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.TickEvent; import baritone.api.event.events.type.EventState; +import baritone.api.utils.BetterBlockPos; import baritone.cache.ContainerMemory; import baritone.utils.BlockStateInterface; import net.minecraft.block.Block; @@ -99,8 +100,8 @@ public final class MemoryBehavior extends Behavior { TileEntityLockable lockable = (TileEntityLockable) tileEntity; int size = lockable.getSizeInventory(); - BlockPos position = tileEntity.getPos(); - BlockPos adj = neighboringConnectedBlock(position); + BetterBlockPos position = BetterBlockPos.from(tileEntity.getPos()); + BetterBlockPos adj = BetterBlockPos.from(neighboringConnectedBlock(position)); System.out.println(position + " " + adj); if (adj != null) { size *= 2; // double chest or double trapped chest @@ -239,7 +240,8 @@ public final class MemoryBehavior extends Behavior { this.slots = slots; this.type = type; this.pos = pos; - System.out.println("Future inventory created " + time + " " + slots + " " + type + " " + pos); + // betterblockpos has censoring + System.out.println("Future inventory created " + time + " " + slots + " " + type + " " + BetterBlockPos.from(pos)); } } From ef380518267557cebfc270e346b67cabbe4a20ca Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 09:47:27 -0700 Subject: [PATCH 593/682] Coordinate censoring --- src/api/java/baritone/api/Settings.java | 5 ++++ src/api/java/baritone/api/cache/Waypoint.java | 8 +++++- .../baritone/api/pathing/goals/GoalBlock.java | 8 +++++- .../api/pathing/goals/GoalGetToBlock.java | 8 +++++- .../baritone/api/pathing/goals/GoalNear.java | 14 +++++----- .../api/pathing/goals/GoalRunAway.java | 7 ++++- .../pathing/goals/GoalStrictDirection.java | 16 ++++++----- .../api/pathing/goals/GoalTwoBlocks.java | 8 +++++- .../baritone/api/pathing/goals/GoalXZ.java | 7 ++++- .../api/pathing/goals/GoalYLevel.java | 6 ++++- .../baritone/api/utils/BetterBlockPos.java | 27 +++++++++++++++++++ .../api/utils/ExampleBaritoneControl.java | 2 +- .../java/baritone/api/utils/SettingsUtil.java | 9 +++++++ .../baritone/behavior/MemoryBehavior.java | 8 +++--- 14 files changed, 109 insertions(+), 24 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 80dcf5ce..0f87349c 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -596,6 +596,11 @@ public final class Settings { */ public final Setting prefixControl = new Setting<>(true); + /** + * Censor coordinates in goals and block positions + */ + public final Setting censorCoordinates = new Setting<>(false); + /** * Don't stop walking forward when you need to break blocks in your way */ diff --git a/src/api/java/baritone/api/cache/Waypoint.java b/src/api/java/baritone/api/cache/Waypoint.java index 2b9a7232..357028d2 100644 --- a/src/api/java/baritone/api/cache/Waypoint.java +++ b/src/api/java/baritone/api/cache/Waypoint.java @@ -17,6 +17,7 @@ package baritone.api.cache; +import baritone.api.utils.BetterBlockPos; import net.minecraft.util.math.BlockPos; import java.util.Date; @@ -80,7 +81,12 @@ public class Waypoint implements IWaypoint { @Override public String toString() { - return name + " " + location.toString() + " " + new Date(creationTimestamp).toString(); + return String.format( + "%s %s %s", + name, + BetterBlockPos.from(location).toString(), + new Date(creationTimestamp).toString() + ); } @Override diff --git a/src/api/java/baritone/api/pathing/goals/GoalBlock.java b/src/api/java/baritone/api/pathing/goals/GoalBlock.java index 89dd6304..55385f46 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.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -67,7 +68,12 @@ public class GoalBlock implements Goal, IGoalRenderPos { @Override public String toString() { - return "GoalBlock{x=" + x + ",y=" + y + ",z=" + z + "}"; + return String.format( + "GoalBlock{x=%s,y=%s,z=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z) + ); } /** diff --git a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java index fb2a07aa..6bf4d026 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.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -61,6 +62,11 @@ public class GoalGetToBlock implements Goal, IGoalRenderPos { @Override public String toString() { - return "GoalGetToBlock{x=" + x + ",y=" + y + ",z=" + z + "}"; + return String.format( + "GoalGetToBlock{x=%s,y=%s,z=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z) + ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalNear.java b/src/api/java/baritone/api/pathing/goals/GoalNear.java index 4f75aba7..94a02ba5 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.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -56,11 +57,12 @@ public class GoalNear implements Goal, IGoalRenderPos { @Override public String toString() { - return "GoalNear{" + - "x=" + x + - ", y=" + y + - ", z=" + z + - ", rangeSq=" + rangeSq + - "}"; + return String.format( + "GoalNear{x=%s, y=%s, z=%s, rangeSq=%d}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z), + rangeSq + ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index 3f4a02de..85e294a3 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -17,6 +17,7 @@ package baritone.api.pathing.goals; +import baritone.api.utils.SettingsUtil; import net.minecraft.util.math.BlockPos; import java.util.Arrays; @@ -82,7 +83,11 @@ public class GoalRunAway implements Goal { @Override public String toString() { if (maintainY != null) { - return "GoalRunAwayFromMaintainY y=" + maintainY + ", " + Arrays.asList(from); + return String.format( + "GoalRunAwayFromMaintainY y=%s, %s", + SettingsUtil.possiblyCensorCoordinate(maintainY), + Arrays.asList(from) + ); } else { return "GoalRunAwayFrom" + Arrays.asList(from); } diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java index 24ae385a..167a00a6 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.SettingsUtil; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -64,12 +65,13 @@ public class GoalStrictDirection implements Goal { @Override public String toString() { - return "GoalStrictDirection{" + - "x=" + x + - ", y=" + y + - ", z=" + z + - ", dx=" + dx + - ", dz=" + dz + - "}"; + return String.format( + "GoalStrictDirection{x=%s, y=%s, z=%s, dx=%s, dz=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z), + SettingsUtil.possiblyCensorCoordinate(dx), + SettingsUtil.possiblyCensorCoordinate(dz) + ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java index f1026ab5..d0b51e17 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.SettingsUtil; import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; @@ -73,6 +74,11 @@ public class GoalTwoBlocks implements Goal, IGoalRenderPos { @Override public String toString() { - return "GoalTwoBlocks{x=" + x + ",y=" + y + ",z=" + z + "}"; + return String.format( + "GoalTwoBlocks{x=%s,y=%s,z=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z) + ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalXZ.java b/src/api/java/baritone/api/pathing/goals/GoalXZ.java index 7f8d16ab..44e58a60 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalXZ.java +++ b/src/api/java/baritone/api/pathing/goals/GoalXZ.java @@ -18,6 +18,7 @@ package baritone.api.pathing.goals; import baritone.api.BaritoneAPI; +import baritone.api.utils.SettingsUtil; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; @@ -59,7 +60,11 @@ public class GoalXZ implements Goal { @Override public String toString() { - return "GoalXZ{x=" + x + ",z=" + z + "}"; + return String.format( + "GoalXZ{x=%s,z=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(z) + ); } public static double calculate(double xDiff, double zDiff) { diff --git a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java index 9add7176..fed62c74 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java +++ b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java @@ -18,6 +18,7 @@ package baritone.api.pathing.goals; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.utils.SettingsUtil; /** * Useful for mining (getting to diamond / iron level) @@ -59,6 +60,9 @@ public class GoalYLevel implements Goal, ActionCosts { @Override public String toString() { - return "GoalYLevel{y=" + level + "}"; + return String.format( + "GoalYLevel{y=%s}", + SettingsUtil.possiblyCensorCoordinate(level) + ); } } diff --git a/src/api/java/baritone/api/utils/BetterBlockPos.java b/src/api/java/baritone/api/utils/BetterBlockPos.java index 3b94a833..b0f536e5 100644 --- a/src/api/java/baritone/api/utils/BetterBlockPos.java +++ b/src/api/java/baritone/api/utils/BetterBlockPos.java @@ -22,6 +22,8 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3i; +import javax.annotation.Nonnull; + /** * A better BlockPos that has fewer hash collisions (and slightly more performant offsets) *

@@ -51,6 +53,20 @@ public final class BetterBlockPos extends BlockPos { this(pos.getX(), pos.getY(), pos.getZ()); } + /** + * Like constructor but returns null if pos is null, good if you just need to possibly censor coordinates + * + * @param pos The BlockPos, possibly null, to convert + * @return A BetterBlockPos or null if pos was null + */ + public static BetterBlockPos from(BlockPos pos) { + if (pos == null) { + return null; + } + + return new BetterBlockPos(pos); + } + @Override public int hashCode() { return (int) longHash(x, y, z); @@ -182,4 +198,15 @@ public final class BetterBlockPos extends BlockPos { public BetterBlockPos west(int amt) { return amt == 0 ? this : new BetterBlockPos(x - amt, y, z); } + + @Override + @Nonnull + public String toString() { + return String.format( + "BetterBlockPos{x=%s,y=%s,z=%s}", + SettingsUtil.possiblyCensorCoordinate(x), + SettingsUtil.possiblyCensorCoordinate(y), + SettingsUtil.possiblyCensorCoordinate(z) + ); + } } diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java index 16a56667..b56865c5 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControl.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControl.java @@ -372,7 +372,7 @@ public class ExampleBaritoneControl implements Helper, AbstractGameEventListener } if (msg.equals("chests")) { for (Map.Entry entry : baritone.getWorldProvider().getCurrentWorld().getContainerMemory().getRememberedInventories().entrySet()) { - logDirect(entry.getKey() + ""); + logDirect(BetterBlockPos.from(entry.getKey()) + ""); log(entry.getValue().getContents()); } return true; diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 4e659dec..882c8096 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -17,6 +17,7 @@ package baritone.api.utils; +import baritone.api.BaritoneAPI; import baritone.api.Settings; import net.minecraft.block.Block; import net.minecraft.item.Item; @@ -120,6 +121,14 @@ public class SettingsUtil { return modified; } + public static String possiblyCensorCoordinate(int coord) { + if (BaritoneAPI.getSettings().censorCoordinates.value) { + return ""; + } + + return Integer.toString(coord); + } + public static String settingToString(Settings.Setting setting) throws IllegalStateException { if (setting.getName().equals("logger")) { return "logger"; diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index d98e3237..5caee6a3 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -24,6 +24,7 @@ import baritone.api.event.events.PacketEvent; import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.TickEvent; import baritone.api.event.events.type.EventState; +import baritone.api.utils.BetterBlockPos; import baritone.cache.ContainerMemory; import baritone.utils.BlockStateInterface; import net.minecraft.block.Block; @@ -99,8 +100,8 @@ public final class MemoryBehavior extends Behavior { TileEntityLockable lockable = (TileEntityLockable) tileEntity; int size = lockable.getSizeInventory(); - BlockPos position = tileEntity.getPos(); - BlockPos adj = neighboringConnectedBlock(position); + BetterBlockPos position = BetterBlockPos.from(tileEntity.getPos()); + BetterBlockPos adj = BetterBlockPos.from(neighboringConnectedBlock(position)); System.out.println(position + " " + adj); if (adj != null) { size *= 2; // double chest or double trapped chest @@ -239,7 +240,8 @@ public final class MemoryBehavior extends Behavior { this.slots = slots; this.type = type; this.pos = pos; - System.out.println("Future inventory created " + time + " " + slots + " " + type + " " + pos); + // betterblockpos has censoring + System.out.println("Future inventory created " + time + " " + slots + " " + type + " " + BetterBlockPos.from(pos)); } } From 9038310150fde19fb08a0db397af4f8bd708f10c Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 10:06:50 -0700 Subject: [PATCH 594/682] Rename SettingsUtil.possiblyCensorCoordinate to maybeCensor --- src/api/java/baritone/api/pathing/goals/GoalBlock.java | 6 +++--- .../baritone/api/pathing/goals/GoalGetToBlock.java | 6 +++--- src/api/java/baritone/api/pathing/goals/GoalNear.java | 6 +++--- .../java/baritone/api/pathing/goals/GoalRunAway.java | 2 +- .../api/pathing/goals/GoalStrictDirection.java | 10 +++++----- .../java/baritone/api/pathing/goals/GoalTwoBlocks.java | 6 +++--- src/api/java/baritone/api/pathing/goals/GoalXZ.java | 4 ++-- .../java/baritone/api/pathing/goals/GoalYLevel.java | 2 +- src/api/java/baritone/api/utils/BetterBlockPos.java | 6 +++--- src/api/java/baritone/api/utils/SettingsUtil.java | 2 +- 10 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalBlock.java b/src/api/java/baritone/api/pathing/goals/GoalBlock.java index 55385f46..836b47df 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalBlock.java @@ -70,9 +70,9 @@ public class GoalBlock implements Goal, IGoalRenderPos { public String toString() { return String.format( "GoalBlock{x=%s,y=%s,z=%s}", - SettingsUtil.possiblyCensorCoordinate(x), - SettingsUtil.possiblyCensorCoordinate(y), - SettingsUtil.possiblyCensorCoordinate(z) + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) ); } diff --git a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java index 6bf4d026..7fe64a4f 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java @@ -64,9 +64,9 @@ public class GoalGetToBlock implements Goal, IGoalRenderPos { public String toString() { return String.format( "GoalGetToBlock{x=%s,y=%s,z=%s}", - SettingsUtil.possiblyCensorCoordinate(x), - SettingsUtil.possiblyCensorCoordinate(y), - SettingsUtil.possiblyCensorCoordinate(z) + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalNear.java b/src/api/java/baritone/api/pathing/goals/GoalNear.java index 94a02ba5..1482b904 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalNear.java +++ b/src/api/java/baritone/api/pathing/goals/GoalNear.java @@ -59,9 +59,9 @@ public class GoalNear implements Goal, IGoalRenderPos { public String toString() { return String.format( "GoalNear{x=%s, y=%s, z=%s, rangeSq=%d}", - SettingsUtil.possiblyCensorCoordinate(x), - SettingsUtil.possiblyCensorCoordinate(y), - SettingsUtil.possiblyCensorCoordinate(z), + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z), rangeSq ); } diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index 85e294a3..fa9c29fc 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -85,7 +85,7 @@ public class GoalRunAway implements Goal { if (maintainY != null) { return String.format( "GoalRunAwayFromMaintainY y=%s, %s", - SettingsUtil.possiblyCensorCoordinate(maintainY), + SettingsUtil.maybeCensor(maintainY), Arrays.asList(from) ); } else { diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java index 167a00a6..3f14bf24 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java +++ b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java @@ -67,11 +67,11 @@ public class GoalStrictDirection implements Goal { public String toString() { return String.format( "GoalStrictDirection{x=%s, y=%s, z=%s, dx=%s, dz=%s}", - SettingsUtil.possiblyCensorCoordinate(x), - SettingsUtil.possiblyCensorCoordinate(y), - SettingsUtil.possiblyCensorCoordinate(z), - SettingsUtil.possiblyCensorCoordinate(dx), - SettingsUtil.possiblyCensorCoordinate(dz) + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z), + SettingsUtil.maybeCensor(dx), + SettingsUtil.maybeCensor(dz) ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java index d0b51e17..52286dd0 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java +++ b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java @@ -76,9 +76,9 @@ public class GoalTwoBlocks implements Goal, IGoalRenderPos { public String toString() { return String.format( "GoalTwoBlocks{x=%s,y=%s,z=%s}", - SettingsUtil.possiblyCensorCoordinate(x), - SettingsUtil.possiblyCensorCoordinate(y), - SettingsUtil.possiblyCensorCoordinate(z) + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalXZ.java b/src/api/java/baritone/api/pathing/goals/GoalXZ.java index 44e58a60..65d506f8 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalXZ.java +++ b/src/api/java/baritone/api/pathing/goals/GoalXZ.java @@ -62,8 +62,8 @@ public class GoalXZ implements Goal { public String toString() { return String.format( "GoalXZ{x=%s,z=%s}", - SettingsUtil.possiblyCensorCoordinate(x), - SettingsUtil.possiblyCensorCoordinate(z) + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(z) ); } diff --git a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java index fed62c74..84b4cefe 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java +++ b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java @@ -62,7 +62,7 @@ public class GoalYLevel implements Goal, ActionCosts { public String toString() { return String.format( "GoalYLevel{y=%s}", - SettingsUtil.possiblyCensorCoordinate(level) + SettingsUtil.maybeCensor(level) ); } } diff --git a/src/api/java/baritone/api/utils/BetterBlockPos.java b/src/api/java/baritone/api/utils/BetterBlockPos.java index b0f536e5..6a462d0c 100644 --- a/src/api/java/baritone/api/utils/BetterBlockPos.java +++ b/src/api/java/baritone/api/utils/BetterBlockPos.java @@ -204,9 +204,9 @@ public final class BetterBlockPos extends BlockPos { public String toString() { return String.format( "BetterBlockPos{x=%s,y=%s,z=%s}", - SettingsUtil.possiblyCensorCoordinate(x), - SettingsUtil.possiblyCensorCoordinate(y), - SettingsUtil.possiblyCensorCoordinate(z) + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) ); } } diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 882c8096..a562f768 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -121,7 +121,7 @@ public class SettingsUtil { return modified; } - public static String possiblyCensorCoordinate(int coord) { + public static String maybeCensor(int coord) { if (BaritoneAPI.getSettings().censorCoordinates.value) { return ""; } From f1973b14c7b57d97bb466c04feaa50b8e979b6c1 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 10:15:41 -0700 Subject: [PATCH 595/682] Remove MixinBlockPos since we now only log BetterBlockPos --- .../baritone/launch/mixins/MixinBlockPos.java | 49 ------------------- src/launch/resources/mixins.baritone.json | 1 - 2 files changed, 50 deletions(-) delete mode 100644 src/launch/java/baritone/launch/mixins/MixinBlockPos.java diff --git a/src/launch/java/baritone/launch/mixins/MixinBlockPos.java b/src/launch/java/baritone/launch/mixins/MixinBlockPos.java deleted file mode 100644 index b0aa75ba..00000000 --- a/src/launch/java/baritone/launch/mixins/MixinBlockPos.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.launch.mixins; - -import com.google.common.base.MoreObjects; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3i; -import org.spongepowered.asm.mixin.Mixin; - -import javax.annotation.Nonnull; - -/** - * @author Brady - * @since 8/25/2018 - */ -@Mixin(BlockPos.class) -public class MixinBlockPos extends Vec3i { - - public MixinBlockPos(int xIn, int yIn, int zIn) { - super(xIn, yIn, zIn); - } - - /** - * The purpose of this was to ensure a friendly name for when we print raw - * block positions to chat in the context of an obfuscated environment. - * - * @return a string representation of the object. - */ - @Override - @Nonnull - public String toString() { - return MoreObjects.toStringHelper("BlockPos").add("x", this.getX()).add("y", this.getY()).add("z", this.getZ()).toString(); - } -} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index 3b5fa70c..2a38a317 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -9,7 +9,6 @@ }, "client": [ "MixinAnvilChunkLoader", - "MixinBlockPos", "MixinChunkProviderClient", "MixinChunkProviderServer", "MixinChunkRenderContainer", From b96692f2d9ed27417b9da4bafc6290ce52bb9930 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 13:12:06 -0700 Subject: [PATCH 596/682] Save settings... --- .../api/utils/command/defaults/SetCommand.java | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java b/src/api/java/baritone/api/utils/command/defaults/SetCommand.java index 6a23c2a4..d5767de9 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SetCommand.java @@ -52,6 +52,13 @@ public class SetCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { String arg = args.has() ? args.getString().toLowerCase(Locale.US) : "list"; + + if (asList("s", "save").contains(arg)) { + SettingsUtil.save(settings); + logDirect("Settings saved"); + return; + } + boolean viewModified = asList("m", "mod", "modified").contains(arg); boolean viewAll = asList("all", "l", "list").contains(arg); boolean paginate = viewModified | viewAll; @@ -125,6 +132,7 @@ public class SetCommand extends Command { } else if (args.peekString().equalsIgnoreCase("all")) { SettingsUtil.modifiedSettings(settings).forEach(Settings.Setting::reset); logDirect("All settings have been reset to their default values"); + SettingsUtil.save(settings); return; } @@ -205,6 +213,8 @@ public class SetCommand extends Command { logDirect("Warning: Prefixed commands will no longer work. If you want to revert this change, use chat control (if enabled) or click the old value listed above.", TextFormatting.RED); } } + + SettingsUtil.save(settings); } @Override @@ -212,7 +222,7 @@ public class SetCommand extends Command { if (args.has()) { String arg = args.getString(); - if (args.hasExactlyOne()) { + if (args.hasExactlyOne() && !asList("s", "save").contains(args.peekString().toLowerCase(Locale.US))) { if (arg.equalsIgnoreCase("reset")) { return new TabCompleteHelper() .addModifiedSettings() @@ -247,7 +257,7 @@ public class SetCommand extends Command { return new TabCompleteHelper() .addSettings() .sortAlphabetically() - .prepend("list", "modified", "reset", "toggle") + .prepend("list", "modified", "reset", "toggle", "save") .filterPrefix(arg) .stream(); } @@ -269,7 +279,8 @@ public class SetCommand extends Command { "> set - Set the value of a setting", "> set reset all - Reset ALL SETTINGS to their defaults", "> set reset - Reset a setting to its default", - "> set toggle - Toggle a boolean setting" + "> set toggle - Toggle a boolean setting", + "> set save - Save all settings (this is automatic tho)" ); } } From ce329d7fb3d6678d0a24049da303bbbc0876a300 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 14:18:59 -0700 Subject: [PATCH 597/682] Waypoints command --- .../java/baritone/api/cache/IWaypoint.java | 6 +- src/api/java/baritone/api/cache/Waypoint.java | 10 +- .../api/utils/ExampleBaritoneControlOld.java | 4 +- .../command/argparser/DefaultArgParsers.java | 14 + .../utils/command/datatypes/ForWaypoints.java | 108 ++++++ .../command/datatypes/RelativeBlockPos.java | 6 +- .../command/defaults/DefaultCommands.java | 5 +- .../command/defaults/WaypointsCommand.java | 352 ++++++++++++++++++ .../helpers/arguments/ArgConsumer.java | 4 + .../command/helpers/pagination/Paginator.java | 55 ++- .../baritone/behavior/MemoryBehavior.java | 2 +- .../baritone/cache/WaypointCollection.java | 3 +- 12 files changed, 543 insertions(+), 26 deletions(-) create mode 100644 src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/WaypointsCommand.java diff --git a/src/api/java/baritone/api/cache/IWaypoint.java b/src/api/java/baritone/api/cache/IWaypoint.java index 01df2a48..23df5d39 100644 --- a/src/api/java/baritone/api/cache/IWaypoint.java +++ b/src/api/java/baritone/api/cache/IWaypoint.java @@ -17,7 +17,7 @@ package baritone.api.cache; -import net.minecraft.util.math.BlockPos; +import baritone.api.utils.BetterBlockPos; import org.apache.commons.lang3.ArrayUtils; import java.util.Arrays; @@ -60,7 +60,7 @@ public interface IWaypoint { * * @return The block position of this waypoint */ - BlockPos getLocation(); + BetterBlockPos getLocation(); enum Tag { @@ -92,7 +92,7 @@ public interface IWaypoint { /** * The names for the tag, anything that the tag can be referred to as. */ - private final String[] names; + public final String[] names; Tag(String... names) { this.names = names; diff --git a/src/api/java/baritone/api/cache/Waypoint.java b/src/api/java/baritone/api/cache/Waypoint.java index 720e835e..f126de38 100644 --- a/src/api/java/baritone/api/cache/Waypoint.java +++ b/src/api/java/baritone/api/cache/Waypoint.java @@ -32,9 +32,9 @@ public class Waypoint implements IWaypoint { private final String name; private final Tag tag; private final long creationTimestamp; - private final BlockPos location; + private final BetterBlockPos location; - public Waypoint(String name, Tag tag, BlockPos location) { + public Waypoint(String name, Tag tag, BetterBlockPos location) { this(name, tag, location, System.currentTimeMillis()); } @@ -47,7 +47,7 @@ public class Waypoint implements IWaypoint { * @param location The waypoint location * @param creationTimestamp When the waypoint was created */ - public Waypoint(String name, Tag tag, BlockPos location, long creationTimestamp) { + public Waypoint(String name, Tag tag, BetterBlockPos location, long creationTimestamp) { this.name = name; this.tag = tag; this.location = location; @@ -56,7 +56,7 @@ public class Waypoint implements IWaypoint { @Override public int hashCode() { - return name.hashCode() * tag.hashCode() * location.hashCode(); //lol + return name.hashCode() ^ tag.hashCode() ^ location.hashCode() ^ Long.hashCode(creationTimestamp); } @Override @@ -75,7 +75,7 @@ public class Waypoint implements IWaypoint { } @Override - public BlockPos getLocation() { + public BetterBlockPos getLocation() { return this.location; } diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java b/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java index 56f6976b..998a981f 100644 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java +++ b/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java @@ -575,7 +575,7 @@ public class ExampleBaritoneControlOld implements Helper, AbstractGameEventListe } if (msg.startsWith("save")) { String name = msg.substring(4).trim(); - BlockPos pos = ctx.playerFeet(); + BetterBlockPos pos = ctx.playerFeet(); if (name.contains(" ")) { logDirect("Name contains a space, assuming it's in the format 'save waypointName X Y Z'"); String[] parts = name.split(" "); @@ -584,7 +584,7 @@ public class ExampleBaritoneControlOld implements Helper, AbstractGameEventListe return true; } try { - pos = new BlockPos(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3])); + pos = new BetterBlockPos(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3])); } catch (NumberFormatException ex) { logDirect("Unable to parse coordinate integers"); return true; diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index 03d3b5c9..ae80734d 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -39,6 +39,19 @@ public class DefaultArgParsers { } } + public static class LongArgumentParser extends ArgParser implements IArgParser.Stateless { + public static final LongArgumentParser INSTANCE = new LongArgumentParser(); + + public LongArgumentParser() { + super(Long.class); + } + + @Override + public Long parseArg(CommandArgument arg) throws RuntimeException { + return Long.parseLong(arg.value); + } + } + public static class FloatArgumentParser extends ArgParser implements IArgParser.Stateless { public static final FloatArgumentParser INSTANCE = new FloatArgumentParser(); @@ -103,6 +116,7 @@ public class DefaultArgParsers { public static final List> all = Collections.unmodifiableList(asList( IntArgumentParser.INSTANCE, + LongArgumentParser.INSTANCE, FloatArgumentParser.INSTANCE, DoubleArgumentParser.INSTANCE, BooleanArgumentParser.INSTANCE diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java new file mode 100644 index 00000000..6cc358e4 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -0,0 +1,108 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.BaritoneAPI; +import baritone.api.cache.IWaypoint; +import baritone.api.cache.IWaypointCollection; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class ForWaypoints implements IDatatypeFor { + private final IWaypoint[] waypoints; + + public ForWaypoints() { + waypoints = null; + } + + public ForWaypoints(String arg) { + IWaypoint.Tag tag = getTagByName(arg); + waypoints = tag == null ? getWaypointsByName(arg) : getWaypointsByTag(tag); + } + + public ForWaypoints(ArgConsumer consumer) { + this(consumer.getString()); + } + + @Override + public IWaypoint[] get() { + return waypoints; + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + return new TabCompleteHelper() + .append(getWaypointNames()) + .sortAlphabetically() + .prepend(getTagNames()) + .filterPrefix(consumer.getString()) + .stream(); + } + + public static IWaypointCollection waypoints() { + return BaritoneAPI.getProvider() + .getPrimaryBaritone() + .getWorldProvider() + .getCurrentWorld() + .getWaypoints(); + } + + public static String[] getTagNames() { + Set names = new HashSet<>(); + + for (IWaypoint.Tag tag : IWaypoint.Tag.values()) { + names.addAll(asList(tag.names)); + } + + return names.toArray(new String[0]); + } + + public static IWaypoint.Tag getTagByName(String name) { + for (IWaypoint.Tag tag : IWaypoint.Tag.values()) { + for (String alias : tag.names) { + if (alias.equalsIgnoreCase(name)) { + return tag; + } + } + } + + return null; + } + + public static IWaypoint[] getWaypoints() { + return waypoints().getAllWaypoints().stream() + .sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed()) + .toArray(IWaypoint[]::new); + } + + public static String[] getWaypointNames() { + return Arrays.stream(getWaypoints()) + .map(IWaypoint::getName) + .filter(name -> !name.equals("")) + .toArray(String[]::new); + } + + public static IWaypoint[] getWaypointsByTag(IWaypoint.Tag tag) { + return waypoints().getByTag(tag).stream() + .sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed()) + .toArray(IWaypoint[]::new); + } + + public static IWaypoint[] getWaypointsByName(String name) { + Set found = new HashSet<>(); + + for (IWaypoint waypoint : getWaypoints()) { + if (waypoint.getName().equalsIgnoreCase(name)) { + found.add(waypoint); + } + } + + return found.toArray(new IWaypoint[0]); + } +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java index 788986b1..28c86e80 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java @@ -42,11 +42,9 @@ public class RelativeBlockPos implements IDatatypePost. + */ + +package baritone.api.utils.command.defaults; + +import baritone.api.Settings; +import baritone.api.cache.IWaypoint; +import baritone.api.cache.Waypoint; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalBlock; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.ForWaypoints; +import baritone.api.utils.command.datatypes.RelativeBlockPos; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.pagination.Paginator; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.event.ClickEvent; +import net.minecraft.util.text.event.HoverEvent; + +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.stream.Stream; + +import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; +import static java.util.Arrays.asList; + +public class WaypointsCommand extends Command { + public WaypointsCommand() { + super(asList("waypoints", "waypoint", "wp"), "Manage waypoints"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + Action action = args.has() ? Action.getByName(args.getString()) : Action.LIST; + + if (action == null) { + throw new CommandInvalidTypeException(args.consumed(), "an action"); + } + + BiFunction toComponent = (waypoint, _action) -> { + ITextComponent component = new TextComponentString(""); + + ITextComponent tagComponent = new TextComponentString(waypoint.getTag().name() + " "); + tagComponent.getStyle().setColor(TextFormatting.GRAY); + String name = waypoint.getName(); + ITextComponent nameComponent = new TextComponentString(!name.isEmpty() ? name : ""); + nameComponent.getStyle().setColor(!name.isEmpty() ? TextFormatting.GRAY : TextFormatting.DARK_GRAY); + ITextComponent timestamp = new TextComponentString(" @ " + new Date(waypoint.getCreationTimestamp())); + timestamp.getStyle().setColor(TextFormatting.DARK_GRAY); + + component.appendSibling(tagComponent); + component.appendSibling(nameComponent); + component.appendSibling(timestamp); + component.getStyle() + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to select") + )) + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format( + "%s%s %s %s @ %d", + FORCE_COMMAND_PREFIX, + label, + _action.names[0], + waypoint.getTag().names[0], + waypoint.getCreationTimestamp() + )) + ); + + return component; + }; + + Function transform = waypoint -> + toComponent.apply(waypoint, action == Action.LIST ? Action.INFO : action); + + if (action == Action.LIST) { + IWaypoint.Tag tag = args.has() ? ForWaypoints.getTagByName(args.peekString()) : null; + + if (tag != null) { + args.get(); + } + + IWaypoint[] waypoints = tag != null + ? ForWaypoints.getWaypointsByTag(tag) + : ForWaypoints.getWaypoints(); + + if (waypoints.length > 0) { + args.requireMax(1); + Paginator.paginate( + args, + waypoints, + () -> logDirect( + tag != null + ? String.format("All waypoints by tag %s:", tag.name()) + : "All waypoints:" + ), + transform, + String.format( + "%s%s %s%s", + FORCE_COMMAND_PREFIX, + label, + action.names[0], + tag != null ? " " + tag.names[0] : "" + ) + ); + } else { + args.requireMax(0); + throw new CommandInvalidStateException( + tag != null + ? "No waypoints found by that tag" + : "No waypoints found" + ); + } + } else if (action == Action.SAVE) { + IWaypoint.Tag tag = ForWaypoints.getTagByName(args.getString()); + + if (tag == null) { + throw new CommandInvalidStateException(String.format("'%s' is not a tag ", args.consumedString())); + } + + String name = args.has() ? args.getString() : ""; + BetterBlockPos pos = args.has() + ? args.getDatatypePost(RelativeBlockPos.class, ctx.playerFeet()) + : ctx.playerFeet(); + + args.requireMax(0); + + IWaypoint waypoint = new Waypoint(name, tag, pos); + ForWaypoints.waypoints().addWaypoint(waypoint); + + ITextComponent component = new TextComponentString("Waypoint added: "); + component.getStyle().setColor(TextFormatting.GRAY); + component.appendSibling(toComponent.apply(waypoint, Action.INFO)); + logDirect(component); + } else if (action == Action.CLEAR) { + args.requireMax(1); + IWaypoint.Tag tag = ForWaypoints.getTagByName(args.getString()); + IWaypoint[] waypoints = ForWaypoints.getWaypointsByTag(tag); + + for (IWaypoint waypoint : waypoints) { + ForWaypoints.waypoints().removeWaypoint(waypoint); + } + + logDirect(String.format("Cleared %d waypoints", waypoints.length)); + } else { + IWaypoint[] waypoints = args.getDatatypeFor(ForWaypoints.class); + IWaypoint waypoint = null; + + if (args.has() && args.peekString().equals("@")) { + args.requireExactly(2); + args.get(); + long timestamp = args.getAs(Long.class); + + for (IWaypoint iWaypoint : waypoints) { + if (iWaypoint.getCreationTimestamp() == timestamp) { + waypoint = iWaypoint; + break; + } + } + + if (waypoint == null) { + throw new CommandInvalidStateException("Timestamp was specified but no waypoint was found"); + } + } else { + switch (waypoints.length) { + case 0: + throw new CommandInvalidStateException("No waypoints found"); + case 1: + waypoint = waypoints[0]; + } + } + + if (waypoint == null) { + args.requireMax(1); + Paginator.paginate( + args, + waypoints, + () -> logDirect("Multiple waypoints were found:"), + transform, + String.format( + "%s%s %s %s", + FORCE_COMMAND_PREFIX, + label, + action.names[0], + args.consumedString() + ) + ); + } else { + if (action == Action.INFO) { + logDirect(transform.apply(waypoint)); + logDirect(String.format("Position: %s", waypoint.getLocation())); + ITextComponent deleteComponent = new TextComponentString("Click to delete this waypoint"); + deleteComponent.getStyle().setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format( + "%s%s delete %s @ %d", + FORCE_COMMAND_PREFIX, + label, + waypoint.getTag().names[0], + waypoint.getCreationTimestamp() + ) + )); + ITextComponent goalComponent = new TextComponentString("Click to set goal to this waypoint"); + goalComponent.getStyle().setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format( + "%s%s goal %s @ %d", + FORCE_COMMAND_PREFIX, + label, + waypoint.getTag().names[0], + waypoint.getCreationTimestamp() + ) + )); + ITextComponent backComponent = new TextComponentString("Click to return to the waypoints list"); + backComponent.getStyle().setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format( + "%s%s list", + FORCE_COMMAND_PREFIX, + label + ) + )); + logDirect(deleteComponent); + logDirect(goalComponent); + logDirect(backComponent); + } else if (action == Action.DELETE) { + ForWaypoints.waypoints().removeWaypoint(waypoint); + logDirect("That waypoint has successfully been deleted"); + } else if (action == Action.GOAL) { + Goal goal = new GoalBlock(waypoint.getLocation()); + baritone.getCustomGoalProcess().setGoal(goal); + logDirect(String.format("Goal: %s", goal)); + } + } + } + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + if (args.has()) { + if (args.hasExactlyOne()) { + return new TabCompleteHelper() + .append(Action.getAllNames()) + .sortAlphabetically() + .filterPrefix(args.getString()) + .stream(); + } else { + Action action = Action.getByName(args.getString()); + + if (args.hasExactlyOne()) { + if (action == Action.LIST || action == Action.SAVE || action == Action.CLEAR) { + return new TabCompleteHelper() + .append(ForWaypoints.getTagNames()) + .sortAlphabetically() + .filterPrefix(args.getString()) + .stream(); + } else { + return args.tabCompleteDatatype(ForWaypoints.class); + } + } else if (args.has(3) && action == Action.SAVE) { + args.get(); + args.get(); + return args.tabCompleteDatatype(RelativeBlockPos.class); + } + } + } + + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "The waypoint command allows you to manage Baritone's waypoints.", + "", + "Waypoints can be used to mark positions for later. Waypoints are each given a tag and an optional name.", + "", + "Note that the info, delete, and goal commands let you specify a waypoint by tag. If there is more than one waypoint with a certain tag, then they will let you select which waypoint you mean.", + "", + "Usage:", + "> wp [l/list] - List all waypoints.", + "> wp - Save your current position as an unnamed waypoint with the specified tag.", + "> wp - Save the waypoint with the specified name.", + "> wp - Save the waypoint with the specified name and position.", + "> wp - Show info on a waypoint by tag.", + "> wp - Delete a waypoint by tag.", + "> wp - Set a goal to a waypoint by tag." + ); + } + + private enum Action { + LIST("list", "get", "l"), + CLEAR("clear", "c"), + SAVE("save", "s"), + INFO("info", "show", "i"), + DELETE("delete", "d"), + GOAL("goal", "goto", "g"); + + private final String[] names; + + Action(String... names) { + this.names = names; + } + + public static Action getByName(String name) { + for (Action action : Action.values()) { + for (String alias : action.names) { + if (alias.equalsIgnoreCase(name)) { + return action; + } + } + } + + return null; + } + + public static String[] getAllNames() { + Set names = new HashSet<>(); + + for (Action action : Action.values()) { + names.addAll(asList(action.names)); + } + + return names.toArray(new String[0]); + } + } +} diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index df20d3b4..3cf823a0 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -300,6 +300,10 @@ public class ArgConsumer { return consumed.size() > 0 ? consumed.getLast() : CommandArgument.unknown(); } + public String consumedString() { + return consumed().value; + } + @SuppressWarnings("MethodDoesntCallSuperMethod") @Override public ArgConsumer clone() { diff --git a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java index db7942b6..24d0b6a3 100644 --- a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java +++ b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java @@ -29,6 +29,7 @@ import net.minecraft.util.text.event.HoverEvent; import java.util.List; import java.util.function.Function; +import static java.util.Arrays.asList; import static java.util.Objects.nonNull; public class Paginator implements Helper { @@ -40,6 +41,10 @@ public class Paginator implements Helper { this.entries = entries; } + public Paginator(E... entries) { + this.entries = asList(entries); + } + public Paginator setPageSize(int pageSize) { this.pageSize = pageSize; @@ -60,7 +65,7 @@ public class Paginator implements Helper { return this; } - public void display(Function transform, String commandFormat) { + public void display(Function transform, String commandPrefix) { int offset = (page - 1) * pageSize; for (int i = offset; i < offset + pageSize; i++) { @@ -71,8 +76,8 @@ public class Paginator implements Helper { } } - boolean hasPrevPage = nonNull(commandFormat) && validPage(page - 1); - boolean hasNextPage = nonNull(commandFormat) && validPage(page + 1); + boolean hasPrevPage = nonNull(commandPrefix) && validPage(page - 1); + boolean hasNextPage = nonNull(commandPrefix) && validPage(page + 1); logDirect(new TextComponentString("") {{ getStyle().setColor(TextFormatting.GRAY); @@ -82,7 +87,7 @@ public class Paginator implements Helper { getStyle() .setClickEvent(new ClickEvent( ClickEvent.Action.RUN_COMMAND, - String.format(commandFormat, page - 1) + String.format("%s %d", commandPrefix, page - 1) )) .setHoverEvent(new HoverEvent( HoverEvent.Action.SHOW_TEXT, @@ -100,7 +105,7 @@ public class Paginator implements Helper { getStyle() .setClickEvent(new ClickEvent( ClickEvent.Action.RUN_COMMAND, - String.format(commandFormat, page + 1) + commandPrefix + " " + (page + 1) )) .setHoverEvent(new HoverEvent( HoverEvent.Action.SHOW_TEXT, @@ -119,7 +124,7 @@ public class Paginator implements Helper { display(transform, null); } - public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform, String commandFormat) { + public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform, String commandPrefix) { int page = 1; consumer.requireMax(1); @@ -145,18 +150,50 @@ public class Paginator implements Helper { pre.run(); } - pagi.display(transform, commandFormat); + pagi.display(transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform, String commandName) { - paginate(consumer, pagi, null, transform, commandName); + public static void paginate(ArgConsumer consumer, List elems, Runnable pre, Function transform, String commandPrefix) { + paginate(consumer, new Paginator<>(elems), pre, transform, commandPrefix); + } + + public static void paginate(ArgConsumer consumer, T[] elems, Runnable pre, Function transform, String commandPrefix) { + paginate(consumer, asList(elems), pre, transform, commandPrefix); + } + + public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform, String commandPrefix) { + paginate(consumer, pagi, null, transform, commandPrefix); + } + + public static void paginate(ArgConsumer consumer, List elems, Function transform, String commandPrefix) { + paginate(consumer, new Paginator<>(elems), null, transform, commandPrefix); + } + + public static void paginate(ArgConsumer consumer, T[] elems, Function transform, String commandPrefix) { + paginate(consumer, asList(elems), null, transform, commandPrefix); } public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform) { paginate(consumer, pagi, pre, transform, null); } + public static void paginate(ArgConsumer consumer, List elems, Runnable pre, Function transform) { + paginate(consumer, new Paginator<>(elems), pre, transform, null); + } + + public static void paginate(ArgConsumer consumer, T[] elems, Runnable pre, Function transform) { + paginate(consumer, asList(elems), pre, transform, null); + } + public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform) { paginate(consumer, pagi, null, transform, null); } + + public static void paginate(ArgConsumer consumer, List elems, Function transform) { + paginate(consumer, new Paginator<>(elems), null, transform, null); + } + + public static void paginate(ArgConsumer consumer, T[] elems, Function transform) { + paginate(consumer, asList(elems), null, transform, null); + } } diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 5caee6a3..aac6b554 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -160,7 +160,7 @@ public final class MemoryBehavior extends Behavior { @Override public void onBlockInteract(BlockInteractEvent event) { if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(ctx, event.getPos()) instanceof BlockBed) { - baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos())); + baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, BetterBlockPos.from(event.getPos()))); } } diff --git a/src/main/java/baritone/cache/WaypointCollection.java b/src/main/java/baritone/cache/WaypointCollection.java index 18b13b89..448dddd3 100644 --- a/src/main/java/baritone/cache/WaypointCollection.java +++ b/src/main/java/baritone/cache/WaypointCollection.java @@ -20,6 +20,7 @@ package baritone.cache; import baritone.api.cache.IWaypoint; import baritone.api.cache.IWaypointCollection; import baritone.api.cache.Waypoint; +import baritone.api.utils.BetterBlockPos; import net.minecraft.util.math.BlockPos; import java.io.*; @@ -86,7 +87,7 @@ public class WaypointCollection implements IWaypointCollection { int x = in.readInt(); int y = in.readInt(); int z = in.readInt(); - this.waypoints.get(tag).add(new Waypoint(name, tag, new BlockPos(x, y, z), creationTimestamp)); + this.waypoints.get(tag).add(new Waypoint(name, tag, new BetterBlockPos(x, y, z), creationTimestamp)); } } catch (IOException ignored) {} } From 384b9b4704f97780a05a56f52028ad0c12876348 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 14:45:31 -0700 Subject: [PATCH 598/682] Prefer silk touch setting --- src/api/java/baritone/api/Settings.java | 6 ++++ .../pathing/movement/MovementHelper.java | 7 ++-- src/main/java/baritone/utils/ToolSet.java | 34 ++++++++++++------- 3 files changed, 31 insertions(+), 16 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 316d6e47..ebebc4d4 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -626,6 +626,12 @@ public final class Settings { */ public final Setting censorRanCommands = new Setting<>(false); + /** + * Always prefer silk touch tools over regular tools. This will not sacrifice speed, but it will always prefer silk + * touch tools over other tools of the same speed. This includes always choosing ANY silk touch tool over your hand. + */ + public final Setting preferSilkTouch = new Setting<>(false); + /** * Don't stop walking forward when you need to break blocks in your way */ diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index b7dd442d..5bd19bc2 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -18,6 +18,7 @@ package baritone.pathing.movement; import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.MovementStatus; @@ -408,7 +409,7 @@ public interface MovementHelper extends ActionCosts, Helper { * @param b the blockstate to mine */ static void switchToBestToolFor(IPlayerContext ctx, IBlockState b) { - switchToBestToolFor(ctx, b, new ToolSet(ctx.player())); + switchToBestToolFor(ctx, b, new ToolSet(ctx.player()), BaritoneAPI.getSettings().preferSilkTouch.value); } /** @@ -418,8 +419,8 @@ public interface MovementHelper extends ActionCosts, Helper { * @param b the blockstate to mine * @param ts previously calculated ToolSet */ - static void switchToBestToolFor(IPlayerContext ctx, IBlockState b, ToolSet ts) { - ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock()); + static void switchToBestToolFor(IPlayerContext ctx, IBlockState b, ToolSet ts, boolean preferSilkTouch) { + ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock(), preferSilkTouch); } static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) { diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 69a5ae9a..353474b2 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -90,30 +90,38 @@ public class ToolSet { } } + public boolean hasSilkTouch(ItemStack stack) { + return EnchantmentHelper.getEnchantmentLevel(Enchantments.SILK_TOUCH, stack) > 0; + } + /** * Calculate which tool on the hotbar is best for mining * * @param b the blockstate to be mined * @return A byte containing the index in the tools array that worked best */ - public byte getBestSlot(Block b) { + public byte getBestSlot(Block b, boolean preferSilkTouch) { byte best = 0; - double value = Double.NEGATIVE_INFINITY; - int materialCost = Integer.MIN_VALUE; + double highestSpeed = Double.NEGATIVE_INFINITY; + int lowestCost = Integer.MIN_VALUE; + boolean bestSilkTouch = false; IBlockState blockState = b.getDefaultState(); for (byte i = 0; i < 9; i++) { ItemStack itemStack = player.inventory.getStackInSlot(i); - double v = calculateSpeedVsBlock(itemStack, blockState); - if (v > value) { - value = v; + double speed = calculateSpeedVsBlock(itemStack, blockState); + boolean silkTouch = hasSilkTouch(itemStack); + if (speed > highestSpeed) { + highestSpeed = speed; best = i; - materialCost = getMaterialCost(itemStack); - } else if (v == value) { - int c = getMaterialCost(itemStack); - if (c < materialCost) { - value = v; + lowestCost = getMaterialCost(itemStack); + bestSilkTouch = silkTouch; + } else if (speed == highestSpeed) { + int cost = getMaterialCost(itemStack); + if ((cost < lowestCost && (!preferSilkTouch || (!bestSilkTouch && silkTouch)))) { + highestSpeed = speed; best = i; - materialCost = c; + lowestCost = cost; + bestSilkTouch = silkTouch; } } } @@ -127,7 +135,7 @@ public class ToolSet { * @return A double containing the destruction ticks with the best tool */ private double getBestDestructionTime(Block b) { - ItemStack stack = player.inventory.getStackInSlot(getBestSlot(b)); + ItemStack stack = player.inventory.getStackInSlot(getBestSlot(b, false)); return calculateSpeedVsBlock(stack, b.getDefaultState()) * avoidanceMultiplier(b); } From afc575d08078739507dd585039a42f90777990ee Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 14:45:31 -0700 Subject: [PATCH 599/682] Setting to prefer silk touch, fixes #883 --- src/api/java/baritone/api/Settings.java | 6 ++++ .../pathing/movement/MovementHelper.java | 7 ++-- src/main/java/baritone/utils/ToolSet.java | 34 ++++++++++++------- 3 files changed, 31 insertions(+), 16 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 80dcf5ce..bf55bc76 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -596,6 +596,12 @@ public final class Settings { */ public final Setting prefixControl = new Setting<>(true); + /** + * Always prefer silk touch tools over regular tools. This will not sacrifice speed, but it will always prefer silk + * touch tools over other tools of the same speed. This includes always choosing ANY silk touch tool over your hand. + */ + public final Setting preferSilkTouch = new Setting<>(false); + /** * Don't stop walking forward when you need to break blocks in your way */ diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index b7dd442d..5bd19bc2 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -18,6 +18,7 @@ package baritone.pathing.movement; import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.MovementStatus; @@ -408,7 +409,7 @@ public interface MovementHelper extends ActionCosts, Helper { * @param b the blockstate to mine */ static void switchToBestToolFor(IPlayerContext ctx, IBlockState b) { - switchToBestToolFor(ctx, b, new ToolSet(ctx.player())); + switchToBestToolFor(ctx, b, new ToolSet(ctx.player()), BaritoneAPI.getSettings().preferSilkTouch.value); } /** @@ -418,8 +419,8 @@ public interface MovementHelper extends ActionCosts, Helper { * @param b the blockstate to mine * @param ts previously calculated ToolSet */ - static void switchToBestToolFor(IPlayerContext ctx, IBlockState b, ToolSet ts) { - ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock()); + static void switchToBestToolFor(IPlayerContext ctx, IBlockState b, ToolSet ts, boolean preferSilkTouch) { + ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock(), preferSilkTouch); } static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) { diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 69a5ae9a..353474b2 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -90,30 +90,38 @@ public class ToolSet { } } + public boolean hasSilkTouch(ItemStack stack) { + return EnchantmentHelper.getEnchantmentLevel(Enchantments.SILK_TOUCH, stack) > 0; + } + /** * Calculate which tool on the hotbar is best for mining * * @param b the blockstate to be mined * @return A byte containing the index in the tools array that worked best */ - public byte getBestSlot(Block b) { + public byte getBestSlot(Block b, boolean preferSilkTouch) { byte best = 0; - double value = Double.NEGATIVE_INFINITY; - int materialCost = Integer.MIN_VALUE; + double highestSpeed = Double.NEGATIVE_INFINITY; + int lowestCost = Integer.MIN_VALUE; + boolean bestSilkTouch = false; IBlockState blockState = b.getDefaultState(); for (byte i = 0; i < 9; i++) { ItemStack itemStack = player.inventory.getStackInSlot(i); - double v = calculateSpeedVsBlock(itemStack, blockState); - if (v > value) { - value = v; + double speed = calculateSpeedVsBlock(itemStack, blockState); + boolean silkTouch = hasSilkTouch(itemStack); + if (speed > highestSpeed) { + highestSpeed = speed; best = i; - materialCost = getMaterialCost(itemStack); - } else if (v == value) { - int c = getMaterialCost(itemStack); - if (c < materialCost) { - value = v; + lowestCost = getMaterialCost(itemStack); + bestSilkTouch = silkTouch; + } else if (speed == highestSpeed) { + int cost = getMaterialCost(itemStack); + if ((cost < lowestCost && (!preferSilkTouch || (!bestSilkTouch && silkTouch)))) { + highestSpeed = speed; best = i; - materialCost = c; + lowestCost = cost; + bestSilkTouch = silkTouch; } } } @@ -127,7 +135,7 @@ public class ToolSet { * @return A double containing the destruction ticks with the best tool */ private double getBestDestructionTime(Block b) { - ItemStack stack = player.inventory.getStackInSlot(getBestSlot(b)); + ItemStack stack = player.inventory.getStackInSlot(getBestSlot(b, false)); return calculateSpeedVsBlock(stack, b.getDefaultState()) * avoidanceMultiplier(b); } From 0b953a237d4b87b50c8ab5609220a366eb743ed4 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 15:01:02 -0700 Subject: [PATCH 600/682] Fix logic error --- src/main/java/baritone/utils/ToolSet.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 353474b2..921bb613 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -117,7 +117,8 @@ public class ToolSet { bestSilkTouch = silkTouch; } else if (speed == highestSpeed) { int cost = getMaterialCost(itemStack); - if ((cost < lowestCost && (!preferSilkTouch || (!bestSilkTouch && silkTouch)))) { + if (cost < lowestCost && (silkTouch || !bestSilkTouch) || + (preferSilkTouch && !bestSilkTouch && silkTouch)) { highestSpeed = speed; best = i; lowestCost = cost; From 150f7a9fd9b9355bdb5312411cade784197690ed Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 15:18:59 -0700 Subject: [PATCH 601/682] extra parenthesis --- src/main/java/baritone/utils/ToolSet.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 921bb613..860f0577 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -117,7 +117,7 @@ public class ToolSet { bestSilkTouch = silkTouch; } else if (speed == highestSpeed) { int cost = getMaterialCost(itemStack); - if (cost < lowestCost && (silkTouch || !bestSilkTouch) || + if ((cost < lowestCost && (silkTouch || !bestSilkTouch)) || (preferSilkTouch && !bestSilkTouch && silkTouch)) { highestSpeed = speed; best = i; From b405a610bbd3cb9d314bd958fb0d239cd6719a4d Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 15:53:13 -0700 Subject: [PATCH 602/682] ground work for more build commands --- src/main/java/baritone/process/BuilderProcess.java | 4 ++-- .../schematic/{AirSchematic.java => FillSchematic.java} | 9 +++++---- 2 files changed, 7 insertions(+), 6 deletions(-) rename src/main/java/baritone/utils/schematic/{AirSchematic.java => FillSchematic.java} (85%) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 0c37ac16..5fded3f3 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -33,7 +33,7 @@ import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; import baritone.utils.PathingCommandContext; -import baritone.utils.schematic.AirSchematic; +import baritone.utils.schematic.FillSchematic; import baritone.utils.schematic.MapArtSchematic; import baritone.utils.schematic.Schematic; import baritone.utils.schematic.schematica.SchematicaHelper; @@ -132,7 +132,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil int widthX = Math.abs(corner1.getX() - corner2.getX()) + 1; int heightY = Math.abs(corner1.getY() - corner2.getY()) + 1; int lengthZ = Math.abs(corner1.getZ() - corner2.getZ()) + 1; - build("clear area", new AirSchematic(widthX, heightY, lengthZ), origin); + build("clear area", new FillSchematic(widthX, heightY, lengthZ, Blocks.AIR.getDefaultState()), origin); } private static ISchematic parse(NBTTagCompound schematic) { diff --git a/src/main/java/baritone/utils/schematic/AirSchematic.java b/src/main/java/baritone/utils/schematic/FillSchematic.java similarity index 85% rename from src/main/java/baritone/utils/schematic/AirSchematic.java rename to src/main/java/baritone/utils/schematic/FillSchematic.java index fd253105..c9c9e0f5 100644 --- a/src/main/java/baritone/utils/schematic/AirSchematic.java +++ b/src/main/java/baritone/utils/schematic/FillSchematic.java @@ -21,21 +21,22 @@ import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; -public class AirSchematic implements ISchematic { - +public class FillSchematic implements ISchematic { private final int widthX; private final int heightY; private final int lengthZ; + private final IBlockState state; - public AirSchematic(int widthX, int heightY, int lengthZ) { + public FillSchematic(int widthX, int heightY, int lengthZ, IBlockState state) { this.widthX = widthX; this.heightY = heightY; this.lengthZ = lengthZ; + this.state = state; } @Override public IBlockState desiredState(int x, int y, int z) { - return Blocks.AIR.getDefaultState(); + return state; } @Override From 98bb3fba9c177c3baa7f150dfebd405b087d2da9 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Mon, 2 Sep 2019 03:00:21 -0700 Subject: [PATCH 603/682] Pass current blockstate to schematics --- .../java/baritone/api/utils/ISchematic.java | 18 ++-- .../mixins/MixinStateImplementation.java | 2 + .../baritone/behavior/InventoryBehavior.java | 3 +- .../java/baritone/process/BuilderProcess.java | 99 +++++++++++-------- .../utils/schematic/FillSchematic.java | 2 +- .../utils/schematic/MapArtSchematic.java | 4 +- .../baritone/utils/schematic/Schematic.java | 2 +- .../schematica/SchematicAdapter.java | 2 +- 8 files changed, 76 insertions(+), 56 deletions(-) diff --git a/src/api/java/baritone/api/utils/ISchematic.java b/src/api/java/baritone/api/utils/ISchematic.java index 821dc68c..0b2f92d9 100644 --- a/src/api/java/baritone/api/utils/ISchematic.java +++ b/src/api/java/baritone/api/utils/ISchematic.java @@ -36,12 +36,13 @@ public interface ISchematic { * However, in the case of something like a map art, anything that's below the level of the map art doesn't matter, * so this function should return false in that case. (i.e. it doesn't really have to be air below the art blocks) * - * @param x The x position of the block, relative to the origin - * @param y The y position of the block, relative to the origin - * @param z The z position of the block, relative to the origin + * @param x The x position of the block, relative to the origin + * @param y The y position of the block, relative to the origin + * @param z The z position of the block, relative to the origin + * @param currentState The current state of that block in the world, or null * @return Whether or not the specified position is within the bounds of this schematic */ - default boolean inSchematic(int x, int y, int z) { + default boolean inSchematic(int x, int y, int z, IBlockState currentState) { return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ(); } @@ -61,12 +62,13 @@ public interface ISchematic { /** * Returns the desired block state at a given (X, Y, Z) position relative to the origin (0, 0, 0). * - * @param x The x position of the block, relative to the origin - * @param y The y position of the block, relative to the origin - * @param z The z position of the block, relative to the origin + * @param x The x position of the block, relative to the origin + * @param y The y position of the block, relative to the origin + * @param z The z position of the block, relative to the origin + * @param current The current state of that block in the world, or null * @return The desired block state at the specified position */ - IBlockState desiredState(int x, int y, int z); + IBlockState desiredState(int x, int y, int z, IBlockState current); /** * @return The width (X axis length) of this schematic diff --git a/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java b/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java index 8d0f770e..9e2e2396 100644 --- a/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java +++ b/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java @@ -49,6 +49,8 @@ public abstract class MixinStateImplementation { * Cache this instead of using the fucking map every time * * @author LoganDark + * @reason Regular IBlockState generates a new hash every fucking time. This is not needed when scanning millions + * per second */ @Override @Overwrite diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index eface5c0..0d600853 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -28,6 +28,7 @@ import net.minecraft.inventory.ClickType; import net.minecraft.item.*; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; import java.util.ArrayList; import java.util.OptionalInt; @@ -132,7 +133,7 @@ public final class InventoryBehavior extends Behavior { } public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) { - IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z); + IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, ctx.world().getBlockState(new BlockPos(x, y, z))); if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && maybe.equals(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(ctx.world(), ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ, stack.getItem().getMetadata(stack.getMetadata()), ctx.player())))) { return true; // gotem } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 5fded3f3..b3f31059 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -25,7 +25,11 @@ import baritone.api.pathing.goals.GoalGetToBlock; import baritone.api.process.IBuilderProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.api.utils.*; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.ISchematic; +import baritone.api.utils.RayTraceUtils; +import baritone.api.utils.Rotation; +import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -48,17 +52,24 @@ import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.Tuple; -import net.minecraft.util.math.*; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.Vec3i; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; import static baritone.api.pathing.movement.ActionCosts.COST_INF; public final class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { - private HashSet incorrectPositions; private LongOpenHashSet observedCompleted; // positions that are completed even if they're out of render distance and we can't make sure right now private String name; @@ -106,6 +117,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil e.printStackTrace(); return false; } + //noinspection ConstantConditions if (tag == null) { return false; } @@ -144,14 +156,14 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil return schematic != null; } - public IBlockState placeAt(int x, int y, int z) { + public IBlockState placeAt(int x, int y, int z, IBlockState current) { if (!isActive()) { return null; } - if (!schematic.inSchematic(x - origin.getX(), y - origin.getY(), z - origin.getZ())) { + if (!schematic.inSchematic(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current)) { return null; } - IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ()); + IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current); if (state.getBlock() == Blocks.AIR) { return null; } @@ -170,7 +182,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil if (dy == -1 && x == pathStart.x && z == pathStart.z) { continue; // dont mine what we're supported by, but not directly standing on } - IBlockState desired = bcc.getSchematic(x, y, z); + IBlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z)); if (desired == null) { continue; // irrelevant } @@ -188,7 +200,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil return Optional.empty(); } - public class Placement { + public static class Placement { private final int hotbarSelection; private final BlockPos placeAgainst; private final EnumFacing side; @@ -210,7 +222,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil int x = center.x + dx; int y = center.y + dy; int z = center.z + dz; - IBlockState desired = bcc.getSchematic(x, y, z); + IBlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z)); if (desired == null) { continue; // irrelevant } @@ -271,14 +283,14 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil ctx.player().rotationYaw = rot.getYaw(); ctx.player().rotationPitch = rot.getPitch(); IBlockState wouldBePlaced = ((ItemBlock) stack.getItem()).getBlock().getStateForPlacement( - ctx.world(), - result.getBlockPos().offset(result.sideHit), - result.sideHit, - (float) result.hitVec.x - result.getBlockPos().getX(), // as in PlayerControllerMP - (float) result.hitVec.y - result.getBlockPos().getY(), - (float) result.hitVec.z - result.getBlockPos().getZ(), - stack.getItem().getMetadata(stack.getMetadata()), - ctx.player() + ctx.world(), + result.getBlockPos().offset(result.sideHit), + result.sideHit, + (float) result.hitVec.x - result.getBlockPos().getX(), // as in PlayerControllerMP + (float) result.hitVec.y - result.getBlockPos().getY(), + (float) result.hitVec.z - result.getBlockPos().getZ(), + stack.getItem().getMetadata(stack.getMetadata()), + ctx.player() ); ctx.player().rotationYaw = originalYaw; ctx.player().rotationPitch = originalPitch; @@ -292,16 +304,16 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil private static Vec3d[] aabbSideMultipliers(EnumFacing side) { switch (side) { case UP: - return new Vec3d[]{new Vec3d(0.5, 1, 0.5), new Vec3d(0.1, 1, 0.5), new Vec3d(0.9, 1, 0.5), new Vec3d(0.5, 1, 0.1), new Vec3d(0.5, 1, 0.9)}; + return new Vec3d[] {new Vec3d(0.5, 1, 0.5), new Vec3d(0.1, 1, 0.5), new Vec3d(0.9, 1, 0.5), new Vec3d(0.5, 1, 0.1), new Vec3d(0.5, 1, 0.9)}; case DOWN: - return new Vec3d[]{new Vec3d(0.5, 0, 0.5), new Vec3d(0.1, 0, 0.5), new Vec3d(0.9, 0, 0.5), new Vec3d(0.5, 0, 0.1), new Vec3d(0.5, 0, 0.9)}; + return new Vec3d[] {new Vec3d(0.5, 0, 0.5), new Vec3d(0.1, 0, 0.5), new Vec3d(0.9, 0, 0.5), new Vec3d(0.5, 0, 0.1), new Vec3d(0.5, 0, 0.9)}; case NORTH: case SOUTH: case EAST: case WEST: double x = side.getXOffset() == 0 ? 0.5 : (1 + side.getXOffset()) / 2D; double z = side.getZOffset() == 0 ? 0.5 : (1 + side.getZOffset()) / 2D; - return new Vec3d[]{new Vec3d(x, 0.25, z), new Vec3d(x, 0.75, z)}; + return new Vec3d[] {new Vec3d(x, 0.25, z), new Vec3d(x, 0.75, z)}; default: // null throw new IllegalStateException(); } @@ -336,13 +348,13 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } schematic = new ISchematic() { @Override - public IBlockState desiredState(int x, int y, int z) { - return realSchematic.desiredState(x, y, z); + public IBlockState desiredState(int x, int y, int z, IBlockState current) { + return realSchematic.desiredState(x, y, z, current); } @Override - public boolean inSchematic(int x, int y, int z) { - return ISchematic.super.inSchematic(x, y, z) && y >= minYInclusive && y <= maxYInclusive; + public boolean inSchematic(int x, int y, int z, IBlockState currentState) { + return ISchematic.super.inSchematic(x, y, z, currentState) && y >= minYInclusive && y <= maxYInclusive; } @Override @@ -485,7 +497,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil int x = center.x + dx; int y = center.y + dy; int z = center.z + dz; - IBlockState desired = bcc.getSchematic(x, y, z); + IBlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z)); if (desired != null) { // we care about this position BetterBlockPos pos = new BetterBlockPos(x, y, z); @@ -507,15 +519,16 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil for (int y = 0; y < schematic.heightY(); y++) { for (int z = 0; z < schematic.lengthZ(); z++) { for (int x = 0; x < schematic.widthX(); x++) { - if (!schematic.inSchematic(x, y, z)) { - continue; - } int blockX = x + origin.getX(); int blockY = y + origin.getY(); int blockZ = z + origin.getZ(); + IBlockState current = bcc.bsi.get0(x, y, z); + if (!schematic.inSchematic(x, y, z, current)) { + continue; + } if (bcc.bsi.worldContainsLoadedChunk(blockX, blockZ)) { // check if its in render distance, not if its in cache // we can directly observe this block, it is in render distance - if (valid(bcc.bsi.get0(blockX, blockY, blockZ), schematic.desiredState(x, y, z))) { + if (valid(bcc.bsi.get0(blockX, blockY, blockZ), schematic.desiredState(x, y, z, current))) { observedCompleted.add(BetterBlockPos.longHash(blockX, blockY, blockZ)); } else { incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ)); @@ -541,14 +554,14 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } private Goal assemble(BuilderCalculationContext bcc, List approxPlacable) { - List placable = new ArrayList<>(); + List placeable = new ArrayList<>(); List breakable = new ArrayList<>(); List sourceLiquids = new ArrayList<>(); incorrectPositions.forEach(pos -> { IBlockState state = bcc.bsi.get0(pos); if (state.getBlock() instanceof BlockAir) { - if (approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))) { - placable.add(pos); + if (approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z, state))) { + placeable.add(pos); } } else { if (state.getBlock() instanceof BlockLiquid) { @@ -566,8 +579,8 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil List toBreak = new ArrayList<>(); breakable.forEach(pos -> toBreak.add(breakGoal(pos, bcc))); List toPlace = new ArrayList<>(); - placable.forEach(pos -> { - if (!placable.contains(pos.down()) && !placable.contains(pos.down(2))) { + placeable.forEach(pos -> { + if (!placeable.contains(pos.down()) && !placeable.contains(pos.down(2))) { toPlace.add(placementGoal(pos, bcc)); } }); @@ -629,9 +642,11 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) { // TODO can this even happen? return new GoalPlace(pos); } - boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR; + IBlockState current = ctx.world().getBlockState(pos.up()); + boolean allowSameLevel = current.getBlock() != Blocks.AIR; for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) { - if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ()).getBlock(), pos, false, facing, null)) { + //noinspection ConstantConditions + if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ(), current).getBlock(), pos, false, facing, null)) { return new GoalAdjacent(pos, pos.offset(facing), allowSameLevel); } } @@ -754,9 +769,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil this.backtrackCostFavoringCoefficient = 1; } - private IBlockState getSchematic(int x, int y, int z) { - if (schematic.inSchematic(x - originX, y - originY, z - originZ)) { - return schematic.desiredState(x - originX, y - originY, z - originZ); + private IBlockState getSchematic(int x, int y, int z, IBlockState current) { + if (schematic.inSchematic(x - originX, y - originY, z - originZ, current)) { + return schematic.desiredState(x - originX, y - originY, z - originZ, current); } else { return null; } @@ -767,7 +782,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil if (isPossiblyProtected(x, y, z) || !worldBorder.canPlaceAt(x, z)) { // make calculation fail properly if we can't build return COST_INF; } - IBlockState sch = getSchematic(x, y, z); + IBlockState sch = getSchematic(x, y, z, bsi.get0(x, y, z)); if (sch != null) { // TODO this can return true even when allowPlace is off.... is that an issue? if (sch.getBlock() == Blocks.AIR) { @@ -801,7 +816,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil if (!allowBreak || isPossiblyProtected(x, y, z)) { return COST_INF; } - IBlockState sch = getSchematic(x, y, z); + IBlockState sch = getSchematic(x, y, z, bsi.get0(x, y, z)); if (sch != null) { if (sch.getBlock() == Blocks.AIR) { // it should be air diff --git a/src/main/java/baritone/utils/schematic/FillSchematic.java b/src/main/java/baritone/utils/schematic/FillSchematic.java index c9c9e0f5..6bac6ce6 100644 --- a/src/main/java/baritone/utils/schematic/FillSchematic.java +++ b/src/main/java/baritone/utils/schematic/FillSchematic.java @@ -35,7 +35,7 @@ public class FillSchematic implements ISchematic { } @Override - public IBlockState desiredState(int x, int y, int z) { + public IBlockState desiredState(int x, int y, int z, IBlockState current) { return state; } diff --git a/src/main/java/baritone/utils/schematic/MapArtSchematic.java b/src/main/java/baritone/utils/schematic/MapArtSchematic.java index fa1c2d00..32b3292c 100644 --- a/src/main/java/baritone/utils/schematic/MapArtSchematic.java +++ b/src/main/java/baritone/utils/schematic/MapArtSchematic.java @@ -59,8 +59,8 @@ public class MapArtSchematic extends Schematic { } @Override - public boolean inSchematic(int x, int y, int z) { + public boolean inSchematic(int x, int y, int z, IBlockState currentState) { // in map art, we only care about coordinates in or above the art - return super.inSchematic(x, y, z) && y >= heightMap[x][z]; + return super.inSchematic(x, y, z, currentState) && y >= heightMap[x][z]; } } diff --git a/src/main/java/baritone/utils/schematic/Schematic.java b/src/main/java/baritone/utils/schematic/Schematic.java index 55dfb619..3efb2404 100644 --- a/src/main/java/baritone/utils/schematic/Schematic.java +++ b/src/main/java/baritone/utils/schematic/Schematic.java @@ -68,7 +68,7 @@ public class Schematic implements ISchematic { } @Override - public IBlockState desiredState(int x, int y, int z) { + public IBlockState desiredState(int x, int y, int z, IBlockState current) { return states[x][z][y]; } diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java index fd0ace8c..3ba9c314 100644 --- a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java @@ -31,7 +31,7 @@ public final class SchematicAdapter implements ISchematic { } @Override - public IBlockState desiredState(int x, int y, int z) { + public IBlockState desiredState(int x, int y, int z, IBlockState current) { return schematic.getSchematic().getBlockState(new BlockPos(x, y, z)); } From bc0f2b59dae36ca74f91165f4b76b1adf61e34d7 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Mon, 2 Sep 2019 11:29:48 -0700 Subject: [PATCH 604/682] First version of selection stuff; nothing supports it yet --- src/api/java/baritone/api/IBaritone.java | 7 + src/api/java/baritone/api/Settings.java | 35 ++ .../baritone/api/selection/ISelection.java | 73 +++++ .../api/selection/ISelectionManager.java | 52 +++ .../java/baritone/api/utils/IRenderer.java | 88 +++++ .../baritone/api/utils/command/Command.java | 5 +- .../command/defaults/DefaultCommands.java | 3 +- .../utils/command/defaults/SelCommand.java | 160 +++++++++ src/main/java/baritone/Baritone.java | 8 + .../java/baritone/selection/Selection.java | 129 ++++++++ .../baritone/selection/SelectionManager.java | 62 ++++ .../baritone/selection/SelectionRenderer.java | 57 ++++ src/main/java/baritone/utils/GuiClick.java | 3 +- .../java/baritone/utils/PathRenderer.java | 306 +++++++----------- 14 files changed, 800 insertions(+), 188 deletions(-) create mode 100644 src/api/java/baritone/api/selection/ISelection.java create mode 100644 src/api/java/baritone/api/selection/ISelectionManager.java create mode 100644 src/api/java/baritone/api/utils/IRenderer.java create mode 100644 src/api/java/baritone/api/utils/command/defaults/SelCommand.java create mode 100644 src/main/java/baritone/selection/Selection.java create mode 100644 src/main/java/baritone/selection/SelectionManager.java create mode 100644 src/main/java/baritone/selection/SelectionRenderer.java diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index 2c892d98..4ca48c24 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -23,6 +23,7 @@ import baritone.api.cache.IWorldProvider; import baritone.api.event.listener.IEventBus; import baritone.api.pathing.calc.IPathingControlManager; import baritone.api.process.*; +import baritone.api.selection.ISelectionManager; import baritone.api.utils.IInputOverrideHandler; import baritone.api.utils.IPlayerContext; @@ -128,6 +129,12 @@ public interface IBaritone { */ IEventBus getGameEventHandler(); + /** + * @return The {@link ISelectionManager} instance + * @see ISelectionManager + */ + ISelectionManager getSelectionManager(); + /** * Open click */ diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index ebebc4d4..8d649d4b 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -528,6 +528,21 @@ public final class Settings { */ public final Setting renderPathIgnoreDepth = new Setting<>(true); + /** + * Ignore depth when rendering selections + */ + public final Setting renderSelectionIgnoreDepth = new Setting<>(true); + + /** + * Render selections + */ + public final Setting renderSelection = new Setting<>(true); + + /** + * Render selection corners + */ + public final Setting renderSelectionCorners = new Setting<>(true); + /** * Line width of the path when rendered, in pixels */ @@ -538,6 +553,11 @@ public final class Settings { */ public final Setting goalRenderLineWidthPixels = new Setting<>(3F); + /** + * Line width of the goal when rendered, in pixels + */ + public final Setting selectionRenderLineWidthPixels = new Setting<>(3F); + /** * Start fading out the path at 20 movements ahead, and stop rendering it entirely 30 movements ahead. * Improves FPS. @@ -935,6 +955,21 @@ public final class Settings { */ public final Setting colorInvertedGoalBox = new Setting<>(Color.RED); + /** + * The color of all selections + */ + public final Setting colorSelection = new Setting<>(Color.GREEN); + + /** + * The color of the selection pos 1 + */ + public final Setting colorSelectionPos1 = new Setting<>(Color.PINK); + + /** + * The color of the selection pos 2 + */ + public final Setting colorSelectionPos2 = new Setting<>(Color.PINK); + /** * A map of lowercase setting field names to their respective setting diff --git a/src/api/java/baritone/api/selection/ISelection.java b/src/api/java/baritone/api/selection/ISelection.java new file mode 100644 index 00000000..4067c307 --- /dev/null +++ b/src/api/java/baritone/api/selection/ISelection.java @@ -0,0 +1,73 @@ +package baritone.api.selection; + +import baritone.api.utils.BetterBlockPos; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.Vec3i; + +/** + * A selection is an immutable object representing the current selection. The selection is commonly used for certain + * types of build commands, however it can be used for anything. + */ +public interface ISelection { + /** + * @return The first corner of this selection. This is meant to preserve the user's original first corner. + */ + BetterBlockPos pos1(); + + /** + * @return The second corner of this selection. This is meant to preserve the user's original second corner. + */ + BetterBlockPos pos2(); + + /** + * @return The {@link BetterBlockPos} with the lowest x, y, and z position in the selection. + */ + BetterBlockPos min(); + + /** + * @return The opposite corner from the {@link #min()}. + */ + BetterBlockPos max(); + + /** + * @return The size of this ISelection. + */ + Vec3i size(); + + /** + * @return An {@link AxisAlignedBB} encompassing all blocks in this selection. + */ + AxisAlignedBB aabb(); + + /** + * Returns a new {@link ISelection} expanded in the specified direction by the specified number of blocks. + * + * @param direction The direction to expand the selection. + * @param blocks How many blocks to expand it. + * @return A new selection, expanded as specified. + */ + ISelection expand(EnumFacing direction, int blocks); + + /** + * Returns a new {@link ISelection} contracted in the specified direction by the specified number of blocks. + * + * Note that, for example, if the direction specified is UP, the bottom of the selection will be shifted up. If it + * is DOWN, the top of the selection will be shifted down. + * + * @param direction The direction to contract the selection. + * @param blocks How many blocks to contract it. + * @return A new selection, contracted as specified. + */ + ISelection contract(EnumFacing direction, int blocks); + + /** + * Returns a new {@link ISelection} shifted in the specified direction by the specified number of blocks. This moves + * the whole selection. + * + * @param direction The direction to shift the selection. + * @param blocks How many blocks to shift it. + * @return A new selection, shifted as specified. + */ + ISelection shift(EnumFacing direction, int blocks); +} diff --git a/src/api/java/baritone/api/selection/ISelectionManager.java b/src/api/java/baritone/api/selection/ISelectionManager.java new file mode 100644 index 00000000..d7513160 --- /dev/null +++ b/src/api/java/baritone/api/selection/ISelectionManager.java @@ -0,0 +1,52 @@ +package baritone.api.selection; + +import baritone.api.utils.BetterBlockPos; + +/** + * The selection manager handles setting Baritone's selections. You can set the selection here, as well as retrieving + * the current selection. + */ +public interface ISelectionManager { + /** + * Adds a new selection. The added selection is returned. + * + * @param selection The new selection to add. + */ + ISelection addSelection(ISelection selection); + + /** + * Adds a new {@link ISelection} constructed from the given block positions. The new selection is returned. + * + * @param pos1 One corner of the selection + * @param pos2 The new corner of the selection + */ + ISelection addSelection(BetterBlockPos pos1, BetterBlockPos pos2); + + /** + * Removes the selection from the current selections. + * + * @param selection The selection to remove. + * @return The removed selection. + */ + ISelection removeSelection(ISelection selection); + + /** + * Removes all selections. + * + * @return The selections that were removed, sorted from oldest to newest.. + */ + ISelection[] removeAllSelections(); + + /** + * @return The current selections, sorted from oldest to newest. + */ + ISelection[] getSelections(); + + /** + * For anything expecting only one selection, this method is provided. However, to enforce multi-selection support, + * this method will only return a selection if there is ONLY one. + * + * @return The only selection. + */ + ISelection getOnlySelection(); +} diff --git a/src/api/java/baritone/api/utils/IRenderer.java b/src/api/java/baritone/api/utils/IRenderer.java new file mode 100644 index 00000000..48355a14 --- /dev/null +++ b/src/api/java/baritone/api/utils/IRenderer.java @@ -0,0 +1,88 @@ +package baritone.api.utils; + +import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; +import baritone.api.Settings; +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.vertex.DefaultVertexFormats; +import net.minecraft.util.math.AxisAlignedBB; + +import java.awt.Color; + +import static org.lwjgl.opengl.GL11.GL_LINES; +import static org.lwjgl.opengl.GL11.GL_ONE; +import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA; +import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA; +import static org.lwjgl.opengl.GL11.GL_ZERO; + +public interface IRenderer { + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder buffer = tessellator.getBuffer(); + IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone(); + Settings settings = BaritoneAPI.getSettings(); + + static void startLines(Color color, float lineWidth, boolean ignoreDepth) { + GlStateManager.enableBlend(); + GlStateManager.disableLighting(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); + float[] colorComponents = color.getColorComponents(null); + GlStateManager.color(colorComponents[0], colorComponents[1], colorComponents[2], 0.4f); + GlStateManager.glLineWidth(lineWidth); + GlStateManager.disableTexture2D(); + GlStateManager.depthMask(false); + + if (ignoreDepth) { + GlStateManager.disableDepth(); + } + } + + static void endLines(boolean ignoredDepth) { + if (ignoredDepth) { + GlStateManager.enableDepth(); + } + + GlStateManager.depthMask(true); + GlStateManager.enableTexture2D(); + GlStateManager.enableLighting(); + GlStateManager.disableBlend(); + } + + static void drawAABB(AxisAlignedBB aabb) { + float expand = 0.002F; + RenderManager renderManager = Helper.mc.getRenderManager(); + AxisAlignedBB toDraw = aabb.expand(expand, expand, expand).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(); + 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(); + // 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(); + // 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(); + tessellator.draw(); + } +} diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index 26fca9e1..7fa3b2a8 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -20,6 +20,7 @@ package baritone.api.utils.command; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; +import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.api.utils.command.execution.CommandExecution; @@ -34,8 +35,9 @@ import java.util.Locale; import java.util.stream.Collectors; import java.util.stream.Stream; -public abstract class Command implements Helper { +public abstract class Command implements Helper, AbstractGameEventListener { protected IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone(); + protected Settings settings = BaritoneAPI.getSettings(); protected IPlayerContext ctx = baritone.getPlayerContext(); protected Minecraft MC = mc; @@ -60,6 +62,7 @@ public abstract class Command implements Helper { .map(s -> s.toLowerCase(Locale.US)) .collect(Collectors.toCollection(ArrayList::new)); this.shortDesc = shortDesc; + baritone.getGameEventHandler().registerEventListener(this); } protected Command(String name, String shortDesc) { diff --git a/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java b/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java index 1c3f3f10..d640f079 100644 --- a/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java +++ b/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java @@ -64,6 +64,7 @@ public class DefaultCommands { new ThisWayCommand(), new WaypointsCommand(), new CommandAlias("sethome", "Sets your home waypoint", "waypoints save home"), - new CommandAlias("home", "Set goal to your home waypoint", "waypoints goal home") + new CommandAlias("home", "Set goal to your home waypoint", "waypoints goal home"), + new SelCommand() )); } diff --git a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java new file mode 100644 index 00000000..ef66be5e --- /dev/null +++ b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java @@ -0,0 +1,160 @@ +/* + * 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.command.defaults; + +import baritone.api.Settings; +import baritone.api.event.events.RenderEvent; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.IRenderer; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.RelativeBlockPos; +import baritone.api.utils.command.exception.CommandInvalidStateException; +import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import net.minecraft.util.math.AxisAlignedBB; + +import java.awt.Color; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class SelCommand extends Command { + private BetterBlockPos pos1 = null; + + public SelCommand() { + super(asList("sel", "selection", "s"), "WorldEdit-like commands"); + } + + @Override + protected void executed(String label, ArgConsumer args, Settings settings) { + Action action = Action.getByName(args.getString()); + + if (action == null) { + throw new CommandInvalidTypeException(args.consumed(), "an action"); + } + + if (action == Action.POS1 || action == Action.POS2) { + if (action == Action.POS2 && pos1 == null) { + throw new CommandInvalidStateException("Set pos1 first before using pos2"); + } + + BetterBlockPos playerPos = ctx.playerFeet(); + BetterBlockPos pos = args.has() ? args.getDatatypePost(RelativeBlockPos.class, playerPos) : playerPos; + args.requireMax(0); + + if (action == Action.POS1) { + pos1 = pos; + logDirect("Position 1 has been set"); + } else { + baritone.getSelectionManager().addSelection(pos1, pos); + pos1 = null; + logDirect("Selection added"); + } + } else if (action == Action.CLEAR) { + pos1 = null; + logDirect(String.format( + "Removed %d selections", + baritone.getSelectionManager().removeAllSelections().length + )); + } + } + + @Override + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + if (args.hasExactlyOne()) { + return new TabCompleteHelper() + .append(Action.getAllNames()) + .filterPrefix(args.getString()) + .sortAlphabetically() + .stream(); + } else { + Action action = Action.getByName(args.getString()); + + if (action != null) { + if (action == Action.POS1 || action == Action.POS2) { + return args.tabCompleteDatatype(RelativeBlockPos.class); + } + } + } + + return Stream.empty(); + } + + @Override + public List getLongDesc() { + return asList( + "", + "", + "Usage:", + "> " + ); + } + + enum Action { + POS1("pos1", "p1"), + POS2("pos2", "p2"), + CLEAR("clear", "c"); + + private final String[] names; + + Action(String... names) { + this.names = names; + } + + public static Action getByName(String name) { + for (Action action : Action.values()) { + for (String alias : action.names) { + if (alias.equalsIgnoreCase(name)) { + return action; + } + } + } + + return null; + } + + public static String[] getAllNames() { + Set names = new HashSet<>(); + + for (Action action : Action.values()) { + names.addAll(asList(action.names)); + } + + return names.toArray(new String[0]); + } + } + + @Override + public void onRenderPass(RenderEvent event) { + if (!settings.renderSelectionCorners.value || pos1 == null) { + return; + } + + Color color = settings.colorSelectionPos1.value; + float lineWidth = settings.selectionRenderLineWidthPixels.value; + boolean ignoreDepth = settings.renderSelectionIgnoreDepth.value; + + IRenderer.startLines(color, lineWidth, ignoreDepth); + IRenderer.drawAABB(new AxisAlignedBB(pos1, pos1.add(1, 1, 1))); + IRenderer.endLines(ignoreDepth); + } +} diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index d2aae776..a0e19015 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -28,6 +28,7 @@ import baritone.behavior.*; import baritone.cache.WorldProvider; import baritone.event.GameEventHandler; import baritone.process.*; +import baritone.selection.SelectionManager; import baritone.utils.*; import baritone.utils.player.PrimaryPlayerContext; import net.minecraft.client.Minecraft; @@ -83,6 +84,7 @@ public class Baritone implements IBaritone { private FarmProcess farmProcess; private PathingControlManager pathingControlManager; + private SelectionManager selectionManager; private IPlayerContext playerContext; private WorldProvider worldProvider; @@ -125,6 +127,7 @@ public class Baritone implements IBaritone { } this.worldProvider = new WorldProvider(); + this.selectionManager = new SelectionManager(); if (BaritoneAutoTest.ENABLE_AUTO_TEST) { this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE); @@ -203,6 +206,11 @@ public class Baritone implements IBaritone { return this.pathingBehavior; } + @Override + public SelectionManager getSelectionManager() { + return selectionManager; + } + @Override public WorldProvider getWorldProvider() { return this.worldProvider; diff --git a/src/main/java/baritone/selection/Selection.java b/src/main/java/baritone/selection/Selection.java new file mode 100644 index 00000000..68b8021b --- /dev/null +++ b/src/main/java/baritone/selection/Selection.java @@ -0,0 +1,129 @@ +package baritone.selection; + +import baritone.api.selection.ISelection; +import baritone.api.utils.BetterBlockPos; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.Vec3i; + +public class Selection implements ISelection { + private final BetterBlockPos pos1; + private final BetterBlockPos pos2; + private final BetterBlockPos min; + private final BetterBlockPos max; + private final Vec3i size; + private final AxisAlignedBB aabb; + + public Selection(BetterBlockPos pos1, BetterBlockPos pos2) { + this.pos1 = pos1; + this.pos2 = pos2; + + this.min = new BetterBlockPos( + Math.min(pos1.x, pos2.x), + Math.min(pos1.y, pos2.y), + Math.min(pos1.z, pos2.z) + ); + + this.max = new BetterBlockPos( + Math.max(pos1.x, pos2.x), + Math.max(pos1.y, pos2.y), + Math.max(pos1.z, pos2.z) + ); + + this.size = new Vec3i( + max.x - min.x + 1, + max.y - min.y + 1, + max.z - min.z + 1 + ); + + this.aabb = new AxisAlignedBB(this.min, this.max.add(1, 1, 1)); + } + + @Override + public BetterBlockPos pos1() { + return pos1; + } + + @Override + public BetterBlockPos pos2() { + return pos2; + } + + @Override + public BetterBlockPos min() { + return min; + } + + @Override + public BetterBlockPos max() { + return max; + } + + @Override + public Vec3i size() { + return size; + } + + @Override + public AxisAlignedBB aabb() { + return aabb; + } + + @Override + public int hashCode() { + return pos1.hashCode() ^ pos2.hashCode(); + } + + @Override + public String toString() { + return String.format("Selection{pos1=%s,pos2=%s}", pos1, pos2); + } + + /** + * Since it might not be immediately obvious what this does, let me explain. + * + * Let's say you specify EnumFacing.UP, this functions returns if pos2 is the highest BlockPos. + * If you specify EnumFacing.DOWN, it returns if pos2 is the lowest BlockPos. + * + * @param facing The direction to check. + * @return {@code true} if pos2 is further in that direction than pos1, {@code false} if it isn't, and something + * else if they're both at the same position on that axis (it really doesn't matter) + */ + private boolean isPos2(EnumFacing facing) { + boolean negative = facing.getAxisDirection().getOffset() < 0; + + switch (facing.getAxis()) { + case X: + return (pos2.x > pos1.x) ^ negative; + case Y: + return (pos2.y > pos1.y) ^ negative; + case Z: + return (pos2.z > pos1.z) ^ negative; + default: + throw new IllegalStateException("Bad EnumFacing.Axis"); + } + } + + @Override + public ISelection expand(EnumFacing direction, int blocks) { + if (isPos2(direction)) { + return new Selection(pos1, pos2.offset(direction, blocks)); + } else { + return new Selection(pos1.offset(direction, blocks), pos2); + } + } + + @Override + public ISelection contract(EnumFacing direction, int blocks) { + if (isPos2(direction)) { + return new Selection(pos1.offset(direction, -blocks), pos2); + } else { + return new Selection(pos1, pos2.offset(direction, -blocks)); + } + } + + @Override + public ISelection shift(EnumFacing direction, int blocks) { + return new Selection(pos1.offset(direction, blocks), pos2.offset(direction, blocks)); + } +} diff --git a/src/main/java/baritone/selection/SelectionManager.java b/src/main/java/baritone/selection/SelectionManager.java new file mode 100644 index 00000000..b95c60b2 --- /dev/null +++ b/src/main/java/baritone/selection/SelectionManager.java @@ -0,0 +1,62 @@ +package baritone.selection; + +import baritone.api.selection.ISelection; +import baritone.api.selection.ISelectionManager; +import baritone.api.utils.BetterBlockPos; + +import java.util.LinkedHashSet; +import java.util.Set; + +public class SelectionManager implements ISelectionManager { + private final Set selections = new LinkedHashSet<>(); + private ISelection[] selectionsArr = new ISelection[0]; + + public SelectionManager() { + new SelectionRenderer(this); + } + + private void resetSelectionsArr() { + selectionsArr = selections.toArray(new ISelection[0]); + } + + @Override + public synchronized ISelection addSelection(ISelection selection) { + selections.add(selection); + resetSelectionsArr(); + return selection; + } + + @Override + public ISelection addSelection(BetterBlockPos pos1, BetterBlockPos pos2) { + return addSelection(new Selection(pos1, pos2)); + } + + @Override + public synchronized ISelection removeSelection(ISelection selection) { + selections.remove(selection); + resetSelectionsArr(); + return selection; + } + + @Override + public synchronized ISelection[] removeAllSelections() { + ISelection[] selectionsArr = getSelections(); + selections.clear(); + resetSelectionsArr(); + return selectionsArr; + } + + @Override + public ISelection[] getSelections() { + return selectionsArr; + } + + @Override + public synchronized ISelection getOnlySelection() { + if (selections.size() == 1) { + return selections.iterator().next(); + } + + return null; + } +} diff --git a/src/main/java/baritone/selection/SelectionRenderer.java b/src/main/java/baritone/selection/SelectionRenderer.java new file mode 100644 index 00000000..48f8ae49 --- /dev/null +++ b/src/main/java/baritone/selection/SelectionRenderer.java @@ -0,0 +1,57 @@ +package baritone.selection; + +import baritone.api.event.events.RenderEvent; +import baritone.api.event.listener.AbstractGameEventListener; +import baritone.api.selection.ISelection; +import baritone.api.utils.IRenderer; +import net.minecraft.util.math.AxisAlignedBB; + +public class SelectionRenderer implements IRenderer, AbstractGameEventListener { + private final SelectionManager manager; + + SelectionRenderer(SelectionManager manager) { + this.manager = manager; + baritone.getGameEventHandler().registerEventListener(this); + } + + public static void renderSelections(ISelection[] selections) { + boolean ignoreDepth = settings.renderSelectionIgnoreDepth.value; + float lineWidth = settings.selectionRenderLineWidthPixels.value; + + if (!settings.renderSelection.value) { + return; + } + + IRenderer.startLines(settings.colorSelection.value, lineWidth, ignoreDepth); + + for (ISelection selection : selections) { + IRenderer.drawAABB(selection.aabb()); + } + + IRenderer.endLines(ignoreDepth); + + if (!settings.renderSelectionCorners.value) { + return; + } + + IRenderer.startLines(settings.colorSelectionPos1.value, lineWidth, ignoreDepth); + + for (ISelection selection : selections) { + IRenderer.drawAABB(new AxisAlignedBB(selection.pos1(), selection.pos1().add(1, 1, 1))); + } + + IRenderer.endLines(ignoreDepth); + IRenderer.startLines(settings.colorSelectionPos2.value, lineWidth, ignoreDepth); + + for (ISelection selection : selections) { + IRenderer.drawAABB(new AxisAlignedBB(selection.pos2(), selection.pos2().add(1, 1, 1))); + } + + IRenderer.endLines(ignoreDepth); + } + + @Override + public void onRenderPass(RenderEvent event) { + renderSelections(manager.getSelections()); + } +} diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index ce5c28a0..9f805387 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -22,6 +22,7 @@ import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.IRenderer; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; @@ -110,7 +111,7 @@ public class GuiClick extends GuiScreen { GlStateManager.disableDepth(); BetterBlockPos a = new BetterBlockPos(currentMouseOver); BetterBlockPos b = new BetterBlockPos(clickStart); - PathRenderer.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)); + 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); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index cb5e7be0..3de40b91 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -17,20 +17,25 @@ package baritone.utils; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.event.events.RenderEvent; import baritone.api.pathing.calc.IPath; -import baritone.api.pathing.goals.*; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalComposite; +import baritone.api.pathing.goals.GoalGetToBlock; +import baritone.api.pathing.goals.GoalInverted; +import baritone.api.pathing.goals.GoalTwoBlocks; +import baritone.api.pathing.goals.GoalXZ; +import baritone.api.pathing.goals.GoalYLevel; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Helper; +import baritone.api.utils.IRenderer; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.behavior.PathingBehavior; import baritone.pathing.path.PathExecutor; import net.minecraft.block.state.IBlockState; -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.tileentity.TileEntityBeaconRenderer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.Entity; @@ -39,29 +44,30 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; -import java.awt.*; +import java.awt.Color; import java.util.Collection; import java.util.Collections; import java.util.List; -import static org.lwjgl.opengl.GL11.*; +import static org.lwjgl.opengl.GL11.GL_LIGHTING_BIT; +import static org.lwjgl.opengl.GL11.GL_LINES; +import static org.lwjgl.opengl.GL11.GL_LINE_LOOP; +import static org.lwjgl.opengl.GL11.GL_LINE_STRIP; +import static org.lwjgl.opengl.GL11.glPopAttrib; +import static org.lwjgl.opengl.GL11.glPushAttrib; /** * @author Brady * @since 8/9/2018 */ -public final class PathRenderer implements Helper { - - private static final Tessellator TESSELLATOR = Tessellator.getInstance(); - private static final BufferBuilder BUFFER = TESSELLATOR.getBuffer(); - +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 (mc.currentScreen instanceof GuiClick) { - ((GuiClick) mc.currentScreen).onRender(); + if (Helper.mc.currentScreen instanceof GuiClick) { + ((GuiClick) Helper.mc.currentScreen).onRender(); } int thisPlayerDimension = behavior.baritone.getPlayerContext().world().provider.getDimensionType().getId(); @@ -72,7 +78,7 @@ public final class PathRenderer implements Helper { return; } - Entity renderView = mc.getRenderViewEntity(); + Entity renderView = Helper.mc.getRenderViewEntity(); if (renderView.world != BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world()) { System.out.println("I have no idea what's going on"); @@ -81,19 +87,20 @@ public final class PathRenderer implements Helper { return; } - if (goal != null && Baritone.settings().renderGoal.value) { - drawDankLitGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.value); + if (goal != null && settings.renderGoal.value) { + drawDankLitGoalBox(renderView, goal, partialTicks, settings.colorGoalBox.value); } - if (!Baritone.settings().renderPath.value) { + if (!settings.renderPath.value) { return; } + 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 && Baritone.settings().renderSelectionBoxes.value) { - drawManySelectionBoxes(renderView, current.toBreak(), Baritone.settings().colorBlocksToBreak.value); - drawManySelectionBoxes(renderView, current.toPlace(), Baritone.settings().colorBlocksToPlace.value); - drawManySelectionBoxes(renderView, current.toWalkInto(), Baritone.settings().colorBlocksToWalkInto.value); + 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(player, Collections.singletonList(behavior.pathStart()), partialTicks, Color.WHITE); @@ -101,63 +108,51 @@ public final class PathRenderer implements Helper { // Render the current path, if there is one if (current != null && current.getPath() != null) { int renderBegin = Math.max(current.getPosition() - 3, 0); - drawPath(current.getPath(), renderBegin, renderView, partialTicks, Baritone.settings().colorCurrentPath.value, Baritone.settings().fadePath.value, 10, 20); + drawPath(current.getPath(), renderBegin, settings.colorCurrentPath.value, settings.fadePath.value, 10, 20); } + if (next != null && next.getPath() != null) { - drawPath(next.getPath(), 0, renderView, partialTicks, Baritone.settings().colorNextPath.value, Baritone.settings().fadePath.value, 10, 20); + drawPath(next.getPath(), 0, settings.colorNextPath.value, settings.fadePath.value, 10, 20); } // If there is a path calculation currently running, render the path calculation process behavior.getInProgress().ifPresent(currentlyRunning -> { currentlyRunning.bestPathSoFar().ifPresent(p -> { - drawPath(p, 0, renderView, partialTicks, Baritone.settings().colorBestPathSoFar.value, Baritone.settings().fadePath.value, 10, 20); + drawPath(p, 0, settings.colorBestPathSoFar.value, settings.fadePath.value, 10, 20); }); - currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { - drawPath(mr, 0, renderView, partialTicks, Baritone.settings().colorMostRecentConsidered.value, Baritone.settings().fadePath.value, 10, 20); - drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), Baritone.settings().colorMostRecentConsidered.value); + currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { + drawPath(mr, 0, settings.colorMostRecentConsidered.value, settings.fadePath.value, 10, 20); + drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), settings.colorMostRecentConsidered.value); }); }); } - public static void drawPath(IPath path, int startIndex, Entity player, float partialTicks, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) { - GlStateManager.enableBlend(); - GlStateManager.disableLighting(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); - GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F); - GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); - GlStateManager.disableTexture2D(); - GlStateManager.depthMask(false); - if (Baritone.settings().renderPathIgnoreDepth.value) { - GlStateManager.disableDepth(); - } - List positions = path.positions(); - int next; - Tessellator tessellator = Tessellator.getInstance(); + public 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; int fadeEnd = fadeEnd0 + startIndex; - for (int i = startIndex; i < positions.size() - 1; i = next) { - BetterBlockPos start = positions.get(i); - next = i + 1; - BetterBlockPos end = positions.get(next); + List positions = path.positions(); + for (int i = startIndex, next; i < positions.size() - 1; i = next) { + BetterBlockPos start = positions.get(i); + BetterBlockPos end = positions.get(next = i + 1); int dirX = end.x - start.x; int dirY = end.y - start.y; int dirZ = end.z - start.z; - while (next + 1 < positions.size() && (!fadeOut || next + 1 < fadeStart) && (dirX == positions.get(next + 1).x - end.x && dirY == positions.get(next + 1).y - end.y && dirZ == positions.get(next + 1).z - end.z)) { - next++; - end = positions.get(next); - } - double x1 = start.x; - double y1 = start.y; - double z1 = start.z; - double x2 = end.x; - double y2 = end.y; - double z2 = end.z; - if (fadeOut) { + while (next + 1 < positions.size() && (!fadeOut || next + 1 < fadeStart) && + (dirX == positions.get(next + 1).x - end.x && + dirY == positions.get(next + 1).y - end.y && + dirZ == positions.get(next + 1).z - end.z)) { + end = positions.get(++next); + } + + if (fadeOut) { float alpha; + if (i <= fadeStart) { alpha = 0.4F; } else { @@ -166,114 +161,68 @@ public final class PathRenderer implements Helper { } alpha = 0.4F * (1.0F - (float) (i - fadeStart) / (float) (fadeEnd - fadeStart)); } - GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], alpha); + + float[] components = color.getComponents(null); + GlStateManager.color(components[0], components[1], components[2], alpha); } - drawLine(x1, y1, z1, x2, y2, z2); + + drawLine(start.x, start.y, start.z, end.x, end.y, end.z); + tessellator.draw(); } - if (Baritone.settings().renderPathIgnoreDepth.value) { - GlStateManager.enableDepth(); - } - //GlStateManager.color(0.0f, 0.0f, 0.0f, 0.4f); - GlStateManager.depthMask(true); - GlStateManager.enableTexture2D(); - GlStateManager.enableLighting(); - GlStateManager.disableBlend(); + + IRenderer.endLines(settings.renderPathIgnoreDepth.value); } - public static void drawLine(double bp1x, double bp1y, double bp1z, double bp2x, double bp2y, double bp2z) { - double d0 = mc.getRenderManager().viewerPosX; - double d1 = mc.getRenderManager().viewerPosY; - double d2 = mc.getRenderManager().viewerPosZ; - boolean renderPathAsFrickinThingy = !Baritone.settings().renderPathAsLine.value; + public static void drawLine(double x1, double y1, double z1, double x2, double y2, double z2) { + RenderManager renderManager = Helper.mc.getRenderManager(); + 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(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex(); - BUFFER.pos(bp2x + 0.5D - d0, bp2y + 0.5D - d1, bp2z + 0.5D - d2).endVertex(); + 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(bp2x + 0.5D - d0, bp2y + 0.53D - d1, bp2z + 0.5D - d2).endVertex(); - BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.53D - d1, bp1z + 0.5D - d2).endVertex(); - BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).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.5D - vpY, z1 + 0.5D - vpZ).endVertex(); } } public static void drawManySelectionBoxes(Entity player, Collection positions, Color color) { - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); - GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F); - GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); - GlStateManager.disableTexture2D(); - GlStateManager.depthMask(false); - - if (Baritone.settings().renderSelectionBoxesIgnoreDepth.value) { - GlStateManager.disableDepth(); - } - + IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value, settings.renderSelectionBoxesIgnoreDepth.value); //BlockPos blockpos = movingObjectPositionIn.getBlockPos(); BlockStateInterface bsi = new BlockStateInterface(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext()); // TODO this assumes same dimension between primary baritone and render view? is this safe? + positions.forEach(pos -> { IBlockState state = bsi.get0(pos); AxisAlignedBB toDraw; + if (state.getBlock().equals(Blocks.AIR)) { toDraw = Blocks.DIRT.getDefaultState().getSelectedBoundingBox(player.world, pos); } else { toDraw = state.getSelectedBoundingBox(player.world, pos); } - drawAABB(toDraw); + + IRenderer.drawAABB(toDraw); }); - if (Baritone.settings().renderSelectionBoxesIgnoreDepth.value) { - GlStateManager.enableDepth(); - } - - GlStateManager.depthMask(true); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - } - - public static void drawAABB(AxisAlignedBB aabb) { - float expand = 0.002F; - AxisAlignedBB toDraw = aabb.expand(expand, expand, expand).offset(-mc.getRenderManager().viewerPosX, -mc.getRenderManager().viewerPosY, -mc.getRenderManager().viewerPosZ); - BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); - 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.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); - TESSELLATOR.draw(); - BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); - 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.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); - TESSELLATOR.draw(); - BUFFER.begin(GL_LINES, DefaultVertexFormats.POSITION); - 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(); - TESSELLATOR.draw(); + IRenderer.endLines(settings.renderSelectionBoxesIgnoreDepth.value); } public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTicks, Color color) { - double renderPosX = mc.getRenderManager().viewerPosX; - double renderPosY = mc.getRenderManager().viewerPosY; - double renderPosZ = mc.getRenderManager().viewerPosZ; - double minX; - double maxX; - double minZ; - double maxZ; - double minY; - double maxY; - double y1; - double y2; + RenderManager renderManager = Helper.mc.getRenderManager(); + double renderPosX = renderManager.viewerPosX; + double renderPosY = renderManager.viewerPosY; + double renderPosZ = renderManager.viewerPosZ; + double minX, maxX; + double minZ, maxZ; + double minY, maxY; + double y1, y2; double y = MathHelper.cos((float) (((float) ((System.nanoTime() / 100000L) % 20000L)) / 20000F * Math.PI * 2)); if (goal instanceof IGoalRenderPos) { BlockPos goalPos = ((IGoalRenderPos) goal).getGoalPos(); @@ -296,28 +245,28 @@ public final class PathRenderer implements Helper { } else if (goal instanceof GoalXZ) { GoalXZ goalPos = (GoalXZ) goal; - if (Baritone.settings().renderGoalXZBeacon.value) { + if (settings.renderGoalXZBeacon.value) { glPushAttrib(GL_LIGHTING_BIT); - mc.getTextureManager().bindTexture(TileEntityBeaconRenderer.TEXTURE_BEACON_BEAM); + Helper.mc.getTextureManager().bindTexture(TileEntityBeaconRenderer.TEXTURE_BEACON_BEAM); - if (Baritone.settings().renderGoalIgnoreDepth.value) { + if (settings.renderGoalIgnoreDepth.value) { GlStateManager.disableDepth(); } TileEntityBeaconRenderer.renderBeamSegment( - goalPos.getX() - renderPosX, - -renderPosY, - goalPos.getZ() - renderPosZ, - partialTicks, - 1.0, - player.world.getTotalWorldTime(), - 0, - 256, - color.getColorComponents(null) + goalPos.getX() - renderPosX, + -renderPosY, + goalPos.getZ() - renderPosZ, + partialTicks, + 1.0, + player.world.getTotalWorldTime(), + 0, + 256, + color.getColorComponents(null) ); - if (Baritone.settings().renderGoalIgnoreDepth.value) { + if (settings.renderGoalIgnoreDepth.value) { GlStateManager.enableDepth(); } @@ -340,14 +289,14 @@ public final class PathRenderer implements Helper { } return; } else if (goal instanceof GoalInverted) { - drawDankLitGoalBox(player, ((GoalInverted) goal).origin, partialTicks, Baritone.settings().colorInvertedGoalBox.value); + drawDankLitGoalBox(player, ((GoalInverted) goal).origin, partialTicks, settings.colorInvertedGoalBox.value); return; } else if (goal instanceof GoalYLevel) { GoalYLevel goalpos = (GoalYLevel) goal; - minX = player.posX - Baritone.settings().yLevelBoxSize.value - renderPosX; - minZ = player.posZ - Baritone.settings().yLevelBoxSize.value - renderPosZ; - maxX = player.posX + Baritone.settings().yLevelBoxSize.value - renderPosX; - maxZ = player.posZ + Baritone.settings().yLevelBoxSize.value - renderPosZ; + minX = player.posX - settings.yLevelBoxSize.value - renderPosX; + minZ = player.posZ - settings.yLevelBoxSize.value - renderPosZ; + maxX = player.posX + settings.yLevelBoxSize.value - renderPosX; + maxZ = player.posZ + settings.yLevelBoxSize.value - renderPosZ; minY = ((GoalYLevel) goal).level - renderPosY; maxY = minY + 2; y1 = 1 + y + goalpos.level - renderPosY; @@ -356,46 +305,33 @@ public final class PathRenderer implements Helper { return; } - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); - GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.6F); - GlStateManager.glLineWidth(Baritone.settings().goalRenderLineWidthPixels.value); - GlStateManager.disableTexture2D(); - GlStateManager.depthMask(false); - if (Baritone.settings().renderGoalIgnoreDepth.value) { - GlStateManager.disableDepth(); - } + 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(); - 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(); - TESSELLATOR.draw(); + buffer.begin(GL_LINES, DefaultVertexFormats.POSITION); + 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(); + tessellator.draw(); - if (Baritone.settings().renderGoalIgnoreDepth.value) { - GlStateManager.enableDepth(); - } - GlStateManager.depthMask(true); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); + 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, maxZ).endVertex(); - BUFFER.pos(minX, y, maxZ).endVertex(); - TESSELLATOR.draw(); + buffer.begin(GL_LINE_LOOP, DefaultVertexFormats.POSITION); + buffer.pos(minX, y, minZ).endVertex(); + buffer.pos(maxX, y, minZ).endVertex(); + buffer.pos(maxX, y, maxZ).endVertex(); + buffer.pos(minX, y, maxZ).endVertex(); + tessellator.draw(); } } } From d1a0b735d9bf1f045a129d561d1b11587bc61ca3 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Mon, 2 Sep 2019 16:18:07 -0700 Subject: [PATCH 605/682] First working version of WorldEdit-like commands(!!!) --- .../api/schematic/AbstractSchematic.java | 30 +++++++++ .../api/schematic/CompositeSchematic.java | 61 +++++++++++++++++++ .../schematic/CompositeSchematicEntry.java | 17 ++++++ .../api/schematic/FillBomSchematic.java | 26 ++++++++ .../baritone/api/schematic/MaskSchematic.java | 25 ++++++++ .../api/schematic/ShellSchematic.java | 14 +++++ .../api/schematic/WallsSchematic.java | 14 +++++ .../baritone/api/utils/BlockOptionalMeta.java | 9 ++- .../utils/command/defaults/SelCommand.java | 56 ++++++++++++++++- 9 files changed, 250 insertions(+), 2 deletions(-) create mode 100644 src/api/java/baritone/api/schematic/AbstractSchematic.java create mode 100644 src/api/java/baritone/api/schematic/CompositeSchematic.java create mode 100644 src/api/java/baritone/api/schematic/CompositeSchematicEntry.java create mode 100644 src/api/java/baritone/api/schematic/FillBomSchematic.java create mode 100644 src/api/java/baritone/api/schematic/MaskSchematic.java create mode 100644 src/api/java/baritone/api/schematic/ShellSchematic.java create mode 100644 src/api/java/baritone/api/schematic/WallsSchematic.java diff --git a/src/api/java/baritone/api/schematic/AbstractSchematic.java b/src/api/java/baritone/api/schematic/AbstractSchematic.java new file mode 100644 index 00000000..3b6bb41c --- /dev/null +++ b/src/api/java/baritone/api/schematic/AbstractSchematic.java @@ -0,0 +1,30 @@ +package baritone.api.schematic; + +import baritone.api.utils.ISchematic; + +public abstract class AbstractSchematic implements ISchematic { + protected int x; + protected int y; + protected int z; + + public AbstractSchematic(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + @Override + public int widthX() { + return x; + } + + @Override + public int heightY() { + return y; + } + + @Override + public int lengthZ() { + return z; + } +} diff --git a/src/api/java/baritone/api/schematic/CompositeSchematic.java b/src/api/java/baritone/api/schematic/CompositeSchematic.java new file mode 100644 index 00000000..56c49b80 --- /dev/null +++ b/src/api/java/baritone/api/schematic/CompositeSchematic.java @@ -0,0 +1,61 @@ +package baritone.api.schematic; + +import baritone.api.utils.ISchematic; +import net.minecraft.block.state.IBlockState; + +import java.util.ArrayList; +import java.util.List; + +public class CompositeSchematic extends AbstractSchematic { + private final List schematics; + private CompositeSchematicEntry[] schematicArr; + + private void recalcArr() { + schematicArr = schematics.toArray(new CompositeSchematicEntry[0]); + + for (CompositeSchematicEntry entry : schematicArr) { + this.x = Math.max(x, entry.x + entry.schematic.widthX()); + this.y = Math.max(y, entry.y + entry.schematic.heightY()); + this.z = Math.max(z, entry.z + entry.schematic.lengthZ()); + } + } + + public CompositeSchematic(int x, int y, int z) { + super(x, y, z); + schematics = new ArrayList<>(); + recalcArr(); + } + + public void put(ISchematic extra, int x, int y, int z) { + schematics.add(new CompositeSchematicEntry(extra, x, y, z)); + recalcArr(); + } + + private CompositeSchematicEntry getSchematic(int x, int y, int z, IBlockState currentState) { + for (CompositeSchematicEntry entry : schematicArr) { + if (x >= entry.x && y >= entry.y && z >= entry.z && + entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState)) { + return entry; + } + } + + return null; + } + + @Override + public boolean inSchematic(int x, int y, int z, IBlockState currentState) { + CompositeSchematicEntry entry = getSchematic(x, y, z, currentState); + return entry != null && entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState); + } + + @Override + public IBlockState desiredState(int x, int y, int z, IBlockState current) { + CompositeSchematicEntry entry = getSchematic(x, y, z, current); + + if (entry == null) { + throw new IllegalStateException("couldn't find schematic for this position"); + } + + return entry.schematic.desiredState(x - entry.x, y - entry.y, z - entry.z, current); + } +} diff --git a/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java b/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java new file mode 100644 index 00000000..c34cd112 --- /dev/null +++ b/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java @@ -0,0 +1,17 @@ +package baritone.api.schematic; + +import baritone.api.utils.ISchematic; + +public class CompositeSchematicEntry { + public final ISchematic schematic; + public final int x; + public final int y; + public final int z; + + public CompositeSchematicEntry(ISchematic schematic, int x, int y, int z) { + this.schematic = schematic; + this.x = x; + this.y = y; + this.z = z; + } +} diff --git a/src/api/java/baritone/api/schematic/FillBomSchematic.java b/src/api/java/baritone/api/schematic/FillBomSchematic.java new file mode 100644 index 00000000..b7536e81 --- /dev/null +++ b/src/api/java/baritone/api/schematic/FillBomSchematic.java @@ -0,0 +1,26 @@ +package baritone.api.schematic; + +import baritone.api.utils.BlockOptionalMeta; +import net.minecraft.block.state.IBlockState; + +public class FillBomSchematic extends AbstractSchematic { + private final BlockOptionalMeta bom; + + public FillBomSchematic(int x, int y, int z, BlockOptionalMeta bom) { + super(x, y, z); + this.bom = bom; + } + + public BlockOptionalMeta getBom() { + return bom; + } + + @Override + public IBlockState desiredState(int x, int y, int z, IBlockState current) { + if (bom.matches(current)) { + return current; + } + + return bom.getAnyBlockState(); + } +} diff --git a/src/api/java/baritone/api/schematic/MaskSchematic.java b/src/api/java/baritone/api/schematic/MaskSchematic.java new file mode 100644 index 00000000..033e390c --- /dev/null +++ b/src/api/java/baritone/api/schematic/MaskSchematic.java @@ -0,0 +1,25 @@ +package baritone.api.schematic; + +import baritone.api.utils.ISchematic; +import net.minecraft.block.state.IBlockState; + +public abstract class MaskSchematic extends AbstractSchematic { + private final ISchematic schematic; + + public MaskSchematic(ISchematic schematic) { + super(schematic.widthX(), schematic.heightY(), schematic.lengthZ()); + this.schematic = schematic; + } + + protected abstract boolean partOfMask(int x, int y, int z, IBlockState currentState); + + @Override + public boolean inSchematic(int x, int y, int z, IBlockState currentState) { + return schematic.inSchematic(x, y, z, currentState) && partOfMask(x, y, z, currentState); + } + + @Override + public IBlockState desiredState(int x, int y, int z, IBlockState current) { + return schematic.desiredState(x, y, z, current); + } +} diff --git a/src/api/java/baritone/api/schematic/ShellSchematic.java b/src/api/java/baritone/api/schematic/ShellSchematic.java new file mode 100644 index 00000000..2c94fa9f --- /dev/null +++ b/src/api/java/baritone/api/schematic/ShellSchematic.java @@ -0,0 +1,14 @@ +package baritone.api.schematic; + +import baritone.api.utils.ISchematic; +import net.minecraft.block.state.IBlockState; + +public class ShellSchematic extends MaskSchematic { + public ShellSchematic(ISchematic schematic) { + super(schematic); + } + + protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { + return x == 0 || y == 0 || z == 0 || x == widthX() - 1 || y == heightY() - 1 || z == lengthZ() - 1; + } +} diff --git a/src/api/java/baritone/api/schematic/WallsSchematic.java b/src/api/java/baritone/api/schematic/WallsSchematic.java new file mode 100644 index 00000000..8091944e --- /dev/null +++ b/src/api/java/baritone/api/schematic/WallsSchematic.java @@ -0,0 +1,14 @@ +package baritone.api.schematic; + +import baritone.api.utils.ISchematic; +import net.minecraft.block.state.IBlockState; + +public class WallsSchematic extends MaskSchematic { + public WallsSchematic(ISchematic schematic) { + super(schematic); + } + + protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { + return x == 0 || z == 0 || x == widthX() - 1 || z == lengthZ() - 1; + } +} diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index 90d163d8..bd17307c 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -31,7 +31,6 @@ import net.minecraft.block.BlockDoublePlant; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFire; import net.minecraft.block.BlockGrass; -import net.minecraft.block.BlockHorizontal; import net.minecraft.block.BlockLeaves; import net.minecraft.block.BlockLever; import net.minecraft.block.BlockLog; @@ -323,4 +322,12 @@ public final class BlockOptionalMeta { //noinspection deprecation return Block.getBlockFromItem(stack.getItem()).getStateFromMeta(stack.getMetadata()); } + + public IBlockState getAnyBlockState() { + if (blockstates.size() > 0) { + return blockstates.iterator().next(); + } + + return null; + } } diff --git a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java index ef66be5e..c696bd72 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java @@ -19,15 +19,25 @@ package baritone.api.utils.command.defaults; import baritone.api.Settings; import baritone.api.event.events.RenderEvent; +import baritone.api.schematic.CompositeSchematic; +import baritone.api.schematic.FillBomSchematic; +import baritone.api.schematic.ShellSchematic; +import baritone.api.schematic.WallsSchematic; +import baritone.api.selection.ISelection; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.IRenderer; +import baritone.api.utils.ISchematic; import baritone.api.utils.command.Command; +import baritone.api.utils.command.datatypes.ForBlockOptionalMeta; import baritone.api.utils.command.datatypes.RelativeBlockPos; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import net.minecraft.init.Blocks; import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.Vec3i; import java.awt.Color; import java.util.HashSet; @@ -75,6 +85,46 @@ public class SelCommand extends Command { "Removed %d selections", baritone.getSelectionManager().removeAllSelections().length )); + } else { + BlockOptionalMeta type = action == Action.CLEARAREA + ? new BlockOptionalMeta(Blocks.AIR) + : args.getDatatypeFor(ForBlockOptionalMeta.class); + args.requireMax(0); + ISelection[] selections = baritone.getSelectionManager().getSelections(); + + if (selections.length == 0) { + throw new CommandInvalidStateException("No selections"); + } + + BetterBlockPos origin = selections[0].min(); + CompositeSchematic composite = new CompositeSchematic(0, 0, 0); + + for (ISelection selection : selections) { + BetterBlockPos min = selection.min(); + origin = new BetterBlockPos( + Math.min(origin.x, min.x), + Math.min(origin.y, min.y), + Math.min(origin.z, min.z) + ); + } + + for (ISelection selection : selections) { + Vec3i size = selection.size(); + BetterBlockPos min = selection.min(); + + ISchematic schematic = new FillBomSchematic(size.getX(), size.getY(), size.getZ(), type); + + if (action == Action.WALLS) { + schematic = new WallsSchematic(schematic); + } else if (action == Action.SHELL) { + schematic = new ShellSchematic(schematic); + } + + composite.put(schematic, min.x - origin.x, min.y - origin.y, min.z - origin.z); + } + + baritone.getBuilderProcess().build("Fill", composite, origin); + logDirect("Filling now"); } } @@ -112,7 +162,11 @@ public class SelCommand extends Command { enum Action { POS1("pos1", "p1"), POS2("pos2", "p2"), - CLEAR("clear", "c"); + CLEAR("clear", "c"), + SET("set", "fill", "s", "f"), + WALLS("walls", "w"), + SHELL("shell", "sh"), + CLEARAREA("cleararea", "ca"); private final String[] names; From 289971557a9f12ebef0d25ca8ad72a150262cba3 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Mon, 2 Sep 2019 19:50:14 -0700 Subject: [PATCH 606/682] Fix bug with a few old commands that causes pagination to not work --- .../java/baritone/api/utils/command/defaults/HelpCommand.java | 2 +- .../java/baritone/api/utils/command/defaults/SetCommand.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java b/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java index efe0d0e2..a4ec3f23 100644 --- a/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java @@ -86,7 +86,7 @@ public class HelpCommand extends Command { }}); }}; }, - FORCE_COMMAND_PREFIX + "help %d" + FORCE_COMMAND_PREFIX + "help" ); } else { String commandName = args.getString().toLowerCase(); diff --git a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java b/src/api/java/baritone/api/utils/command/defaults/SetCommand.java index d5767de9..f343c56e 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SetCommand.java @@ -112,7 +112,7 @@ public class SetCommand extends Command { getStyle().setColor(TextFormatting.DARK_GRAY); }}); }}, - FORCE_COMMAND_PREFIX + "set " + arg + " " + search + " %d" + FORCE_COMMAND_PREFIX + "set " + arg + " " + search ); return; From 17ca9ec43d55b22f386a75e3527fdaecffcc9536 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 2 Sep 2019 23:13:14 -0700 Subject: [PATCH 607/682] Update USAGE.md --- USAGE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/USAGE.md b/USAGE.md index 869d68c2..70737b1c 100644 --- a/USAGE.md +++ b/USAGE.md @@ -24,7 +24,7 @@ Some common examples: - `goal clear` to clear the goal - `cancel` or `stop` to stop everything - `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part) -- `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) An amount of blocks can also be specified, for example, `mine diamond_ore 64`. +- `mine diamond_ore iron_ore` to mine diamond ore or iron ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) An amount of blocks can also be specified, for example, `mine diamond_ore 64`. - `click` to click your destination on the screen. Right click path to on top of the block, left click to path into it (either at foot level or eye level), and left click and drag to clear all blocks from an area. - `follow playerName` to follow a player. `followplayers` to follow any players in range (combine with Kill Aura for a fun time). `followentities` to follow any entities. `followentity pig` to follow entities of a specific type. - `save waypointName` to save a waypoint. `goto waypointName` to go to it. From 65d2bdaf2bb40a0c566c5779ef98d3e352e62f9f Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Tue, 3 Sep 2019 06:09:02 -0700 Subject: [PATCH 608/682] Selection shifting and such --- .../api/selection/ISelectionManager.java | 48 +++++- .../command/datatypes/ForEnumFacing.java | 38 +++++ .../utils/command/defaults/SelCommand.java | 152 ++++++++++++++++-- .../java/baritone/selection/Selection.java | 4 +- .../baritone/selection/SelectionManager.java | 62 ++++++- 5 files changed, 284 insertions(+), 20 deletions(-) create mode 100644 src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java diff --git a/src/api/java/baritone/api/selection/ISelectionManager.java b/src/api/java/baritone/api/selection/ISelectionManager.java index d7513160..763714e7 100644 --- a/src/api/java/baritone/api/selection/ISelectionManager.java +++ b/src/api/java/baritone/api/selection/ISelectionManager.java @@ -1,6 +1,7 @@ package baritone.api.selection; import baritone.api.utils.BetterBlockPos; +import net.minecraft.util.EnumFacing; /** * The selection manager handles setting Baritone's selections. You can set the selection here, as well as retrieving @@ -46,7 +47,52 @@ public interface ISelectionManager { * For anything expecting only one selection, this method is provided. However, to enforce multi-selection support, * this method will only return a selection if there is ONLY one. * - * @return The only selection. + * @return The only selection, or null if there isn't only one. */ ISelection getOnlySelection(); + + /** + * This method will always return the last selection. ONLY use this if you want to, for example, modify the most + * recent selection based on user input. ALWAYS use {@link #getOnlySelection()} or, ideally, + * {@link #getSelections()} for retrieving the content of selections. + * + * @return The last selection, or null if it doesn't exist. + */ + ISelection getLastSelection(); + + /** + * Replaces the specified {@link ISelection} with one expanded in the specified direction by the specified number of + * blocks. Returns the new selection. + * + * @param selection The selection to expand. + * @param direction The direction to expand the selection. + * @param blocks How many blocks to expand it. + * @return The new selection, expanded as specified. + */ + ISelection expand(ISelection selection, EnumFacing direction, int blocks); + + /** + * Replaces the specified {@link ISelection} with one contracted in the specified direction by the specified number + * of blocks. + * + * Note that, for example, if the direction specified is UP, the bottom of the selection will be shifted up. If it + * is DOWN, the top of the selection will be shifted down. + * + * @param selection The selection to contract. + * @param direction The direction to contract the selection. + * @param blocks How many blocks to contract it. + * @return The new selection, contracted as specified. + */ + ISelection contract(ISelection selection, EnumFacing direction, int blocks); + + /** + * Replaces the specified {@link ISelection} with one shifted in the specified direction by the specified number of + * blocks. This moves the whole selection. + * + * @param selection The selection to shift. + * @param direction The direction to shift the selection. + * @param blocks How many blocks to shift it. + * @return The new selection, shifted as specified. + */ + ISelection shift(ISelection selection, EnumFacing direction, int blocks); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java new file mode 100644 index 00000000..f65f1c55 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java @@ -0,0 +1,38 @@ +package baritone.api.utils.command.datatypes; + +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import net.minecraft.util.EnumFacing; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Stream; + +public class ForEnumFacing implements IDatatypeFor { + private final EnumFacing facing; + + public ForEnumFacing() { + facing = null; + } + + public ForEnumFacing(ArgConsumer consumer) { + facing = EnumFacing.valueOf(consumer.getString().toUpperCase(Locale.US)); + } + + @Override + public EnumFacing get() { + return facing; + } + + @Override + public Stream tabComplete(ArgConsumer consumer) { + return new TabCompleteHelper() + .append( + Arrays.stream(EnumFacing.values()) + .map(EnumFacing::getName) + .map(String::toLowerCase) + ) + .filterPrefix(consumer.getString()) + .stream(); + } +} diff --git a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java index c696bd72..366ec9f2 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java @@ -24,18 +24,21 @@ import baritone.api.schematic.FillBomSchematic; import baritone.api.schematic.ShellSchematic; import baritone.api.schematic.WallsSchematic; import baritone.api.selection.ISelection; +import baritone.api.selection.ISelectionManager; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.IRenderer; import baritone.api.utils.ISchematic; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.ForBlockOptionalMeta; +import baritone.api.utils.command.datatypes.ForEnumFacing; import baritone.api.utils.command.datatypes.RelativeBlockPos; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.init.Blocks; +import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.Vec3i; @@ -43,11 +46,13 @@ import java.awt.Color; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.function.Function; import java.util.stream.Stream; import static java.util.Arrays.asList; public class SelCommand extends Command { + private ISelectionManager manager = baritone.getSelectionManager(); private BetterBlockPos pos1 = null; public SelCommand() { @@ -75,22 +80,36 @@ public class SelCommand extends Command { pos1 = pos; logDirect("Position 1 has been set"); } else { - baritone.getSelectionManager().addSelection(pos1, pos); + manager.addSelection(pos1, pos); pos1 = null; logDirect("Selection added"); } } else if (action == Action.CLEAR) { + args.requireMax(0); pos1 = null; - logDirect(String.format( - "Removed %d selections", - baritone.getSelectionManager().removeAllSelections().length - )); - } else { + logDirect(String.format("Removed %d selections", manager.removeAllSelections().length)); + } else if (action == Action.UNDO) { + args.requireMax(0); + + if (pos1 != null) { + pos1 = null; + logDirect("Undid pos1"); + } else { + ISelection[] selections = manager.getSelections(); + + if (selections.length < 1) { + throw new CommandInvalidStateException("Nothing to undo!"); + } else { + pos1 = manager.removeSelection(selections[selections.length - 1]).pos1(); + logDirect("Undid pos2"); + } + } + } else if (action == Action.SET || action == Action.WALLS || action == Action.SHELL || action == Action.CLEARAREA) { BlockOptionalMeta type = action == Action.CLEARAREA ? new BlockOptionalMeta(Blocks.AIR) : args.getDatatypeFor(ForBlockOptionalMeta.class); args.requireMax(0); - ISelection[] selections = baritone.getSelectionManager().getSelections(); + ISelection[] selections = manager.getSelections(); if (selections.length == 0) { throw new CommandInvalidStateException("No selections"); @@ -125,6 +144,36 @@ public class SelCommand extends Command { baritone.getBuilderProcess().build("Fill", composite, origin); logDirect("Filling now"); + } else if (action == Action.EXPAND || action == Action.CONTRACT || action == Action.SHIFT) { + args.requireExactly(3); + TransformTarget transformTarget = TransformTarget.getByName(args.getString()); + + if (transformTarget == null) { + throw new CommandInvalidStateException("Invalid transform type"); + } + + EnumFacing direction = args.getDatatypeFor(ForEnumFacing.class); + int blocks = args.getAs(Integer.class); + + ISelection[] selections = manager.getSelections(); + + if (selections.length < 1) { + throw new CommandInvalidStateException("No selections found"); + } + + selections = transformTarget.transform(selections); + + for (ISelection selection : selections) { + if (action == Action.EXPAND) { + manager.expand(selection, direction, blocks); + } else if (action == Action.CONTRACT) { + manager.contract(selection, direction, blocks); + } else { + manager.shift(selection, direction, blocks); + } + } + + logDirect(String.format("Transformed %d selections", selections.length)); } } @@ -141,7 +190,27 @@ public class SelCommand extends Command { if (action != null) { if (action == Action.POS1 || action == Action.POS2) { - return args.tabCompleteDatatype(RelativeBlockPos.class); + if (args.hasAtMost(3)) { + return args.tabCompleteDatatype(RelativeBlockPos.class); + } + } else if (action == Action.SET || action == Action.WALLS || action == Action.CLEARAREA) { + if (args.hasExactlyOne()) { + return args.tabCompleteDatatype(ForBlockOptionalMeta.class); + } + } else if (action == Action.EXPAND || action == Action.CONTRACT || action == Action.SHIFT) { + if (args.hasExactlyOne()) { + return new TabCompleteHelper() + .append(TransformTarget.getAllNames()) + .filterPrefix(args.getString()) + .sortAlphabetically() + .stream(); + } else { + TransformTarget target = TransformTarget.getByName(args.getString()); + + if (target != null && args.hasExactlyOne()) { + return args.tabCompleteDatatype(ForEnumFacing.class); + } + } } } } @@ -152,21 +221,38 @@ public class SelCommand extends Command { @Override public List getLongDesc() { return asList( + "The sel command allows you to manipulate Baritone's selections, similarly to WorldEdit.", "", + "Using these selections, you can clear areas, fill them with blocks, or something else.", "", "Usage:", - "> " + "> sel pos1/p1/1 - Set position 1 to your current position.", + "> sel pos1/p1/1 - Set position 1 to a relative position.", + "> sel pos2/p2/2 - Set position 2 to your current position.", + "> sel pos2/p2/2 - Set position 2 to a relative position.", + "> sel clear/c - Clear the selection.", + "> sel undo/u - Undo the last action (setting positions, creating selections, etc.)", + "> sel walls/w [block] - Fill in the walls of the selection with a specified block, or the block in your hand.", + "> sel shell/sh [block] - The same as walls, but fills in a ceiling and floor too.", + "> sel cleararea/ca - Basically 'set air'." ); } enum Action { - POS1("pos1", "p1"), - POS2("pos2", "p2"), + POS1("pos1", "p1", "1"), + POS2("pos2", "p2", "2"), + CLEAR("clear", "c"), + UNDO("undo", "u"), + SET("set", "fill", "s", "f"), WALLS("walls", "w"), - SHELL("shell", "sh"), - CLEARAREA("cleararea", "ca"); + SHELL("shell", "shl"), + CLEARAREA("cleararea", "ca"), + + EXPAND("expand", "ex"), + CONTRACT("contact", "ct"), + SHIFT("shift", "sh"); private final String[] names; @@ -197,6 +283,46 @@ public class SelCommand extends Command { } } + enum TransformTarget { + ALL(sels -> sels, "all", "a"), + NEWEST(sels -> new ISelection[] {sels[0]}, "newest", "n"), + OLDEST(sels -> new ISelection[] {sels[sels.length - 1]}, "oldest", "o"); + + private final Function transform; + private final String[] names; + + TransformTarget(Function transform, String... names) { + this.transform = transform; + this.names = names; + } + + public ISelection[] transform(ISelection[] selections) { + return transform.apply(selections); + } + + public static TransformTarget getByName(String name) { + for (TransformTarget target : TransformTarget.values()) { + for (String alias : target.names) { + if (alias.equalsIgnoreCase(name)) { + return target; + } + } + } + + return null; + } + + public static String[] getAllNames() { + Set names = new HashSet<>(); + + for (TransformTarget target : TransformTarget.values()) { + names.addAll(asList(target.names)); + } + + return names.toArray(new String[0]); + } + } + @Override public void onRenderPass(RenderEvent event) { if (!settings.renderSelectionCorners.value || pos1 == null) { diff --git a/src/main/java/baritone/selection/Selection.java b/src/main/java/baritone/selection/Selection.java index 68b8021b..3b385503 100644 --- a/src/main/java/baritone/selection/Selection.java +++ b/src/main/java/baritone/selection/Selection.java @@ -116,9 +116,9 @@ public class Selection implements ISelection { @Override public ISelection contract(EnumFacing direction, int blocks) { if (isPos2(direction)) { - return new Selection(pos1.offset(direction, -blocks), pos2); + return new Selection(pos1.offset(direction, blocks), pos2); } else { - return new Selection(pos1, pos2.offset(direction, -blocks)); + return new Selection(pos1, pos2.offset(direction, blocks)); } } diff --git a/src/main/java/baritone/selection/SelectionManager.java b/src/main/java/baritone/selection/SelectionManager.java index b95c60b2..5fea4cba 100644 --- a/src/main/java/baritone/selection/SelectionManager.java +++ b/src/main/java/baritone/selection/SelectionManager.java @@ -3,12 +3,13 @@ package baritone.selection; import baritone.api.selection.ISelection; import baritone.api.selection.ISelectionManager; import baritone.api.utils.BetterBlockPos; +import net.minecraft.util.EnumFacing; -import java.util.LinkedHashSet; -import java.util.Set; +import java.util.LinkedList; +import java.util.ListIterator; public class SelectionManager implements ISelectionManager { - private final Set selections = new LinkedHashSet<>(); + private final LinkedList selections = new LinkedList<>(); private ISelection[] selectionsArr = new ISelection[0]; public SelectionManager() { @@ -54,7 +55,60 @@ public class SelectionManager implements ISelectionManager { @Override public synchronized ISelection getOnlySelection() { if (selections.size() == 1) { - return selections.iterator().next(); + return selections.peekFirst(); + } + + return null; + } + + @Override + public ISelection getLastSelection() { + return selections.peekLast(); + } + + @Override + public synchronized ISelection expand(ISelection selection, EnumFacing direction, int blocks) { + for (ListIterator it = selections.listIterator(); it.hasNext(); ) { + ISelection current = it.next(); + + if (current == selection) { + it.remove(); + it.add(current.expand(direction, blocks)); + resetSelectionsArr(); + return it.previous(); + } + } + + return null; + } + + @Override + public synchronized ISelection contract(ISelection selection, EnumFacing direction, int blocks) { + for (ListIterator it = selections.listIterator(); it.hasNext(); ) { + ISelection current = it.next(); + + if (current == selection) { + it.remove(); + it.add(current.contract(direction, blocks)); + resetSelectionsArr(); + return it.previous(); + } + } + + return null; + } + + @Override + public synchronized ISelection shift(ISelection selection, EnumFacing direction, int blocks) { + for (ListIterator it = selections.listIterator(); it.hasNext(); ) { + ISelection current = it.next(); + + if (current == selection) { + it.remove(); + it.add(current.shift(direction, blocks)); + resetSelectionsArr(); + return it.previous(); + } } return null; From faa8c727c3d433a002978115463b8a2ecc21325b Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Tue, 3 Sep 2019 06:14:22 -0700 Subject: [PATCH 609/682] correct sel help --- .../api/utils/command/defaults/SelCommand.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java index 366ec9f2..78d79014 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java @@ -225,16 +225,24 @@ public class SelCommand extends Command { "", "Using these selections, you can clear areas, fill them with blocks, or something else.", "", + "The expand/contract/shift commands use a kind of selector to choose which selections to target. Supported ones are a/all, n/newest, and o/oldest.", + "", "Usage:", "> sel pos1/p1/1 - Set position 1 to your current position.", "> sel pos1/p1/1 - Set position 1 to a relative position.", "> sel pos2/p2/2 - Set position 2 to your current position.", "> sel pos2/p2/2 - Set position 2 to a relative position.", + "", "> sel clear/c - Clear the selection.", "> sel undo/u - Undo the last action (setting positions, creating selections, etc.)", - "> sel walls/w [block] - Fill in the walls of the selection with a specified block, or the block in your hand.", - "> sel shell/sh [block] - The same as walls, but fills in a ceiling and floor too.", - "> sel cleararea/ca - Basically 'set air'." + "> 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 cleararea/ca - Basically 'set air'.", + "", + "> sel expand - Expand the targets.", + "> sel contract - Contract the targets.", + "> sel shift - Shift the targets (does not resize)." ); } From 1413bd2f0527dc8c2ba06d595e5581703a7df335 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Tue, 3 Sep 2019 06:27:36 -0700 Subject: [PATCH 610/682] LOL CONTACT --- .../java/baritone/api/utils/command/defaults/SelCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java index 78d79014..2579a3bd 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java @@ -259,7 +259,7 @@ public class SelCommand extends Command { CLEARAREA("cleararea", "ca"), EXPAND("expand", "ex"), - CONTRACT("contact", "ct"), + CONTRACT("contract", "ct"), SHIFT("shift", "sh"); private final String[] names; From 991283182cde4b61bdef3743a1e2d53fc01c2bdb Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Tue, 3 Sep 2019 08:35:16 -0700 Subject: [PATCH 611/682] Fix some bugs with schematics --- .../api/schematic/AbstractSchematic.java | 48 ++++++++++++++++++- .../api/schematic/CompositeSchematic.java | 5 +- .../api/schematic/FillBomSchematic.java | 16 +++++-- .../baritone/api/schematic/MaskSchematic.java | 5 +- .../api/schematic/ReplaceSchematic.java | 21 ++++++++ .../api/schematic/ShellSchematic.java | 5 +- .../api/schematic/WallsSchematic.java | 5 +- .../baritone/api/utils/BlockOptionalMeta.java | 8 ---- .../utils/command/defaults/SelCommand.java | 42 ++++++++++++---- .../java/baritone/process/BuilderProcess.java | 2 +- 10 files changed, 128 insertions(+), 29 deletions(-) create mode 100644 src/api/java/baritone/api/schematic/ReplaceSchematic.java diff --git a/src/api/java/baritone/api/schematic/AbstractSchematic.java b/src/api/java/baritone/api/schematic/AbstractSchematic.java index 3b6bb41c..ec4d8731 100644 --- a/src/api/java/baritone/api/schematic/AbstractSchematic.java +++ b/src/api/java/baritone/api/schematic/AbstractSchematic.java @@ -1,13 +1,30 @@ package baritone.api.schematic; +import baritone.api.IBaritone; +import baritone.api.utils.IPlayerContext; import baritone.api.utils.ISchematic; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; public abstract class AbstractSchematic implements ISchematic { + protected final IBaritone baritone; + protected final IPlayerContext ctx; protected int x; protected int y; protected int z; - public AbstractSchematic(int x, int y, int z) { + public AbstractSchematic(@Nullable IBaritone baritone, int x, int y, int z) { + this.baritone = baritone; + this.ctx = baritone == null ? null : baritone.getPlayerContext(); this.x = x; this.y = y; this.z = z; @@ -27,4 +44,33 @@ public abstract class AbstractSchematic implements ISchematic { public int lengthZ() { return z; } + + protected IBlockState[] approxPlaceable() { + EntityPlayerSP player = ctx.player(); + NonNullList inventory = player.inventory.mainInventory; + List placeable = new ArrayList<>(); + placeable.add(Blocks.AIR.getDefaultState()); + + // 27 + 9 + for (int i = 0; i < 36; i++) { + ItemStack stack = inventory.get(i); + + if (!stack.isEmpty() && stack.getItem() instanceof ItemBlock) { + // + placeable.add(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement( + ctx.world(), + ctx.playerFeet(), + EnumFacing.UP, + (float) player.posX, + (float) player.posY, + (float) player.posZ, + stack.getItem().getMetadata(stack.getMetadata()), + player + )); + // + } + } + + return placeable.toArray(new IBlockState[0]); + } } diff --git a/src/api/java/baritone/api/schematic/CompositeSchematic.java b/src/api/java/baritone/api/schematic/CompositeSchematic.java index 56c49b80..deb9f5fe 100644 --- a/src/api/java/baritone/api/schematic/CompositeSchematic.java +++ b/src/api/java/baritone/api/schematic/CompositeSchematic.java @@ -1,5 +1,6 @@ package baritone.api.schematic; +import baritone.api.IBaritone; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; @@ -20,8 +21,8 @@ public class CompositeSchematic extends AbstractSchematic { } } - public CompositeSchematic(int x, int y, int z) { - super(x, y, z); + public CompositeSchematic(IBaritone baritone, int x, int y, int z) { + super(baritone, x, y, z); schematics = new ArrayList<>(); recalcArr(); } diff --git a/src/api/java/baritone/api/schematic/FillBomSchematic.java b/src/api/java/baritone/api/schematic/FillBomSchematic.java index b7536e81..7989cbfc 100644 --- a/src/api/java/baritone/api/schematic/FillBomSchematic.java +++ b/src/api/java/baritone/api/schematic/FillBomSchematic.java @@ -1,13 +1,15 @@ package baritone.api.schematic; +import baritone.api.IBaritone; import baritone.api.utils.BlockOptionalMeta; import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; public class FillBomSchematic extends AbstractSchematic { private final BlockOptionalMeta bom; - public FillBomSchematic(int x, int y, int z, BlockOptionalMeta bom) { - super(x, y, z); + public FillBomSchematic(IBaritone baritone, int x, int y, int z, BlockOptionalMeta bom) { + super(baritone, x, y, z); this.bom = bom; } @@ -19,8 +21,16 @@ public class FillBomSchematic extends AbstractSchematic { public IBlockState desiredState(int x, int y, int z, IBlockState current) { if (bom.matches(current)) { return current; + } else if (current.getBlock() != Blocks.AIR) { + return Blocks.AIR.getDefaultState(); } - return bom.getAnyBlockState(); + for (IBlockState placeable : approxPlaceable()) { + if (bom.matches(placeable)) { + return placeable; + } + } + + throw new IllegalStateException("Couldn't find desired state"); } } diff --git a/src/api/java/baritone/api/schematic/MaskSchematic.java b/src/api/java/baritone/api/schematic/MaskSchematic.java index 033e390c..133e4e62 100644 --- a/src/api/java/baritone/api/schematic/MaskSchematic.java +++ b/src/api/java/baritone/api/schematic/MaskSchematic.java @@ -1,13 +1,14 @@ package baritone.api.schematic; +import baritone.api.IBaritone; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; public abstract class MaskSchematic extends AbstractSchematic { private final ISchematic schematic; - public MaskSchematic(ISchematic schematic) { - super(schematic.widthX(), schematic.heightY(), schematic.lengthZ()); + public MaskSchematic(IBaritone baritone, ISchematic schematic) { + super(baritone, schematic.widthX(), schematic.heightY(), schematic.lengthZ()); this.schematic = schematic; } diff --git a/src/api/java/baritone/api/schematic/ReplaceSchematic.java b/src/api/java/baritone/api/schematic/ReplaceSchematic.java new file mode 100644 index 00000000..2d13f1eb --- /dev/null +++ b/src/api/java/baritone/api/schematic/ReplaceSchematic.java @@ -0,0 +1,21 @@ +package baritone.api.schematic; + +import baritone.api.IBaritone; +import baritone.api.utils.BlockOptionalMetaLookup; +import baritone.api.utils.ISchematic; +import net.minecraft.block.state.IBlockState; + +public class ReplaceSchematic extends MaskSchematic { + private final BlockOptionalMetaLookup filter; + private final boolean[][][] cache; + + public ReplaceSchematic(IBaritone baritone, ISchematic schematic, BlockOptionalMetaLookup filter) { + super(baritone, schematic); + this.filter = filter; + this.cache = new boolean[lengthZ()][heightY()][widthX()]; + } + + protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { + return cache[x][y][z] || (cache[x][y][z] = filter.has(currentState)); + } +} diff --git a/src/api/java/baritone/api/schematic/ShellSchematic.java b/src/api/java/baritone/api/schematic/ShellSchematic.java index 2c94fa9f..c6c1bcf2 100644 --- a/src/api/java/baritone/api/schematic/ShellSchematic.java +++ b/src/api/java/baritone/api/schematic/ShellSchematic.java @@ -1,11 +1,12 @@ package baritone.api.schematic; +import baritone.api.IBaritone; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; public class ShellSchematic extends MaskSchematic { - public ShellSchematic(ISchematic schematic) { - super(schematic); + public ShellSchematic(IBaritone baritone, ISchematic schematic) { + super(baritone, schematic); } protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { diff --git a/src/api/java/baritone/api/schematic/WallsSchematic.java b/src/api/java/baritone/api/schematic/WallsSchematic.java index 8091944e..ed66e2fc 100644 --- a/src/api/java/baritone/api/schematic/WallsSchematic.java +++ b/src/api/java/baritone/api/schematic/WallsSchematic.java @@ -1,11 +1,12 @@ package baritone.api.schematic; +import baritone.api.IBaritone; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; public class WallsSchematic extends MaskSchematic { - public WallsSchematic(ISchematic schematic) { - super(schematic); + public WallsSchematic(IBaritone baritone, ISchematic schematic) { + super(baritone, schematic); } protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index bd17307c..1fd4264f 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -322,12 +322,4 @@ public final class BlockOptionalMeta { //noinspection deprecation return Block.getBlockFromItem(stack.getItem()).getStateFromMeta(stack.getMetadata()); } - - public IBlockState getAnyBlockState() { - if (blockstates.size() > 0) { - return blockstates.iterator().next(); - } - - return null; - } } diff --git a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java index 2579a3bd..fea637e8 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java @@ -21,12 +21,14 @@ import baritone.api.Settings; import baritone.api.event.events.RenderEvent; import baritone.api.schematic.CompositeSchematic; import baritone.api.schematic.FillBomSchematic; +import baritone.api.schematic.ReplaceSchematic; import baritone.api.schematic.ShellSchematic; import baritone.api.schematic.WallsSchematic; import baritone.api.selection.ISelection; import baritone.api.selection.ISelectionManager; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BlockOptionalMeta; +import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.IRenderer; import baritone.api.utils.ISchematic; import baritone.api.utils.command.Command; @@ -43,6 +45,7 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.Vec3i; import java.awt.Color; +import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -104,11 +107,26 @@ public class SelCommand extends Command { logDirect("Undid pos2"); } } - } else if (action == Action.SET || action == Action.WALLS || action == Action.SHELL || action == Action.CLEARAREA) { + } else if (action == Action.SET || action == Action.WALLS || action == Action.SHELL || action == Action.CLEARAREA || action == Action.REPLACE) { BlockOptionalMeta type = action == Action.CLEARAREA ? new BlockOptionalMeta(Blocks.AIR) : args.getDatatypeFor(ForBlockOptionalMeta.class); - args.requireMax(0); + BlockOptionalMetaLookup replaces = null; + + if (action == Action.REPLACE) { + args.requireMin(1); + + List replacesList = new ArrayList<>(); + + while (args.has()) { + replacesList.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); + } + + replaces = new BlockOptionalMetaLookup(replacesList.toArray(new BlockOptionalMeta[0])); + } else { + args.requireMax(0); + } + ISelection[] selections = manager.getSelections(); if (selections.length == 0) { @@ -116,7 +134,7 @@ public class SelCommand extends Command { } BetterBlockPos origin = selections[0].min(); - CompositeSchematic composite = new CompositeSchematic(0, 0, 0); + CompositeSchematic composite = new CompositeSchematic(baritone, 0, 0, 0); for (ISelection selection : selections) { BetterBlockPos min = selection.min(); @@ -131,12 +149,14 @@ public class SelCommand extends Command { Vec3i size = selection.size(); BetterBlockPos min = selection.min(); - ISchematic schematic = new FillBomSchematic(size.getX(), size.getY(), size.getZ(), type); + ISchematic schematic = new FillBomSchematic(baritone, size.getX(), size.getY(), size.getZ(), type); if (action == Action.WALLS) { - schematic = new WallsSchematic(schematic); + schematic = new WallsSchematic(baritone, schematic); } else if (action == Action.SHELL) { - schematic = new ShellSchematic(schematic); + schematic = new ShellSchematic(baritone, schematic); + } else if (action == Action.REPLACE) { + schematic = new ReplaceSchematic(baritone, schematic, replaces); } composite.put(schematic, min.x - origin.x, min.y - origin.y, min.z - origin.z); @@ -193,8 +213,12 @@ public class SelCommand extends Command { if (args.hasAtMost(3)) { return args.tabCompleteDatatype(RelativeBlockPos.class); } - } else if (action == Action.SET || action == Action.WALLS || action == Action.CLEARAREA) { - if (args.hasExactlyOne()) { + } else if (action == Action.SET || action == Action.WALLS || action == Action.CLEARAREA || action == Action.REPLACE) { + if (args.hasExactlyOne() || action == Action.REPLACE) { + while (args.has(2)) { + args.get(); + } + return args.tabCompleteDatatype(ForBlockOptionalMeta.class); } } else if (action == Action.EXPAND || action == Action.CONTRACT || action == Action.SHIFT) { @@ -239,6 +263,7 @@ public class SelCommand extends Command { "> 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 cleararea/ca - Basically 'set air'.", + "> sel replace/r - Replaces, with 'place', all blocks listed after it.", "", "> sel expand - Expand the targets.", "> sel contract - Contract the targets.", @@ -257,6 +282,7 @@ public class SelCommand extends Command { WALLS("walls", "w"), SHELL("shell", "shl"), CLEARAREA("cleararea", "ca"), + REPLACE("replace", "r"), EXPAND("expand", "ex"), CONTRACT("contract", "ct"), diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index b3f31059..6bea9a7c 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -522,7 +522,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil int blockX = x + origin.getX(); int blockY = y + origin.getY(); int blockZ = z + origin.getZ(); - IBlockState current = bcc.bsi.get0(x, y, z); + IBlockState current = bcc.bsi.get0(blockX, blockY, blockZ); if (!schematic.inSchematic(x, y, z, current)) { continue; } From 620fc9af643c079598dd0129d08c92f00d2d8ede Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Tue, 3 Sep 2019 21:44:45 -0700 Subject: [PATCH 612/682] Sliiightly more efficient AbstractSchematic#approxPlaceable() --- .../java/baritone/api/schematic/AbstractSchematic.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/schematic/AbstractSchematic.java b/src/api/java/baritone/api/schematic/AbstractSchematic.java index ec4d8731..4a7e9b25 100644 --- a/src/api/java/baritone/api/schematic/AbstractSchematic.java +++ b/src/api/java/baritone/api/schematic/AbstractSchematic.java @@ -6,6 +6,7 @@ import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.init.Blocks; +import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; @@ -54,17 +55,20 @@ public abstract class AbstractSchematic implements ISchematic { // 27 + 9 for (int i = 0; i < 36; i++) { ItemStack stack = inventory.get(i); + Item item = stack.getItem(); if (!stack.isEmpty() && stack.getItem() instanceof ItemBlock) { + ItemBlock itemBlock = (ItemBlock) item; + // - placeable.add(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement( + placeable.add(itemBlock.getBlock().getStateForPlacement( ctx.world(), ctx.playerFeet(), EnumFacing.UP, (float) player.posX, (float) player.posY, (float) player.posZ, - stack.getItem().getMetadata(stack.getMetadata()), + itemBlock.getMetadata(stack.getMetadata()), player )); // From b51dccc73736e6c72b1386917ca129e194c8ec13 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Tue, 3 Sep 2019 21:57:20 -0700 Subject: [PATCH 613/682] DON'T THROW EXCEPTIONS IN SCHEMATICS AA --- src/api/java/baritone/api/schematic/FillBomSchematic.java | 2 +- src/api/java/baritone/api/utils/BlockOptionalMeta.java | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/schematic/FillBomSchematic.java b/src/api/java/baritone/api/schematic/FillBomSchematic.java index 7989cbfc..a9b5f356 100644 --- a/src/api/java/baritone/api/schematic/FillBomSchematic.java +++ b/src/api/java/baritone/api/schematic/FillBomSchematic.java @@ -31,6 +31,6 @@ public class FillBomSchematic extends AbstractSchematic { } } - throw new IllegalStateException("Couldn't find desired state"); + return bom.getAnyBlockState(); } } diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index 1fd4264f..bd17307c 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -322,4 +322,12 @@ public final class BlockOptionalMeta { //noinspection deprecation return Block.getBlockFromItem(stack.getItem()).getStateFromMeta(stack.getMetadata()); } + + public IBlockState getAnyBlockState() { + if (blockstates.size() > 0) { + return blockstates.iterator().next(); + } + + return null; + } } From 755a3f01540188f9607ab5f9f40fff1cb5d01576 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Tue, 3 Sep 2019 21:58:20 -0700 Subject: [PATCH 614/682] Fix #sel selectors --- .../java/baritone/api/utils/command/defaults/SelCommand.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java index fea637e8..3ef7b2ec 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java @@ -319,8 +319,8 @@ public class SelCommand extends Command { enum TransformTarget { ALL(sels -> sels, "all", "a"), - NEWEST(sels -> new ISelection[] {sels[0]}, "newest", "n"), - OLDEST(sels -> new ISelection[] {sels[sels.length - 1]}, "oldest", "o"); + NEWEST(sels -> new ISelection[] {sels[sels.length - 1]}, "newest", "n"), + OLDEST(sels -> new ISelection[] {sels[0]}, "oldest", "o"); private final Function transform; private final String[] names; From 8dc4ff26d6f1acfb9c01813dc19c46e696325bd1 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Tue, 3 Sep 2019 22:55:56 -0700 Subject: [PATCH 615/682] Persistent renderManager, selection transparency setting, drawAABB fixes --- src/api/java/baritone/api/Settings.java | 5 +++++ .../java/baritone/api/utils/IRenderer.java | 21 +++++++++++++------ .../utils/command/defaults/SelCommand.java | 5 +++-- .../baritone/selection/SelectionRenderer.java | 11 +++++----- .../java/baritone/utils/PathRenderer.java | 2 -- 5 files changed, 29 insertions(+), 15 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 8d649d4b..67f5496e 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -970,6 +970,11 @@ public final class Settings { */ public final Setting colorSelectionPos2 = new Setting<>(Color.PINK); + /** + * The opacity of the selection. The default (0.4) is what's used for goals and such + */ + public final Setting selectionOpacity = new Setting<>(.4f); + /** * A map of lowercase setting field names to their respective setting diff --git a/src/api/java/baritone/api/utils/IRenderer.java b/src/api/java/baritone/api/utils/IRenderer.java index 48355a14..7bdb970e 100644 --- a/src/api/java/baritone/api/utils/IRenderer.java +++ b/src/api/java/baritone/api/utils/IRenderer.java @@ -21,15 +21,16 @@ import static org.lwjgl.opengl.GL11.GL_ZERO; public interface IRenderer { Tessellator tessellator = Tessellator.getInstance(); BufferBuilder buffer = tessellator.getBuffer(); + RenderManager renderManager = Helper.mc.getRenderManager(); IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone(); Settings settings = BaritoneAPI.getSettings(); - static void startLines(Color color, float lineWidth, boolean ignoreDepth) { + static void startLines(Color color, float alpha, float lineWidth, boolean ignoreDepth) { GlStateManager.enableBlend(); GlStateManager.disableLighting(); GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); float[] colorComponents = color.getColorComponents(null); - GlStateManager.color(colorComponents[0], colorComponents[1], colorComponents[2], 0.4f); + GlStateManager.color(colorComponents[0], colorComponents[1], colorComponents[2], alpha); GlStateManager.glLineWidth(lineWidth); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); @@ -39,6 +40,10 @@ public interface IRenderer { } } + static void startLines(Color color, float lineWidth, boolean ignoreDepth) { + startLines(color, .4f, lineWidth, ignoreDepth); + } + static void endLines(boolean ignoredDepth) { if (ignoredDepth) { GlStateManager.enableDepth(); @@ -50,10 +55,10 @@ public interface IRenderer { GlStateManager.disableBlend(); } - static void drawAABB(AxisAlignedBB aabb) { - float expand = 0.002F; - RenderManager renderManager = Helper.mc.getRenderManager(); - AxisAlignedBB toDraw = aabb.expand(expand, expand, expand).offset(-renderManager.viewerPosX, -renderManager.viewerPosY, -renderManager.viewerPosZ); + static void drawAABB(AxisAlignedBB aabb, float expand) { + AxisAlignedBB toDraw = aabb + .offset(-renderManager.viewerPosX, -renderManager.viewerPosY, -renderManager.viewerPosZ) + .grow(expand, expand, expand); buffer.begin(GL_LINES, DefaultVertexFormats.POSITION); // bottom @@ -85,4 +90,8 @@ public interface IRenderer { buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); tessellator.draw(); } + + static void drawAABB(AxisAlignedBB aabb) { + drawAABB(aabb, 0.002f); + } } diff --git a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java index 3ef7b2ec..eb09895d 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java @@ -364,11 +364,12 @@ public class SelCommand extends Command { } Color color = settings.colorSelectionPos1.value; + float opacity = settings.selectionOpacity.value; float lineWidth = settings.selectionRenderLineWidthPixels.value; boolean ignoreDepth = settings.renderSelectionIgnoreDepth.value; - IRenderer.startLines(color, lineWidth, ignoreDepth); - IRenderer.drawAABB(new AxisAlignedBB(pos1, pos1.add(1, 1, 1))); + IRenderer.startLines(color, opacity, lineWidth, ignoreDepth); + IRenderer.drawAABB(new AxisAlignedBB(pos1, pos1.add(1, 1, 1)), -.01f); IRenderer.endLines(ignoreDepth); } } diff --git a/src/main/java/baritone/selection/SelectionRenderer.java b/src/main/java/baritone/selection/SelectionRenderer.java index 48f8ae49..4d0fd9a7 100644 --- a/src/main/java/baritone/selection/SelectionRenderer.java +++ b/src/main/java/baritone/selection/SelectionRenderer.java @@ -15,6 +15,7 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener { } public static void renderSelections(ISelection[] selections) { + float opacity = settings.selectionOpacity.value; boolean ignoreDepth = settings.renderSelectionIgnoreDepth.value; float lineWidth = settings.selectionRenderLineWidthPixels.value; @@ -22,7 +23,7 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener { return; } - IRenderer.startLines(settings.colorSelection.value, lineWidth, ignoreDepth); + IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth, ignoreDepth); for (ISelection selection : selections) { IRenderer.drawAABB(selection.aabb()); @@ -34,17 +35,17 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener { return; } - IRenderer.startLines(settings.colorSelectionPos1.value, lineWidth, ignoreDepth); + IRenderer.startLines(settings.colorSelectionPos1.value, opacity, lineWidth, ignoreDepth); for (ISelection selection : selections) { - IRenderer.drawAABB(new AxisAlignedBB(selection.pos1(), selection.pos1().add(1, 1, 1))); + IRenderer.drawAABB(new AxisAlignedBB(selection.pos1(), selection.pos1().add(1, 1, 1)), -.01f); } IRenderer.endLines(ignoreDepth); - IRenderer.startLines(settings.colorSelectionPos2.value, lineWidth, ignoreDepth); + IRenderer.startLines(settings.colorSelectionPos2.value, opacity, lineWidth, ignoreDepth); for (ISelection selection : selections) { - IRenderer.drawAABB(new AxisAlignedBB(selection.pos2(), selection.pos2().add(1, 1, 1))); + IRenderer.drawAABB(new AxisAlignedBB(selection.pos2(), selection.pos2().add(1, 1, 1)), -.01f); } IRenderer.endLines(ignoreDepth); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 3de40b91..9ebb58d4 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -175,7 +175,6 @@ public final class PathRenderer implements IRenderer { } public static void drawLine(double x1, double y1, double z1, double x2, double y2, double z2) { - RenderManager renderManager = Helper.mc.getRenderManager(); double vpX = renderManager.viewerPosX; double vpY = renderManager.viewerPosY; double vpZ = renderManager.viewerPosZ; @@ -215,7 +214,6 @@ public final class PathRenderer implements IRenderer { } public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTicks, Color color) { - RenderManager renderManager = Helper.mc.getRenderManager(); double renderPosX = renderManager.viewerPosX; double renderPosY = renderManager.viewerPosY; double renderPosZ = renderManager.viewerPosZ; From 382ad0079c7ff9253ce8a4d092cbb5b1f29c02cc Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Tue, 3 Sep 2019 23:46:20 -0700 Subject: [PATCH 616/682] DrawAABB changes, set command bugfix, sel rendering change, selection setting name changes --- src/api/java/baritone/api/Settings.java | 50 +++++++++---------- .../java/baritone/api/utils/IRenderer.java | 18 ++++--- .../utils/command/defaults/SelCommand.java | 4 +- .../utils/command/defaults/SetCommand.java | 14 ++---- .../baritone/selection/SelectionRenderer.java | 27 ++++------ .../java/baritone/utils/PathRenderer.java | 6 +-- 6 files changed, 54 insertions(+), 65 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 67f5496e..1bdb1e39 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -528,21 +528,6 @@ public final class Settings { */ public final Setting renderPathIgnoreDepth = new Setting<>(true); - /** - * Ignore depth when rendering selections - */ - public final Setting renderSelectionIgnoreDepth = new Setting<>(true); - - /** - * Render selections - */ - public final Setting renderSelection = new Setting<>(true); - - /** - * Render selection corners - */ - public final Setting renderSelectionCorners = new Setting<>(true); - /** * Line width of the path when rendered, in pixels */ @@ -553,11 +538,6 @@ public final class Settings { */ public final Setting goalRenderLineWidthPixels = new Setting<>(3F); - /** - * Line width of the goal when rendered, in pixels - */ - public final Setting selectionRenderLineWidthPixels = new Setting<>(3F); - /** * Start fading out the path at 20 movements ahead, and stop rendering it entirely 30 movements ahead. * Improves FPS. @@ -958,22 +938,42 @@ public final class Settings { /** * The color of all selections */ - public final Setting colorSelection = new Setting<>(Color.GREEN); + public final Setting colorSelection = new Setting<>(Color.CYAN); /** * The color of the selection pos 1 */ - public final Setting colorSelectionPos1 = new Setting<>(Color.PINK); + public final Setting colorSelectionPos1 = new Setting<>(Color.BLACK); /** * The color of the selection pos 2 */ - public final Setting colorSelectionPos2 = new Setting<>(Color.PINK); + public final Setting colorSelectionPos2 = new Setting<>(Color.ORANGE); /** - * The opacity of the selection. The default (0.4) is what's used for goals and such + * The opacity of the selection. 0 is completely transparent, 1 is completely opaque */ - public final Setting selectionOpacity = new Setting<>(.4f); + public final Setting selectionOpacity = new Setting<>(.5f); + + /** + * Line width of the goal when rendered, in pixels + */ + public final Setting selectionLineWidth = new Setting<>(1F); + + /** + * Render selections + */ + public final Setting renderSelection = new Setting<>(true); + + /** + * Ignore depth when rendering selections + */ + public final Setting renderSelectionIgnoreDepth = new Setting<>(true); + + /** + * Render selection corners + */ + public final Setting renderSelectionCorners = new Setting<>(true); /** diff --git a/src/api/java/baritone/api/utils/IRenderer.java b/src/api/java/baritone/api/utils/IRenderer.java index 7bdb970e..5fb024ea 100644 --- a/src/api/java/baritone/api/utils/IRenderer.java +++ b/src/api/java/baritone/api/utils/IRenderer.java @@ -25,12 +25,16 @@ public interface IRenderer { IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone(); Settings settings = BaritoneAPI.getSettings(); + static void glColor(Color color, float alpha) { + float[] colorComponents = color.getColorComponents(null); + GlStateManager.color(colorComponents[0], colorComponents[1], colorComponents[2], alpha); + } + static void startLines(Color color, float alpha, float lineWidth, boolean ignoreDepth) { GlStateManager.enableBlend(); GlStateManager.disableLighting(); GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); - float[] colorComponents = color.getColorComponents(null); - GlStateManager.color(colorComponents[0], colorComponents[1], colorComponents[2], alpha); + glColor(color, alpha); GlStateManager.glLineWidth(lineWidth); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); @@ -55,10 +59,8 @@ public interface IRenderer { GlStateManager.disableBlend(); } - static void drawAABB(AxisAlignedBB aabb, float expand) { - AxisAlignedBB toDraw = aabb - .offset(-renderManager.viewerPosX, -renderManager.viewerPosY, -renderManager.viewerPosZ) - .grow(expand, expand, expand); + static void drawAABB(AxisAlignedBB aabb) { + AxisAlignedBB toDraw = aabb.offset(-renderManager.viewerPosX, -renderManager.viewerPosY, -renderManager.viewerPosZ); buffer.begin(GL_LINES, DefaultVertexFormats.POSITION); // bottom @@ -91,7 +93,7 @@ public interface IRenderer { tessellator.draw(); } - static void drawAABB(AxisAlignedBB aabb) { - drawAABB(aabb, 0.002f); + static void drawAABB(AxisAlignedBB aabb, float expand) { + drawAABB(aabb.grow(expand, expand, expand)); } } diff --git a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java index eb09895d..446724dc 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SelCommand.java @@ -365,11 +365,11 @@ public class SelCommand extends Command { Color color = settings.colorSelectionPos1.value; float opacity = settings.selectionOpacity.value; - float lineWidth = settings.selectionRenderLineWidthPixels.value; + float lineWidth = settings.selectionLineWidth.value; boolean ignoreDepth = settings.renderSelectionIgnoreDepth.value; IRenderer.startLines(color, opacity, lineWidth, ignoreDepth); - IRenderer.drawAABB(new AxisAlignedBB(pos1, pos1.add(1, 1, 1)), -.01f); + IRenderer.drawAABB(new AxisAlignedBB(pos1, pos1.add(1, 1, 1))); IRenderer.endLines(ignoreDepth); } } diff --git a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java b/src/api/java/baritone/api/utils/command/defaults/SetCommand.java index f343c56e..90f4e351 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/SetCommand.java @@ -61,30 +61,24 @@ public class SetCommand extends Command { boolean viewModified = asList("m", "mod", "modified").contains(arg); boolean viewAll = asList("all", "l", "list").contains(arg); - boolean paginate = viewModified | viewAll; + boolean paginate = viewModified || viewAll; if (paginate) { String search = args.has() && args.peekAsOrNull(Integer.class) == null ? args.getString() : ""; args.requireMax(1); List toPaginate = - viewModified - ? SettingsUtil.modifiedSettings(settings) - : settings.allSettings.stream() + (viewModified ? SettingsUtil.modifiedSettings(settings) : settings.allSettings).stream() .filter(s -> !s.getName().equals("logger")) .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.toCollection(ArrayList::new)); - toPaginate.sort((setting1, setting2) -> String.CASE_INSENSITIVE_ORDER.compare( - setting1.getName(), - setting2.getName() - )); - Paginator.paginate( args, new Paginator<>(toPaginate), () -> logDirect( !search.isEmpty() - ? String.format("All settings containing the string '%s':", search) + ? String.format("All %ssettings containing the string '%s':", viewModified ? "modified " : "", search) : String.format("All %ssettings:", viewModified ? "modified " : "") ), setting -> new TextComponentString(setting.getName()) {{ diff --git a/src/main/java/baritone/selection/SelectionRenderer.java b/src/main/java/baritone/selection/SelectionRenderer.java index 4d0fd9a7..a696fe67 100644 --- a/src/main/java/baritone/selection/SelectionRenderer.java +++ b/src/main/java/baritone/selection/SelectionRenderer.java @@ -17,7 +17,7 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener { public static void renderSelections(ISelection[] selections) { float opacity = settings.selectionOpacity.value; boolean ignoreDepth = settings.renderSelectionIgnoreDepth.value; - float lineWidth = settings.selectionRenderLineWidthPixels.value; + float lineWidth = settings.selectionLineWidth.value; if (!settings.renderSelection.value) { return; @@ -26,26 +26,21 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener { IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth, ignoreDepth); for (ISelection selection : selections) { - IRenderer.drawAABB(selection.aabb()); + IRenderer.drawAABB(selection.aabb(), .005f); } - IRenderer.endLines(ignoreDepth); + if (settings.renderSelectionCorners.value) { + IRenderer.glColor(settings.colorSelectionPos1.value, opacity); - if (!settings.renderSelectionCorners.value) { - return; - } + for (ISelection selection : selections) { + IRenderer.drawAABB(new AxisAlignedBB(selection.pos1(), selection.pos1().add(1, 1, 1))); + } - IRenderer.startLines(settings.colorSelectionPos1.value, opacity, lineWidth, ignoreDepth); + IRenderer.glColor(settings.colorSelectionPos2.value, opacity); - for (ISelection selection : selections) { - IRenderer.drawAABB(new AxisAlignedBB(selection.pos1(), selection.pos1().add(1, 1, 1)), -.01f); - } - - IRenderer.endLines(ignoreDepth); - IRenderer.startLines(settings.colorSelectionPos2.value, opacity, lineWidth, ignoreDepth); - - for (ISelection selection : selections) { - IRenderer.drawAABB(new AxisAlignedBB(selection.pos2(), selection.pos2().add(1, 1, 1)), -.01f); + for (ISelection selection : selections) { + IRenderer.drawAABB(new AxisAlignedBB(selection.pos2(), selection.pos2().add(1, 1, 1))); + } } IRenderer.endLines(ignoreDepth); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 9ebb58d4..3d141216 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -35,7 +35,6 @@ import baritone.behavior.PathingBehavior; import baritone.pathing.path.PathExecutor; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.tileentity.TileEntityBeaconRenderer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.Entity; @@ -162,8 +161,7 @@ public final class PathRenderer implements IRenderer { alpha = 0.4F * (1.0F - (float) (i - fadeStart) / (float) (fadeEnd - fadeStart)); } - float[] components = color.getComponents(null); - GlStateManager.color(components[0], components[1], components[2], alpha); + IRenderer.glColor(color, alpha); } drawLine(start.x, start.y, start.z, end.x, end.y, end.z); @@ -207,7 +205,7 @@ public final class PathRenderer implements IRenderer { toDraw = state.getSelectedBoundingBox(player.world, pos); } - IRenderer.drawAABB(toDraw); + IRenderer.drawAABB(toDraw, .002f); }); IRenderer.endLines(settings.renderSelectionBoxesIgnoreDepth.value); From 5ee1e738f404a924b78a9f6bec0144566b362df5 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Wed, 4 Sep 2019 02:30:24 -0700 Subject: [PATCH 617/682] Fix RelativePath and build command --- .../utils/command/datatypes/RelativeFile.java | 32 ++++++++++++++++--- .../utils/command/defaults/BuildCommand.java | 21 +++++++++--- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index b612e342..b47983b0 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -3,6 +3,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.io.File; +import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.InvalidPathException; import java.nio.file.Path; @@ -33,22 +34,45 @@ public class RelativeFile implements IDatatypePost { return Stream.empty(); } - public static Stream tabComplete(ArgConsumer consumer, File base) { + /** + * Seriously + * + * @param file File + * @return Canonical file of file + * @author LoganDark and his hate of checked exceptions + */ + private static File SHUT_THE_FUCK_UP_IOEXCEPTION_NOBODY_LIKES_YOU(File file) { + try { + return file.getCanonicalFile(); + } catch (IOException e) { + throw new RuntimeException("Fuck you", e); + } + } + + public static Stream tabComplete(ArgConsumer consumer, File base0) { + // I will not make the caller deal with this, seriously + // Tab complete code is beautiful and I'm not going to bloat it with dumb ass checked exception bullshit + File base = SHUT_THE_FUCK_UP_IOEXCEPTION_NOBODY_LIKES_YOU(base0); String currentPathStringThing = consumer.getString(); Path currentPath = FileSystems.getDefault().getPath(currentPathStringThing); Path basePath = currentPath.isAbsolute() ? currentPath.getRoot() : base.toPath(); boolean useParent = !currentPathStringThing.isEmpty() && !currentPathStringThing.endsWith(File.separator); File currentFile = currentPath.isAbsolute() ? currentPath.toFile() : new File(base, currentPathStringThing); - return Arrays.stream(Objects.requireNonNull((useParent ? currentFile.getParentFile() : currentFile).listFiles())) + return Arrays.stream(Objects.requireNonNull(SHUT_THE_FUCK_UP_IOEXCEPTION_NOBODY_LIKES_YOU( + useParent + ? currentFile.getParentFile() + : currentFile + ).listFiles())) .map(f -> (currentPath.isAbsolute() ? f : basePath.relativize(f.toPath()).toString()) + (f.isDirectory() ? File.separator : "")) - .filter(s -> s.toLowerCase(Locale.US).startsWith(currentPathStringThing.toLowerCase(Locale.US))); + .filter(s -> s.toLowerCase(Locale.US).startsWith(currentPathStringThing.toLowerCase(Locale.US))) + .filter(s -> !s.contains(" ")); } @Override public File apply(File original) { - return original.toPath().resolve(path).toFile(); + return SHUT_THE_FUCK_UP_IOEXCEPTION_NOBODY_LIKES_YOU(original.toPath().resolve(path).toFile()); } public static File gameDir() { diff --git a/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java b/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java index e7fd614e..c18cc1a4 100644 --- a/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java +++ b/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java @@ -21,22 +21,33 @@ import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeBlockPos; +import baritone.api.utils.command.datatypes.RelativeFile; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.client.Minecraft; +import java.io.File; import java.util.List; +import java.util.Locale; import java.util.stream.Stream; import static java.util.Arrays.asList; public class BuildCommand extends Command { + private static final File schematicsDir = new File(Minecraft.getMinecraft().gameDir, "schematics"); + public BuildCommand() { super("build", "Build a schematic"); } @Override protected void executed(String label, ArgConsumer args, Settings settings) { - String filename = String.format("%s.schematic", args.getString()); + File file = args.getDatatypePost(RelativeFile.class, schematicsDir).getAbsoluteFile(); + + if (!file.getName().toLowerCase(Locale.US).endsWith(".schematic")) { + file = new File(file.getAbsolutePath() + ".schematic"); + } + BetterBlockPos origin = ctx.playerFeet(); BetterBlockPos buildOrigin; @@ -48,18 +59,20 @@ public class BuildCommand extends Command { buildOrigin = origin; } - boolean success = baritone.getBuilderProcess().build(filename, buildOrigin); + boolean success = baritone.getBuilderProcess().build(file.getName(), file, buildOrigin); if (!success) { throw new CommandInvalidStateException("Couldn't load the schematic"); } - logDirect(String.format("Successfully loaded schematic '%s' for building\nOrigin: %s", filename, buildOrigin)); + logDirect(String.format("Successfully loaded schematic for building\nOrigin: %s", buildOrigin)); } @Override protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { - if (args.has(2)) { + if (args.hasExactlyOne()) { + return RelativeFile.tabComplete(args, schematicsDir); + } else if (args.has(2)) { args.get(); return args.tabCompleteDatatype(RelativeBlockPos.class); From daa0d0c859287d2de0263a055227b3d478401e0b Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Wed, 4 Sep 2019 09:16:36 -0700 Subject: [PATCH 618/682] copyright notices --- .../java/baritone/api/accessor/IItemStack.java | 17 +++++++++++++++++ .../api/event/events/type/Overrideable.java | 17 +++++++++++++++++ .../api/schematic/AbstractSchematic.java | 17 +++++++++++++++++ .../api/schematic/CompositeSchematic.java | 17 +++++++++++++++++ .../api/schematic/CompositeSchematicEntry.java | 17 +++++++++++++++++ .../api/schematic/FillBomSchematic.java | 17 +++++++++++++++++ .../baritone/api/schematic/MaskSchematic.java | 17 +++++++++++++++++ .../api/schematic/ReplaceSchematic.java | 17 +++++++++++++++++ .../baritone/api/schematic/ShellSchematic.java | 17 +++++++++++++++++ .../baritone/api/schematic/WallsSchematic.java | 17 +++++++++++++++++ .../baritone/api/selection/ISelection.java | 17 +++++++++++++++++ .../api/selection/ISelectionManager.java | 17 +++++++++++++++++ .../api/utils/BlockOptionalMetaLookup.java | 17 +++++++++++++++++ src/api/java/baritone/api/utils/IRenderer.java | 17 +++++++++++++++++ .../java/baritone/api/utils/command/Lol.java | 17 +++++++++++++++++ .../api/utils/command/datatypes/BlockById.java | 17 +++++++++++++++++ .../command/datatypes/EntityClassById.java | 17 +++++++++++++++++ .../datatypes/ForBlockOptionalMeta.java | 17 +++++++++++++++++ .../utils/command/datatypes/ForEnumFacing.java | 17 +++++++++++++++++ .../utils/command/datatypes/ForWaypoints.java | 17 +++++++++++++++++ .../api/utils/command/datatypes/IDatatype.java | 17 +++++++++++++++++ .../utils/command/datatypes/IDatatypeFor.java | 17 +++++++++++++++++ .../utils/command/datatypes/IDatatypePost.java | 17 +++++++++++++++++ .../command/datatypes/PlayerByUsername.java | 17 +++++++++++++++++ .../command/datatypes/RelativeBlockPos.java | 17 +++++++++++++++++ .../command/datatypes/RelativeCoordinate.java | 17 +++++++++++++++++ .../utils/command/datatypes/RelativeFile.java | 17 +++++++++++++++++ .../utils/command/datatypes/RelativeGoal.java | 17 +++++++++++++++++ .../command/datatypes/RelativeGoalBlock.java | 17 +++++++++++++++++ .../command/datatypes/RelativeGoalXZ.java | 18 +++++++++++++++++- .../command/datatypes/RelativeGoalYLevel.java | 18 +++++++++++++++++- .../command/defaults/PauseResumeCommands.java | 17 +++++++++++++++++ 32 files changed, 544 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/accessor/IItemStack.java b/src/api/java/baritone/api/accessor/IItemStack.java index 68439905..ac0f760f 100644 --- a/src/api/java/baritone/api/accessor/IItemStack.java +++ b/src/api/java/baritone/api/accessor/IItemStack.java @@ -1,3 +1,20 @@ +/* + * 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.accessor; public interface IItemStack { diff --git a/src/api/java/baritone/api/event/events/type/Overrideable.java b/src/api/java/baritone/api/event/events/type/Overrideable.java index 987e64f7..1ec29c67 100644 --- a/src/api/java/baritone/api/event/events/type/Overrideable.java +++ b/src/api/java/baritone/api/event/events/type/Overrideable.java @@ -1,3 +1,20 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + package baritone.api.event.events.type; /** diff --git a/src/api/java/baritone/api/schematic/AbstractSchematic.java b/src/api/java/baritone/api/schematic/AbstractSchematic.java index 4a7e9b25..cee9ff9a 100644 --- a/src/api/java/baritone/api/schematic/AbstractSchematic.java +++ b/src/api/java/baritone/api/schematic/AbstractSchematic.java @@ -1,3 +1,20 @@ +/* + * 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 baritone.api.IBaritone; diff --git a/src/api/java/baritone/api/schematic/CompositeSchematic.java b/src/api/java/baritone/api/schematic/CompositeSchematic.java index deb9f5fe..bb4c6cc1 100644 --- a/src/api/java/baritone/api/schematic/CompositeSchematic.java +++ b/src/api/java/baritone/api/schematic/CompositeSchematic.java @@ -1,3 +1,20 @@ +/* + * 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 baritone.api.IBaritone; diff --git a/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java b/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java index c34cd112..6e97e41f 100644 --- a/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java +++ b/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java @@ -1,3 +1,20 @@ +/* + * 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 baritone.api.utils.ISchematic; diff --git a/src/api/java/baritone/api/schematic/FillBomSchematic.java b/src/api/java/baritone/api/schematic/FillBomSchematic.java index a9b5f356..6fc9eff8 100644 --- a/src/api/java/baritone/api/schematic/FillBomSchematic.java +++ b/src/api/java/baritone/api/schematic/FillBomSchematic.java @@ -1,3 +1,20 @@ +/* + * 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 baritone.api.IBaritone; diff --git a/src/api/java/baritone/api/schematic/MaskSchematic.java b/src/api/java/baritone/api/schematic/MaskSchematic.java index 133e4e62..34b1478b 100644 --- a/src/api/java/baritone/api/schematic/MaskSchematic.java +++ b/src/api/java/baritone/api/schematic/MaskSchematic.java @@ -1,3 +1,20 @@ +/* + * 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 baritone.api.IBaritone; diff --git a/src/api/java/baritone/api/schematic/ReplaceSchematic.java b/src/api/java/baritone/api/schematic/ReplaceSchematic.java index 2d13f1eb..d29179c8 100644 --- a/src/api/java/baritone/api/schematic/ReplaceSchematic.java +++ b/src/api/java/baritone/api/schematic/ReplaceSchematic.java @@ -1,3 +1,20 @@ +/* + * 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 baritone.api.IBaritone; diff --git a/src/api/java/baritone/api/schematic/ShellSchematic.java b/src/api/java/baritone/api/schematic/ShellSchematic.java index c6c1bcf2..aa249ea0 100644 --- a/src/api/java/baritone/api/schematic/ShellSchematic.java +++ b/src/api/java/baritone/api/schematic/ShellSchematic.java @@ -1,3 +1,20 @@ +/* + * 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 baritone.api.IBaritone; diff --git a/src/api/java/baritone/api/schematic/WallsSchematic.java b/src/api/java/baritone/api/schematic/WallsSchematic.java index ed66e2fc..bc632564 100644 --- a/src/api/java/baritone/api/schematic/WallsSchematic.java +++ b/src/api/java/baritone/api/schematic/WallsSchematic.java @@ -1,3 +1,20 @@ +/* + * 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 baritone.api.IBaritone; diff --git a/src/api/java/baritone/api/selection/ISelection.java b/src/api/java/baritone/api/selection/ISelection.java index 4067c307..4771c2e9 100644 --- a/src/api/java/baritone/api/selection/ISelection.java +++ b/src/api/java/baritone/api/selection/ISelection.java @@ -1,3 +1,20 @@ +/* + * 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.selection; import baritone.api.utils.BetterBlockPos; diff --git a/src/api/java/baritone/api/selection/ISelectionManager.java b/src/api/java/baritone/api/selection/ISelectionManager.java index 763714e7..e69549f9 100644 --- a/src/api/java/baritone/api/selection/ISelectionManager.java +++ b/src/api/java/baritone/api/selection/ISelectionManager.java @@ -1,3 +1,20 @@ +/* + * 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.selection; import baritone.api.utils.BetterBlockPos; diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index 2e7cf42e..44c756d1 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -1,3 +1,20 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + package baritone.api.utils; import net.minecraft.block.Block; diff --git a/src/api/java/baritone/api/utils/IRenderer.java b/src/api/java/baritone/api/utils/IRenderer.java index 5fb024ea..534c509e 100644 --- a/src/api/java/baritone/api/utils/IRenderer.java +++ b/src/api/java/baritone/api/utils/IRenderer.java @@ -1,3 +1,20 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + package baritone.api.utils; import baritone.api.BaritoneAPI; diff --git a/src/api/java/baritone/api/utils/command/Lol.java b/src/api/java/baritone/api/utils/command/Lol.java index 5c56544e..47bb8336 100644 --- a/src/api/java/baritone/api/utils/command/Lol.java +++ b/src/api/java/baritone/api/utils/command/Lol.java @@ -1,3 +1,20 @@ +/* + * 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.command; import java.net.URI; diff --git a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java index 469e9caf..13e3d686 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java index dc9d0bae..ea22dc90 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java b/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java index 7226d0cb..e44b7652 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.utils.BlockOptionalMeta; diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java index f65f1c55..2dbadd9d 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java index 6cc358e4..90a1c71c 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.BaritoneAPI; diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java index 35caeaa2..1684fd2f 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.utils.command.exception.CommandInvalidArgumentException; diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java index 313fd6b1..f0c4cb61 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; public interface IDatatypeFor extends IDatatype { diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java index 2168f25a..4e74f03e 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; public interface IDatatypePost extends IDatatype { diff --git a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java index 1d9a48dd..f38028bd 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java +++ b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.BaritoneAPI; diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java index 28c86e80..ab728ede 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.utils.BetterBlockPos; diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java index 3213a033..8d5cc70b 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index b47983b0..afc82978 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java index 13033549..a0f94cee 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.pathing.goals.Goal; diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java index 28ff08bb..1a907135 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java @@ -1,3 +1,20 @@ +/* + * 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.command.datatypes; import baritone.api.pathing.goals.Goal; diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java index 8607c512..7e9b85f9 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java @@ -1,6 +1,22 @@ +/* + * 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.command.datatypes; -import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java index 041eeded..9d00350e 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java @@ -1,6 +1,22 @@ +/* + * 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.command.datatypes; -import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalYLevel; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java b/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java index 283aba68..8696a2da 100644 --- a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java +++ b/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java @@ -1,3 +1,20 @@ +/* + * 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.command.defaults; import baritone.api.BaritoneAPI; From 69e3481a32c07b90e448414ba5e4a5eb976ce989 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Wed, 4 Sep 2019 11:17:36 -0700 Subject: [PATCH 619/682] move default commands to main module --- .../api/schematic/ReplaceSchematic.java | 2 +- .../utils/command/defaults/ExcCommand.java | 49 ------------------- .../utils/command/manager/CommandManager.java | 5 -- src/main/java/baritone/Baritone.java | 4 ++ .../utils/command/defaults/AxisCommand.java | 2 +- .../command/defaults/BlacklistCommand.java | 2 +- .../utils/command/defaults/BuildCommand.java | 2 +- .../utils/command/defaults/CancelCommand.java | 2 +- .../utils/command/defaults/ChestsCommand.java | 2 +- .../command/defaults/ClearareaCommand.java | 2 +- .../utils/command/defaults/ClickCommand.java | 2 +- .../utils/command/defaults/ComeCommand.java | 2 +- .../utils/command/defaults/CommandAlias.java | 2 +- .../command/defaults/DefaultCommands.java | 4 +- .../utils/command/defaults/EmptyCommand.java | 3 +- .../command/defaults/ExploreCommand.java | 2 +- .../defaults/ExploreFilterCommand.java | 2 +- .../utils/command/defaults/FarmCommand.java | 2 +- .../utils/command/defaults/FindCommand.java | 2 +- .../utils/command/defaults/FollowCommand.java | 2 +- .../command/defaults/ForceCancelCommand.java | 2 +- .../utils/command/defaults/GcCommand.java | 2 +- .../utils/command/defaults/GoalCommand.java | 2 +- .../utils/command/defaults/HelpCommand.java | 2 +- .../utils/command/defaults/InvertCommand.java | 2 +- .../utils/command/defaults/MineCommand.java | 2 +- .../utils/command/defaults/PathCommand.java | 2 +- .../command/defaults/PauseResumeCommands.java | 2 +- .../utils/command/defaults/ProcCommand.java | 2 +- .../command/defaults/ReloadAllCommand.java | 2 +- .../utils/command/defaults/RenderCommand.java | 2 +- .../utils/command/defaults/RepackCommand.java | 2 +- .../command/defaults/SaveAllCommand.java | 2 +- .../command/defaults/SchematicaCommand.java | 2 +- .../utils/command/defaults/SelCommand.java | 2 +- .../utils/command/defaults/SetCommand.java | 2 +- .../command/defaults/ThisWayCommand.java | 2 +- .../utils/command/defaults/TunnelCommand.java | 2 +- .../command/defaults/VersionCommand.java | 2 +- .../command/defaults/WaypointsCommand.java | 2 +- 40 files changed, 42 insertions(+), 93 deletions(-) delete mode 100644 src/api/java/baritone/api/utils/command/defaults/ExcCommand.java rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/AxisCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/BlacklistCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/BuildCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/CancelCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/ChestsCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/ClearareaCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/ClickCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/ComeCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/CommandAlias.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/DefaultCommands.java (95%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/EmptyCommand.java (95%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/ExploreCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/ExploreFilterCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/FarmCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/FindCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/FollowCommand.java (99%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/ForceCancelCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/GcCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/GoalCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/HelpCommand.java (99%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/InvertCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/MineCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/PathCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/PauseResumeCommands.java (99%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/ProcCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/ReloadAllCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/RenderCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/RepackCommand.java (98%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/SaveAllCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/SchematicaCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/SelCommand.java (99%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/SetCommand.java (99%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/ThisWayCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/TunnelCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/VersionCommand.java (97%) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/defaults/WaypointsCommand.java (99%) diff --git a/src/api/java/baritone/api/schematic/ReplaceSchematic.java b/src/api/java/baritone/api/schematic/ReplaceSchematic.java index d29179c8..4c7ee546 100644 --- a/src/api/java/baritone/api/schematic/ReplaceSchematic.java +++ b/src/api/java/baritone/api/schematic/ReplaceSchematic.java @@ -29,7 +29,7 @@ public class ReplaceSchematic extends MaskSchematic { public ReplaceSchematic(IBaritone baritone, ISchematic schematic, BlockOptionalMetaLookup filter) { super(baritone, schematic); this.filter = filter; - this.cache = new boolean[lengthZ()][heightY()][widthX()]; + this.cache = new boolean[widthX()][heightY()][lengthZ()]; } protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { diff --git a/src/api/java/baritone/api/utils/command/defaults/ExcCommand.java b/src/api/java/baritone/api/utils/command/defaults/ExcCommand.java deleted file mode 100644 index 4c05bd02..00000000 --- a/src/api/java/baritone/api/utils/command/defaults/ExcCommand.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.api.utils.command.defaults; - -import baritone.api.Settings; -import baritone.api.utils.command.Command; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; - -import java.util.Collections; -import java.util.List; -import java.util.stream.Stream; - -public class ExcCommand extends Command { - public ExcCommand() { - super("exc", "Throw an unhandled exception"); - } - - @Override - protected void executed(String label, ArgConsumer args, Settings settings) { - args.requireMax(0); - - throw new RuntimeException("HI THERE"); - } - - @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { - return Stream.empty(); - } - - @Override - public List getLongDesc() { - return Collections.emptyList(); - } -} diff --git a/src/api/java/baritone/api/utils/command/manager/CommandManager.java b/src/api/java/baritone/api/utils/command/manager/CommandManager.java index 75dff566..287acaa5 100644 --- a/src/api/java/baritone/api/utils/command/manager/CommandManager.java +++ b/src/api/java/baritone/api/utils/command/manager/CommandManager.java @@ -19,7 +19,6 @@ package baritone.api.utils.command.manager; import baritone.api.utils.command.Command; import baritone.api.utils.command.argument.CommandArgument; -import baritone.api.utils.command.defaults.DefaultCommands; import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.registry.Registry; @@ -35,10 +34,6 @@ import static java.util.Objects.nonNull; public class CommandManager { public static final Registry REGISTRY = new Registry<>(); - static { - DefaultCommands.commands.forEach(REGISTRY::register); - } - /** * @param name The command name to search for. * @return The command, if found. diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index a0e19015..0b7e614f 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -24,12 +24,14 @@ import baritone.api.event.listener.IEventBus; import baritone.api.utils.command.BaritoneChatControl; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; +import baritone.api.utils.command.manager.CommandManager; import baritone.behavior.*; import baritone.cache.WorldProvider; import baritone.event.GameEventHandler; import baritone.process.*; import baritone.selection.SelectionManager; import baritone.utils.*; +import baritone.utils.command.defaults.DefaultCommands; import baritone.utils.player.PrimaryPlayerContext; import net.minecraft.client.Minecraft; @@ -111,6 +113,8 @@ public class Baritone implements IBaritone { memoryBehavior = new MemoryBehavior(this); inventoryBehavior = new InventoryBehavior(this); inputOverrideHandler = new InputOverrideHandler(this); + + DefaultCommands.commands.forEach(CommandManager.REGISTRY::register); new BaritoneChatControl(this); } diff --git a/src/api/java/baritone/api/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/AxisCommand.java rename to src/main/java/baritone/utils/command/defaults/AxisCommand.java index 367bc698..59f63867 100644 --- a/src/api/java/baritone/api/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; diff --git a/src/api/java/baritone/api/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/BlacklistCommand.java rename to src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index e51fa5fc..bb19480f 100644 --- a/src/api/java/baritone/api/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.process.IGetToBlockProcess; diff --git a/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/BuildCommand.java rename to src/main/java/baritone/utils/command/defaults/BuildCommand.java index c18cc1a4..1c64f118 100644 --- a/src/api/java/baritone/api/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; diff --git a/src/api/java/baritone/api/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/CancelCommand.java rename to src/main/java/baritone/utils/command/defaults/CancelCommand.java index 416feae5..a07bfc3b 100644 --- a/src/api/java/baritone/api/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java rename to src/main/java/baritone/utils/command/defaults/ChestsCommand.java index a9ca11fb..6d4fac07 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.cache.IRememberedInventory; diff --git a/src/api/java/baritone/api/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/ClearareaCommand.java rename to src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index f3da2913..974a9867 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; diff --git a/src/api/java/baritone/api/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/ClickCommand.java rename to src/main/java/baritone/utils/command/defaults/ClickCommand.java index 120b5867..559752bd 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/ComeCommand.java rename to src/main/java/baritone/utils/command/defaults/ComeCommand.java index 9817afb7..0b5f40ce 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.pathing.goals.GoalBlock; diff --git a/src/api/java/baritone/api/utils/command/defaults/CommandAlias.java b/src/main/java/baritone/utils/command/defaults/CommandAlias.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/CommandAlias.java rename to src/main/java/baritone/utils/command/defaults/CommandAlias.java index 94fcd4ed..0ffaf427 100644 --- a/src/api/java/baritone/api/utils/command/defaults/CommandAlias.java +++ b/src/main/java/baritone/utils/command/defaults/CommandAlias.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java similarity index 95% rename from src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java rename to src/main/java/baritone/utils/command/defaults/DefaultCommands.java index d640f079..a52d252a 100644 --- a/src/api/java/baritone/api/utils/command/defaults/DefaultCommands.java +++ b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java @@ -15,9 +15,10 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.utils.command.Command; +import baritone.api.utils.command.manager.CommandManager; import java.util.Collections; import java.util.List; @@ -30,7 +31,6 @@ public class DefaultCommands { new SetCommand(), new CommandAlias(asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), new CommandAlias("reset", "Reset all settings or just one", "set reset"), - new ExcCommand(), // TODO: remove this debug command... eventually new GoalCommand(), new PathCommand(), new ProcCommand(), diff --git a/src/api/java/baritone/api/utils/command/defaults/EmptyCommand.java b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java similarity index 95% rename from src/api/java/baritone/api/utils/command/defaults/EmptyCommand.java rename to src/main/java/baritone/utils/command/defaults/EmptyCommand.java index 1b5934ba..15951182 100644 --- a/src/api/java/baritone/api/utils/command/defaults/EmptyCommand.java +++ b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java @@ -15,10 +15,9 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; -import baritone.api.utils.Helper; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/api/java/baritone/api/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/ExploreCommand.java rename to src/main/java/baritone/utils/command/defaults/ExploreCommand.java index a4b2d746..24e02f26 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.pathing.goals.GoalXZ; diff --git a/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java rename to src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index 1dd48512..848e913b 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/FarmCommand.java rename to src/main/java/baritone/utils/command/defaults/FarmCommand.java index 1828dec3..8c265912 100644 --- a/src/api/java/baritone/api/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/FindCommand.java rename to src/main/java/baritone/utils/command/defaults/FindCommand.java index 1f9ce9a7..6fd620d1 100644 --- a/src/api/java/baritone/api/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; diff --git a/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java similarity index 99% rename from src/api/java/baritone/api/utils/command/defaults/FollowCommand.java rename to src/main/java/baritone/utils/command/defaults/FollowCommand.java index 6cfaa59b..0107ee3b 100644 --- a/src/api/java/baritone/api/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/ForceCancelCommand.java rename to src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index e78cb696..685db0c3 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.behavior.IPathingBehavior; diff --git a/src/api/java/baritone/api/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/GcCommand.java rename to src/main/java/baritone/utils/command/defaults/GcCommand.java index 7790f2a4..17e241cf 100644 --- a/src/api/java/baritone/api/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/GoalCommand.java rename to src/main/java/baritone/utils/command/defaults/GoalCommand.java index 692d6422..883aed7e 100644 --- a/src/api/java/baritone/api/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; diff --git a/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java similarity index 99% rename from src/api/java/baritone/api/utils/command/defaults/HelpCommand.java rename to src/main/java/baritone/utils/command/defaults/HelpCommand.java index a4ec3f23..16bb128a 100644 --- a/src/api/java/baritone/api/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/InvertCommand.java rename to src/main/java/baritone/utils/command/defaults/InvertCommand.java index da420db8..a29f2c9b 100644 --- a/src/api/java/baritone/api/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; diff --git a/src/api/java/baritone/api/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/MineCommand.java rename to src/main/java/baritone/utils/command/defaults/MineCommand.java index 1cd869d8..ebfb7fe1 100644 --- a/src/api/java/baritone/api/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.BlockOptionalMeta; diff --git a/src/api/java/baritone/api/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/PathCommand.java rename to src/main/java/baritone/utils/command/defaults/PathCommand.java index c184db7f..d65819fa 100644 --- a/src/api/java/baritone/api/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; diff --git a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java similarity index 99% rename from src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java rename to src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index 8696a2da..2b3919e4 100644 --- a/src/api/java/baritone/api/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.BaritoneAPI; import baritone.api.Settings; diff --git a/src/api/java/baritone/api/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/ProcCommand.java rename to src/main/java/baritone/utils/command/defaults/ProcCommand.java index fdbb0a40..469089f6 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.pathing.calc.IPathingControlManager; diff --git a/src/api/java/baritone/api/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/ReloadAllCommand.java rename to src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index 633701ba..73a0245d 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/RenderCommand.java rename to src/main/java/baritone/utils/command/defaults/RenderCommand.java index 82398b35..3fa07ca3 100644 --- a/src/api/java/baritone/api/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; diff --git a/src/api/java/baritone/api/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java similarity index 98% rename from src/api/java/baritone/api/utils/command/defaults/RepackCommand.java rename to src/main/java/baritone/utils/command/defaults/RepackCommand.java index d371603e..0cf2ae78 100644 --- a/src/api/java/baritone/api/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.cache.ICachedWorld; diff --git a/src/api/java/baritone/api/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/SaveAllCommand.java rename to src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index 163408cc..a34a6a58 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/SchematicaCommand.java rename to src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index 2522674f..edef29a7 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java similarity index 99% rename from src/api/java/baritone/api/utils/command/defaults/SelCommand.java rename to src/main/java/baritone/utils/command/defaults/SelCommand.java index 446724dc..c6529d3d 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.event.events.RenderEvent; diff --git a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java similarity index 99% rename from src/api/java/baritone/api/utils/command/defaults/SetCommand.java rename to src/main/java/baritone/utils/command/defaults/SetCommand.java index 90f4e351..3bf6267e 100644 --- a/src/api/java/baritone/api/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.SettingsUtil; diff --git a/src/api/java/baritone/api/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/ThisWayCommand.java rename to src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index 5eeeeba9..d16dbd94 100644 --- a/src/api/java/baritone/api/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.pathing.goals.GoalXZ; diff --git a/src/api/java/baritone/api/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/TunnelCommand.java rename to src/main/java/baritone/utils/command/defaults/TunnelCommand.java index 62b47562..00d9e67c 100644 --- a/src/api/java/baritone/api/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; diff --git a/src/api/java/baritone/api/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java similarity index 97% rename from src/api/java/baritone/api/utils/command/defaults/VersionCommand.java rename to src/main/java/baritone/utils/command/defaults/VersionCommand.java index a232ddc3..6cd06f9c 100644 --- a/src/api/java/baritone/api/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.utils.command.Command; diff --git a/src/api/java/baritone/api/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java similarity index 99% rename from src/api/java/baritone/api/utils/command/defaults/WaypointsCommand.java rename to src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 78da79af..894b23a0 100644 --- a/src/api/java/baritone/api/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.defaults; +package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.cache.IWaypoint; From 243e6e3b997d5343b8ce8355b81cea4b97cd6215 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 4 Sep 2019 17:15:27 -0700 Subject: [PATCH 620/682] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d0a6cc3c..19ec0e87 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ ![Lines of Code](https://tokei.rs/b1/github/cabaletta/baritone?category=code) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) -[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.8%20/%20v1.3.4%20/%20v1.4.1-brightgreen.svg)](https://impactdevelopment.github.io/) +[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.8%20/%20v1.3.4%20/%20v1.4.1-brightgreen.svg)](https://impactclient.net/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/) [![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%20integration-v1.3.4%20/%20v1.4.1-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) @@ -29,9 +29,9 @@ A Minecraft pathfinder bot. -Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. +Baritone is the pathfinding system used in [Impact](https://impactclient.net/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do. -The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the v1.2.* forge api jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. +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.* forge api jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it. For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1). Or [with optifine](https://github.com/cabaletta/baritone/issues/797). From f8d4e22b134d7f3ee100b145e98fea152790e930 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 4 Sep 2019 17:15:46 -0700 Subject: [PATCH 621/682] Update SETUP.md --- SETUP.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SETUP.md b/SETUP.md index 909da5a8..1fcaf1d2 100644 --- a/SETUP.md +++ b/SETUP.md @@ -1,6 +1,6 @@ # Installation -The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. +The easiest way to install Baritone is to install [Impact](https://impactclient.net/), which comes with Baritone. For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1). @@ -103,4 +103,4 @@ $ gradlew build ![Image](https://i.imgur.com/PE6r9iN.png) -- Double click on **build** to run it \ No newline at end of file +- Double click on **build** to run it From 8a001a2438cc4fd387009ea00052a901d643df68 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 6 Sep 2019 03:59:10 -0700 Subject: [PATCH 622/682] Review --- src/api/java/baritone/api/Settings.java | 2 +- .../Lol.java => accessor/IGuiScreen.java} | 4 +- .../api/behavior/IPathingBehavior.java | 4 +- .../java/baritone/api/cache/IWaypoint.java | 45 +- .../baritone/api/cache/IWorldScanner.java | 37 +- .../api/event/events/type/Overrideable.java | 4 +- .../api/pathing/goals/GoalInverted.java | 7 +- .../baritone/api/process/IBuilderProcess.java | 9 + .../api/schematic/AbstractSchematic.java | 34 +- .../api/schematic/CompositeSchematic.java | 4 +- ...llBomSchematic.java => FillSchematic.java} | 10 +- .../baritone/api/schematic/MaskSchematic.java | 6 +- .../api/schematic/ReplaceSchematic.java | 8 +- .../baritone/api/utils/BlockOptionalMeta.java | 78 +- .../api/utils/BlockOptionalMetaLookup.java | 6 + .../java/baritone/api/utils/BlockUtils.java | 7 +- .../api/utils/ExampleBaritoneControlOld.java | 770 ------------- src/api/java/baritone/api/utils/Helper.java | 43 +- .../baritone/api/utils/IPlayerContext.java | 8 + .../java/baritone/api/utils/ISchematic.java | 17 +- .../java/baritone/api/utils/SettingsUtil.java | 9 + .../utils/command/BaritoneChatControl.java | 71 +- .../baritone/api/utils/command/Command.java | 26 +- .../command/argparser/ArgParserManager.java | 62 +- .../command/argparser/DefaultArgParsers.java | 5 +- .../utils/command/argparser/IArgParser.java | 11 + .../command/argument/CommandArgument.java | 93 +- .../utils/command/datatypes/BlockById.java | 2 +- .../command/datatypes/EntityClassById.java | 2 +- .../utils/command/datatypes/ForWaypoints.java | 28 +- .../utils/command/datatypes/IDatatype.java | 21 +- .../command/datatypes/PlayerByUsername.java | 2 +- .../command/datatypes/RelativeCoordinate.java | 6 +- .../utils/command/datatypes/RelativeFile.java | 2 +- .../command/datatypes/RelativeGoalBlock.java | 1 - .../exception/CommandUnhandledException.java | 3 +- .../helpers/arguments/ArgConsumer.java | 1017 ++++++++++++++++- .../command/helpers/pagination/Paginator.java | 70 +- .../tabcomplete/TabCompleteHelper.java | 167 ++- .../api/utils/command/registry/Registry.java | 16 +- .../launch/mixins/MixinChatTabCompleter.java | 15 +- .../baritone/launch/mixins/MixinGuiChat.java | 6 +- .../launch/mixins/MixinGuiScreen.java | 4 +- .../launch/mixins/MixinItemStack.java | 10 +- .../mixins/MixinStateImplementation.java | 5 +- .../launch/mixins/MixinTabCompleter.java | 12 +- src/main/java/baritone/Baritone.java | 6 +- .../baritone/behavior/InventoryBehavior.java | 2 +- .../baritone/behavior/PathingBehavior.java | 5 - .../java/baritone/cache/WorldScanner.java | 44 +- .../pathing/movement/MovementHelper.java | 7 +- .../movement/movements/MovementAscend.java | 2 +- .../movement/movements/MovementParkour.java | 2 +- .../movement/movements/MovementTraverse.java | 2 +- .../java/baritone/process/BuilderProcess.java | 56 +- .../java/baritone/process/FollowProcess.java | 2 +- .../java/baritone/process/MineProcess.java | 7 +- .../baritone/selection/SelectionRenderer.java | 6 +- src/main/java/baritone/utils/GuiClick.java | 1 - .../java/baritone}/utils/IRenderer.java | 5 +- .../java/baritone/utils/PathRenderer.java | 3 +- .../utils/command/defaults/AxisCommand.java | 7 +- .../command/defaults/BlacklistCommand.java | 7 +- .../utils/command/defaults/BuildCommand.java | 7 +- .../utils/command/defaults/CancelCommand.java | 7 +- .../utils/command/defaults/ChestsCommand.java | 7 +- .../command/defaults/ClearareaCommand.java | 7 +- .../utils/command/defaults/ClickCommand.java | 7 +- .../utils/command/defaults/ComeCommand.java | 9 +- .../utils/command/defaults/CommandAlias.java | 12 +- .../command/defaults/DefaultCommands.java | 3 +- .../utils/command/defaults/EmptyCommand.java | 7 +- .../command/defaults/ExploreCommand.java | 7 +- .../defaults/ExploreFilterCommand.java | 7 +- .../utils/command/defaults/FarmCommand.java | 7 +- .../utils/command/defaults/FindCommand.java | 7 +- .../utils/command/defaults/FollowCommand.java | 7 +- .../command/defaults/ForceCancelCommand.java | 7 +- .../utils/command/defaults/GcCommand.java | 7 +- .../utils/command/defaults/GoalCommand.java | 7 +- .../utils/command/defaults/HelpCommand.java | 68 +- .../utils/command/defaults/InvertCommand.java | 7 +- .../utils/command/defaults/MineCommand.java | 17 +- .../utils/command/defaults/PathCommand.java | 9 +- .../command/defaults/PauseResumeCommands.java | 21 +- .../utils/command/defaults/ProcCommand.java | 7 +- .../command/defaults/ReloadAllCommand.java | 7 +- .../utils/command/defaults/RenderCommand.java | 7 +- .../utils/command/defaults/RepackCommand.java | 34 +- .../command/defaults/SaveAllCommand.java | 7 +- .../command/defaults/SchematicaCommand.java | 9 +- .../utils/command/defaults/SelCommand.java | 20 +- .../utils/command/defaults/SetCommand.java | 81 +- .../command/defaults/ThisWayCommand.java | 7 +- .../utils/command/defaults/TunnelCommand.java | 7 +- .../command/defaults/VersionCommand.java | 7 +- .../command/defaults/WaypointsCommand.java | 23 +- .../utils/schematic/FillSchematic.java | 5 +- .../baritone/utils/schematic/Schematic.java | 4 +- .../schematica/SchematicAdapter.java | 4 +- 100 files changed, 2065 insertions(+), 1341 deletions(-) rename src/api/java/baritone/api/{utils/command/Lol.java => accessor/IGuiScreen.java} (92%) rename src/api/java/baritone/api/schematic/{FillBomSchematic.java => FillSchematic.java} (84%) delete mode 100644 src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java rename src/{api/java/baritone/api => main/java/baritone}/utils/IRenderer.java (97%) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 1bdb1e39..2952ed64 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -495,7 +495,7 @@ public final class Settings { /** * Render the path as a line instead of a frickin thingy */ - public final Setting renderPathAsLine = new Setting<>(true); + public final Setting renderPathAsLine = new Setting<>(false); /** * Render the goal diff --git a/src/api/java/baritone/api/utils/command/Lol.java b/src/api/java/baritone/api/accessor/IGuiScreen.java similarity index 92% rename from src/api/java/baritone/api/utils/command/Lol.java rename to src/api/java/baritone/api/accessor/IGuiScreen.java index 47bb8336..3eed255f 100644 --- a/src/api/java/baritone/api/utils/command/Lol.java +++ b/src/api/java/baritone/api/accessor/IGuiScreen.java @@ -15,10 +15,10 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command; +package baritone.api.accessor; import java.net.URI; -public interface Lol { +public interface IGuiScreen { void openLink(URI url); } diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index 8890fdc3..5444bb83 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -74,7 +74,9 @@ public interface IPathingBehavior extends IBehavior { * is a pause in effect. * @see #isPathing() */ - boolean hasPath(); + default boolean hasPath() { + return getCurrent() != null; + } /** * Cancels the pathing behavior or the current path calculation, and all processes that could be controlling path. diff --git a/src/api/java/baritone/api/cache/IWaypoint.java b/src/api/java/baritone/api/cache/IWaypoint.java index 23df5d39..238b4d88 100644 --- a/src/api/java/baritone/api/cache/IWaypoint.java +++ b/src/api/java/baritone/api/cache/IWaypoint.java @@ -18,11 +18,14 @@ package baritone.api.cache; import baritone.api.utils.BetterBlockPos; -import org.apache.commons.lang3.ArrayUtils; import java.util.Arrays; import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Set; + +import static java.util.Arrays.asList; /** * A marker for a position in the world. @@ -99,13 +102,41 @@ public interface IWaypoint { } /** - * Finds a tag from one of the names that could be used to identify said tag. - * - * @param name The name of the tag - * @return The tag, if one is found, otherwise, {@code null} + * @return A name that can be passed to {@link #getByName(String)} to retrieve this tag */ - public static Tag fromString(String name) { - return TAG_LIST.stream().filter(tag -> ArrayUtils.contains(tag.names, name.toLowerCase())).findFirst().orElse(null); + public String getName() { + return names[0]; + } + + /** + * Gets a tag by one of its names. + * + * @param name The name to search for. + * @return The tag, if found, or null. + */ + public static Tag getByName(String name) { + for (Tag action : Tag.values()) { + for (String alias : action.names) { + if (alias.equalsIgnoreCase(name)) { + return action; + } + } + } + + return null; + } + + /** + * @return All tag names. + */ + public static String[] getAllNames() { + Set names = new HashSet<>(); + + for (Tag tag : Tag.values()) { + names.addAll(asList(tag.names)); + } + + return names.toArray(new String[0]); } } } diff --git a/src/api/java/baritone/api/cache/IWorldScanner.java b/src/api/java/baritone/api/cache/IWorldScanner.java index 009268fb..325d4bd0 100644 --- a/src/api/java/baritone/api/cache/IWorldScanner.java +++ b/src/api/java/baritone/api/cache/IWorldScanner.java @@ -34,12 +34,11 @@ public interface IWorldScanner { /** * Scans the world, up to the specified max chunk radius, for the specified blocks. * - * @param ctx The {@link IPlayerContext} containing player and world info that the - * scan is based upon + * @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon * @param filter The blocks to scan for * @param max The maximum number of blocks to scan before cutoff - * @param yLevelThreshold If a block is found within this Y level, the current result will be - * returned, if the value is negative, then this condition doesn't apply. + * @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value + * is negative, then this condition doesn't apply. * @param maxSearchRadius The maximum chunk search radius * @return The matching block positions */ @@ -52,14 +51,36 @@ public interface IWorldScanner { /** * Scans a single chunk for the specified blocks. * - * @param ctx The {@link IPlayerContext} containing player and world info that the - * scan is based upon + * @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon * @param filter The blocks to scan for * @param pos The position of the target chunk * @param max The maximum number of blocks to scan before cutoff - * @param yLevelThreshold If a block is found within this Y level, the current result will be - * returned, if the value is negative, then this condition doesn't apply. + * @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value + * is negative, then this condition doesn't apply. * @return The matching block positions */ List scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold); + + /** + * Scans a single chunk for the specified blocks. + * + * @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon + * @param blocks The blocks to scan for + * @param pos The position of the target chunk + * @param max The maximum number of blocks to scan before cutoff + * @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value + * is negative, then this condition doesn't apply. + * @return The matching block positions + */ + default List scanChunk(IPlayerContext ctx, List blocks, ChunkPos pos, int max, int yLevelThreshold) { + return scanChunk(ctx, new BlockOptionalMetaLookup(blocks), pos, max, yLevelThreshold); + } + + /** + * Repacks 40 chunks around the player. + * + * @param ctx The player context for that player. + * @return The number of chunks queued for repacking. + */ + int repack(IPlayerContext ctx); } diff --git a/src/api/java/baritone/api/event/events/type/Overrideable.java b/src/api/java/baritone/api/event/events/type/Overrideable.java index 1ec29c67..7690ee8f 100644 --- a/src/api/java/baritone/api/event/events/type/Overrideable.java +++ b/src/api/java/baritone/api/event/events/type/Overrideable.java @@ -44,8 +44,8 @@ public class Overrideable { @Override public String toString() { return String.format( - "Overrideable{modified=%s,value=%s}", - Boolean.toString(modified), + "Overrideable{modified=%b,value=%s}", + modified, value.toString() ); } diff --git a/src/api/java/baritone/api/pathing/goals/GoalInverted.java b/src/api/java/baritone/api/pathing/goals/GoalInverted.java index dfe5c770..7f072c4d 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalInverted.java +++ b/src/api/java/baritone/api/pathing/goals/GoalInverted.java @@ -18,7 +18,12 @@ package baritone.api.pathing.goals; /** - * Invert any goal + * Invert any goal. + * + * In the old chat control system, #invert just tried to pick a {@link GoalRunAway} that effectively inverted the + * current goal. This goal just reverses the heuristic to act as a TRUE invert. Inverting a Y level? Baritone tries to + * get away from that Y level. Inverting a GoalBlock? Baritone will try to make distance whether it's in the X, Y or Z + * directions. And of course, you can always invert a GoalXZ. * * @author LoganDark */ diff --git a/src/api/java/baritone/api/process/IBuilderProcess.java b/src/api/java/baritone/api/process/IBuilderProcess.java index 5ca5f804..c48c2a04 100644 --- a/src/api/java/baritone/api/process/IBuilderProcess.java +++ b/src/api/java/baritone/api/process/IBuilderProcess.java @@ -18,11 +18,13 @@ package baritone.api.process; import baritone.api.utils.ISchematic; +import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import java.io.File; +import java.util.List; /** * @author Brady @@ -63,4 +65,11 @@ public interface IBuilderProcess extends IBaritoneProcess { void resume(); void clearArea(BlockPos corner1, BlockPos corner2); + + /** + * @return A list of block states that are estimated to be placeable by this builder process. You can use this in + * schematics, for example, to pick a state that the builder process will be happy with, because any variation will + * cause it to give up. This is updated every tick, but only while the builder process is active. + */ + List getApproxPlaceable(); } diff --git a/src/api/java/baritone/api/schematic/AbstractSchematic.java b/src/api/java/baritone/api/schematic/AbstractSchematic.java index cee9ff9a..27bf6936 100644 --- a/src/api/java/baritone/api/schematic/AbstractSchematic.java +++ b/src/api/java/baritone/api/schematic/AbstractSchematic.java @@ -40,7 +40,7 @@ public abstract class AbstractSchematic implements ISchematic { protected int y; protected int z; - public AbstractSchematic(@Nullable IBaritone baritone, int x, int y, int z) { + public AbstractSchematic(IBaritone baritone, int x, int y, int z) { this.baritone = baritone; this.ctx = baritone == null ? null : baritone.getPlayerContext(); this.x = x; @@ -62,36 +62,4 @@ public abstract class AbstractSchematic implements ISchematic { public int lengthZ() { return z; } - - protected IBlockState[] approxPlaceable() { - EntityPlayerSP player = ctx.player(); - NonNullList inventory = player.inventory.mainInventory; - List placeable = new ArrayList<>(); - placeable.add(Blocks.AIR.getDefaultState()); - - // 27 + 9 - for (int i = 0; i < 36; i++) { - ItemStack stack = inventory.get(i); - Item item = stack.getItem(); - - if (!stack.isEmpty() && stack.getItem() instanceof ItemBlock) { - ItemBlock itemBlock = (ItemBlock) item; - - // - placeable.add(itemBlock.getBlock().getStateForPlacement( - ctx.world(), - ctx.playerFeet(), - EnumFacing.UP, - (float) player.posX, - (float) player.posY, - (float) player.posZ, - itemBlock.getMetadata(stack.getMetadata()), - player - )); - // - } - } - - return placeable.toArray(new IBlockState[0]); - } } diff --git a/src/api/java/baritone/api/schematic/CompositeSchematic.java b/src/api/java/baritone/api/schematic/CompositeSchematic.java index bb4c6cc1..d278fa4c 100644 --- a/src/api/java/baritone/api/schematic/CompositeSchematic.java +++ b/src/api/java/baritone/api/schematic/CompositeSchematic.java @@ -67,13 +67,13 @@ public class CompositeSchematic extends AbstractSchematic { } @Override - public IBlockState desiredState(int x, int y, int z, IBlockState current) { + public IBlockState desiredState(int x, int y, int z, IBlockState current, List approxPlaceable) { CompositeSchematicEntry entry = getSchematic(x, y, z, current); if (entry == null) { throw new IllegalStateException("couldn't find schematic for this position"); } - return entry.schematic.desiredState(x - entry.x, y - entry.y, z - entry.z, current); + return entry.schematic.desiredState(x - entry.x, y - entry.y, z - entry.z, current, approxPlaceable); } } diff --git a/src/api/java/baritone/api/schematic/FillBomSchematic.java b/src/api/java/baritone/api/schematic/FillSchematic.java similarity index 84% rename from src/api/java/baritone/api/schematic/FillBomSchematic.java rename to src/api/java/baritone/api/schematic/FillSchematic.java index 6fc9eff8..8a55376f 100644 --- a/src/api/java/baritone/api/schematic/FillBomSchematic.java +++ b/src/api/java/baritone/api/schematic/FillSchematic.java @@ -22,10 +22,12 @@ import baritone.api.utils.BlockOptionalMeta; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; -public class FillBomSchematic extends AbstractSchematic { +import java.util.List; + +public class FillSchematic extends AbstractSchematic { private final BlockOptionalMeta bom; - public FillBomSchematic(IBaritone baritone, int x, int y, int z, BlockOptionalMeta bom) { + public FillSchematic(IBaritone baritone, int x, int y, int z, BlockOptionalMeta bom) { super(baritone, x, y, z); this.bom = bom; } @@ -35,14 +37,14 @@ public class FillBomSchematic extends AbstractSchematic { } @Override - public IBlockState desiredState(int x, int y, int z, IBlockState current) { + public IBlockState desiredState(int x, int y, int z, IBlockState current, List approxPlaceable) { if (bom.matches(current)) { return current; } else if (current.getBlock() != Blocks.AIR) { return Blocks.AIR.getDefaultState(); } - for (IBlockState placeable : approxPlaceable()) { + for (IBlockState placeable : approxPlaceable) { if (bom.matches(placeable)) { return placeable; } diff --git a/src/api/java/baritone/api/schematic/MaskSchematic.java b/src/api/java/baritone/api/schematic/MaskSchematic.java index 34b1478b..63a4f86f 100644 --- a/src/api/java/baritone/api/schematic/MaskSchematic.java +++ b/src/api/java/baritone/api/schematic/MaskSchematic.java @@ -21,6 +21,8 @@ import baritone.api.IBaritone; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; +import java.util.List; + public abstract class MaskSchematic extends AbstractSchematic { private final ISchematic schematic; @@ -37,7 +39,7 @@ public abstract class MaskSchematic extends AbstractSchematic { } @Override - public IBlockState desiredState(int x, int y, int z, IBlockState current) { - return schematic.desiredState(x, y, z, current); + public IBlockState desiredState(int x, int y, int z, IBlockState current, List approxPlaceable) { + return schematic.desiredState(x, y, z, current, approxPlaceable); } } diff --git a/src/api/java/baritone/api/schematic/ReplaceSchematic.java b/src/api/java/baritone/api/schematic/ReplaceSchematic.java index 4c7ee546..b74c564f 100644 --- a/src/api/java/baritone/api/schematic/ReplaceSchematic.java +++ b/src/api/java/baritone/api/schematic/ReplaceSchematic.java @@ -24,15 +24,17 @@ import net.minecraft.block.state.IBlockState; public class ReplaceSchematic extends MaskSchematic { private final BlockOptionalMetaLookup filter; - private final boolean[][][] cache; + private final Boolean[][][] cache; public ReplaceSchematic(IBaritone baritone, ISchematic schematic, BlockOptionalMetaLookup filter) { super(baritone, schematic); this.filter = filter; - this.cache = new boolean[widthX()][heightY()][lengthZ()]; + this.cache = new Boolean[widthX()][heightY()][lengthZ()]; } protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { - return cache[x][y][z] || (cache[x][y][z] = filter.has(currentState)); + return cache[x][y][z] == null + ? cache[x][y][z] = filter.has(currentState) + : cache[x][y][z]; } } diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index bd17307c..3776baf3 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -56,6 +56,7 @@ import net.minecraft.util.ResourceLocation; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -79,6 +80,42 @@ public final class BlockOptionalMeta { 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 = isNull(meta); + this.meta = noMeta ? 0 : meta; + this.blockstates = getStates(block, meta); + this.stateHashes = getStateHashes(blockstates); + this.stackHashes = getStackHashes(blockstates); + } + + public BlockOptionalMeta(@Nonnull Block block) { + this(block, null); + } + + public BlockOptionalMeta(@Nonnull String selector) { + Matcher matcher = pattern.matcher(selector); + + if (!matcher.find()) { + throw new IllegalArgumentException("invalid block selector"); + } + + MatchResult matchResult = matcher.toMatchResult(); + noMeta = matchResult.group(2) == null; + + ResourceLocation id = new ResourceLocation(matchResult.group(1)); + + 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()); + stateHashes = getStateHashes(blockstates); + stackHashes = getStackHashes(blockstates); + } + static { Map _normalizations = new HashMap<>(); Consumer put = instance -> _normalizations.put(instance.getClass(), instance); @@ -172,7 +209,7 @@ public final class BlockOptionalMeta { _normalizations.put(BlockWall.EAST, false); _normalizations.put(BlockWall.WEST, false); _normalizations.put(BlockWall.SOUTH, false); - normalizations = _normalizations; + normalizations = Collections.unmodifiableMap(_normalizations); } private static , P extends IProperty> P castToIProperty(Object value) { @@ -180,7 +217,6 @@ public final class BlockOptionalMeta { return (P) value; } - @SuppressWarnings("unused") private static , P extends IProperty> C castToIPropertyValue(P iproperty, Object value) { //noinspection unchecked return (C) value; @@ -225,7 +261,7 @@ public final class BlockOptionalMeta { private static Set getStates(@Nonnull Block block, @Nullable Integer meta) { return block.getBlockState().getValidStates().stream() .filter(blockstate -> meta == null || stateMeta(blockstate) == meta) - .collect(Collectors.toCollection(HashSet::new)); + .collect(Collectors.toSet()); } private static ImmutableSet getStateHashes(Set blockstates) { @@ -249,42 +285,6 @@ public final class BlockOptionalMeta { ); } - public BlockOptionalMeta(@Nonnull Block block, @Nullable Integer meta) { - this.block = block; - this.noMeta = isNull(meta); - this.meta = noMeta ? 0 : meta; - this.blockstates = getStates(block, meta); - this.stateHashes = getStateHashes(blockstates); - this.stackHashes = getStackHashes(blockstates); - } - - public BlockOptionalMeta(@Nonnull Block block) { - this(block, null); - } - - public BlockOptionalMeta(@Nonnull String selector) { - Matcher matcher = pattern.matcher(selector); - - if (!matcher.find()) { - throw new IllegalArgumentException("invalid block selector"); - } - - MatchResult matchResult = matcher.toMatchResult(); - noMeta = matchResult.group(2) == null; - - ResourceLocation id = new ResourceLocation(matchResult.group(1)); - - 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()); - stateHashes = getStateHashes(blockstates); - stackHashes = getStackHashes(blockstates); - } - public Block getBlock() { return block; } diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index 44c756d1..963d147c 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -45,6 +45,12 @@ public class BlockOptionalMetaLookup { .toArray(BlockOptionalMeta[]::new); } + public BlockOptionalMetaLookup(String... blocks) { + this.boms = Arrays.stream(blocks) + .map(BlockOptionalMeta::new) + .toArray(BlockOptionalMeta[]::new); + } + public boolean has(Block block) { for (BlockOptionalMeta bom : boms) { if (bom.getBlock() == block) { diff --git a/src/api/java/baritone/api/utils/BlockUtils.java b/src/api/java/baritone/api/utils/BlockUtils.java index 7d148c9f..633e3acb 100644 --- a/src/api/java/baritone/api/utils/BlockUtils.java +++ b/src/api/java/baritone/api/utils/BlockUtils.java @@ -22,7 +22,6 @@ import net.minecraft.util.ResourceLocation; import java.util.HashMap; import java.util.Map; -import java.util.Objects; public class BlockUtils { private static transient Map resourceCache = new HashMap<>(); @@ -39,7 +38,11 @@ public class BlockUtils { public static Block stringToBlockRequired(String name) { Block block = stringToBlockNullable(name); - Objects.requireNonNull(block, String.format("Invalid block name %s", name)); + + if (block == null) { + throw new NullPointerException(String.format("Invalid block name %s", name)); + } + return block; } diff --git a/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java b/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java deleted file mode 100644 index 998a981f..00000000 --- a/src/api/java/baritone/api/utils/ExampleBaritoneControlOld.java +++ /dev/null @@ -1,770 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.api.utils; - -import baritone.api.BaritoneAPI; -import baritone.api.IBaritone; -import baritone.api.Settings; -import baritone.api.behavior.IPathingBehavior; -import baritone.api.cache.IRememberedInventory; -import baritone.api.cache.IWaypoint; -import baritone.api.cache.Waypoint; -import baritone.api.event.events.ChatEvent; -import baritone.api.event.listener.AbstractGameEventListener; -import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.goals.GoalAxis; -import baritone.api.pathing.goals.GoalBlock; -import baritone.api.pathing.goals.GoalGetToBlock; -import baritone.api.pathing.goals.GoalRunAway; -import baritone.api.pathing.goals.GoalStrictDirection; -import baritone.api.pathing.goals.GoalXZ; -import baritone.api.pathing.goals.GoalYLevel; -import baritone.api.process.IBaritoneProcess; -import baritone.api.process.ICustomGoalProcess; -import baritone.api.process.IGetToBlockProcess; -import net.minecraft.block.Block; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ChunkProviderClient; -import net.minecraft.crash.CrashReport; -import net.minecraft.entity.Entity; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ReportedException; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.util.text.TextFormatting; -import net.minecraft.util.text.event.ClickEvent; -import net.minecraft.world.DimensionType; -import net.minecraft.world.chunk.Chunk; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -import static org.apache.commons.lang3.math.NumberUtils.isCreatable; - -public class ExampleBaritoneControlOld implements Helper, AbstractGameEventListener { - private static final String COMMAND_PREFIX = "#"; - - public final IBaritone baritone; - public final IPlayerContext ctx; - - public ExampleBaritoneControlOld(IBaritone baritone) { - this.baritone = baritone; - this.ctx = baritone.getPlayerContext(); - baritone.getGameEventHandler().registerEventListener(this); - } - - @Override - public void onSendChatMessage(ChatEvent event) { - String msg = event.getMessage(); - if (BaritoneAPI.getSettings().prefixControl.value && msg.startsWith(COMMAND_PREFIX)) { - if (!runCommand(msg.substring(COMMAND_PREFIX.length()))) { - logDirect("Invalid command"); - } - event.cancel(); // always cancel if using prefixControl - return; - } - if (!BaritoneAPI.getSettings().chatControl.value && !BaritoneAPI.getSettings().chatControlAnyway.value) { - return; - } - if (runCommand(msg)) { - event.cancel(); - } - } - - public boolean runCommand(String msg0) { // you may think this can be private, but impcat calls it from .b =) - String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL - IPathingBehavior pathingBehavior = baritone.getPathingBehavior(); - ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); - List> toggleable = BaritoneAPI.getSettings().getAllValuesByType(Boolean.class); - for (Settings.Setting setting : toggleable) { - if (msg.equalsIgnoreCase(setting.getName())) { - setting.value ^= true; - logDirect("Toggled " + setting.getName() + " to " + setting.value); - SettingsUtil.save(BaritoneAPI.getSettings()); - return true; - } - } - if (msg.equals("baritone") || msg.equals("modifiedsettings") || msg.startsWith("settings m") || msg.equals("modified")) { - logDirect("All settings that have been modified from their default values:"); - for (Settings.Setting setting : SettingsUtil.modifiedSettings(BaritoneAPI.getSettings())) { - logDirect(setting.toString()); - } - return true; - } - if (msg.startsWith("settings")) { - String rest = msg.substring("settings".length()); - try { - int page = Integer.parseInt(rest.trim()); - int min = page * 10; - int max = Math.min(BaritoneAPI.getSettings().allSettings.size(), (page + 1) * 10); - logDirect("Settings " + min + " to " + (max - 1) + ":"); - for (int i = min; i < max; i++) { - logDirect(BaritoneAPI.getSettings().allSettings.get(i).toString()); - } - } catch (Exception ex) { // NumberFormatException | ArrayIndexOutOfBoundsException and probably some others I'm forgetting lol - ex.printStackTrace(); - logDirect("All settings:"); - for (Settings.Setting setting : BaritoneAPI.getSettings().allSettings) { - logDirect(setting.toString()); - } - logDirect("To get one page of ten settings at a time, do settings "); - } - return true; - } - if (msg.equals("") || msg.equals("help") || msg.equals("?")) { - ITextComponent component = Helper.getPrefix(); - component.getStyle().setColor(TextFormatting.GRAY); - TextComponentString helpLink = new TextComponentString(" Click here for instructions on how to use Baritone (https://github.com/cabaletta/baritone/blob/master/USAGE.md)"); - helpLink.getStyle().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://github.com/cabaletta/baritone/blob/master/USAGE.md")); - component.appendSibling(helpLink); - BaritoneAPI.getSettings().logger.value.accept(component); - return true; - } - if (msg.contains(" ")) { - String settingName = msg.substring(0, msg.indexOf(' ')); - String settingValue = msg.substring(msg.indexOf(' ') + 1); - Settings.Setting setting = BaritoneAPI.getSettings().byLowerName.get(settingName); - if (setting != null) { - if (settingValue.equals("reset")) { - logDirect("Resetting setting " + settingName + " to default value."); - setting.reset(); - } else { - try { - SettingsUtil.parseAndApply(BaritoneAPI.getSettings(), settingName, settingValue); - } catch (Exception ex) { - logDirect("Unable to parse setting"); - return true; - } - } - SettingsUtil.save(BaritoneAPI.getSettings()); - logDirect(setting.toString()); - return true; - } - } - if (BaritoneAPI.getSettings().byLowerName.containsKey(msg)) { - Settings.Setting setting = BaritoneAPI.getSettings().byLowerName.get(msg); - logDirect(setting.toString()); - return true; - } - - if (msg.startsWith("goal")) { - String rest = msg.substring(4).trim(); - Goal goal; - if (rest.equals("clear") || rest.equals("none")) { - goal = null; - } else { - String[] params = rest.split(" "); - if (params[0].equals("")) { - params = new String[] {}; - } - goal = parseGoal(params); - if (goal == null) { - return true; - } - } - customGoalProcess.setGoal(goal); - logDirect("Goal: " + goal); - return true; - } - if (msg.equals("crash")) { - StringBuilder meme = new StringBuilder(); - CrashReport rep = new CrashReport("Manually triggered debug crash", new Throwable()); - mc.addGraphicsAndWorldToCrashReport(rep); - new ReportedException(rep).printStackTrace(); - rep.getSectionsInStringBuilder(meme); - System.out.println(meme); - logDirect(meme.toString()); - logDirect("ok"); - return true; - } - if (msg.equals("path")) { - if (pathingBehavior.getGoal() == null) { - logDirect("No goal."); - } else if (pathingBehavior.getGoal().isInGoal(ctx.playerFeet())) { - logDirect("Already in goal"); - } else if (pathingBehavior.isPathing()) { - logDirect("Currently executing a path. Please cancel it first."); - } else { - customGoalProcess.setGoalAndPath(pathingBehavior.getGoal()); - } - return true; - } - /*if (msg.equals("fullpath")) { - if (pathingBehavior.getGoal() == null) { - logDirect("No goal."); - } else { - logDirect("Started segmented calculator"); - SegmentedCalculator.calculateSegmentsThreaded(pathingBehavior.pathStart(), pathingBehavior.getGoal(), new CalculationContext(baritone, true), ipath -> { - logDirect("Found a path"); - logDirect("Ends at " + ipath.getDest()); - logDirect("Length " + ipath.length()); - logDirect("Estimated time " + ipath.ticksRemainingFrom(0)); - pathingBehavior.secretCursedFunctionDoNotCall(ipath); // it's okay when *I* do it - }, () -> { - logDirect("Path calculation failed, no path"); - }); - } - return true; - }*/ - if (msg.equals("proc")) { - Optional proc = baritone.getPathingControlManager().mostRecentInControl(); - if (!proc.isPresent()) { - logDirect("No process is in control"); - return true; - } - IBaritoneProcess p = proc.get(); - logDirect("Class: " + p.getClass()); - logDirect("Priority: " + p.priority()); - logDirect("Temporary: " + p.isTemporary()); - logDirect("Display name: " + p.displayName()); - logDirect("Command: " + baritone.getPathingControlManager().mostRecentCommand()); - return true; - } - if (msg.equals("version")) { - String version = ExampleBaritoneControlOld.class.getPackage().getImplementationVersion(); - if (version == null) { - logDirect("No version detected. Either dev environment or broken install."); - } else { - logDirect("You are using Baritone v" + version); - } - return true; - } - if (msg.equals("repack") || msg.equals("rescan")) { - logDirect("Queued " + repack() + " chunks for repacking"); - return true; - } - if (msg.startsWith("build")) { - String file; - BlockPos origin; - try { - String[] coords = msg.substring("build".length()).trim().split(" "); - file = coords[0] + ".schematic"; - origin = new BlockPos(parseOrDefault(coords[1], ctx.playerFeet().x, 1), parseOrDefault(coords[2], ctx.playerFeet().y, 1), parseOrDefault(coords[3], ctx.playerFeet().z, 1)); - } catch (Exception ex) { - file = msg.substring(5).trim() + ".schematic"; - origin = ctx.playerFeet(); - } - logDirect("Loading '" + file + "' to build from origin " + origin); - boolean success = baritone.getBuilderProcess().build(file, origin); - logDirect(success ? "Loaded" : "Unable to load"); - return true; - } - if (msg.startsWith("schematica")) { - baritone.getBuilderProcess().buildOpenSchematic(); - return true; - } - if (msg.equals("come")) { - customGoalProcess.setGoalAndPath(new GoalBlock(new BlockPos(Helper.mc.getRenderViewEntity()))); - logDirect("Coming"); - return true; - } - if (msg.equals("axis") || msg.equals("highway")) { - customGoalProcess.setGoalAndPath(new GoalAxis()); - return true; - } - if (msg.equals("cancel") || msg.equals("stop")) { - pathingBehavior.cancelEverything(); - logDirect("ok canceled"); - return true; - } - if (msg.equals("forcecancel")) { - pathingBehavior.cancelEverything(); - pathingBehavior.forceCancel(); - logDirect("ok force canceled"); - return true; - } - if (msg.equals("gc")) { - System.gc(); - logDirect("Called System.gc();"); - return true; - } - if (msg.equals("invert")) { - Goal goal = pathingBehavior.getGoal(); - BlockPos runAwayFrom; - if (goal instanceof GoalXZ) { - runAwayFrom = new BlockPos(((GoalXZ) goal).getX(), 0, ((GoalXZ) goal).getZ()); - } else if (goal instanceof GoalBlock) { - runAwayFrom = ((GoalBlock) goal).getGoalPos(); - } else { - logDirect("Goal must be GoalXZ or GoalBlock to invert"); - logDirect("Inverting goal of player feet"); - runAwayFrom = ctx.playerFeet(); - } - customGoalProcess.setGoalAndPath(new GoalRunAway(1, runAwayFrom) { - @Override - public boolean isInGoal(int x, int y, int z) { - return false; - } - }); - return true; - } - if (msg.startsWith("cleararea")) { - String suffix = msg.substring("cleararea".length()); - BlockPos corner1; - BlockPos corner2; - if (suffix.isEmpty()) { - // clear the area from the current goal to here - Goal goal = baritone.getPathingBehavior().getGoal(); - if (!(goal instanceof GoalBlock)) { - logDirect("Need to specify goal of opposite corner"); - return true; - } - corner1 = ((GoalBlock) goal).getGoalPos(); - corner2 = ctx.playerFeet(); - } else { - try { - String[] spl = suffix.split(" "); - corner1 = ctx.playerFeet(); - corner2 = new BlockPos(Integer.parseInt(spl[0]), Integer.parseInt(spl[1]), Integer.parseInt(spl[2])); - } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) { - logDirect("unable to parse"); - return true; - } - } - baritone.getBuilderProcess().clearArea(corner1, corner2); - return true; - } - if (msg.equals("resume")) { - baritone.getBuilderProcess().resume(); - logDirect("resumed"); - return true; - } - if (msg.equals("pause")) { - baritone.getBuilderProcess().pause(); - logDirect("paused"); - return true; - } - if (msg.equals("reset")) { - for (Settings.Setting setting : BaritoneAPI.getSettings().allSettings) { - setting.reset(); - } - SettingsUtil.save(BaritoneAPI.getSettings()); - logDirect("Baritone settings reset"); - return true; - } - if (msg.equals("tunnel")) { - customGoalProcess.setGoalAndPath(new GoalStrictDirection(ctx.playerFeet(), ctx.player().getHorizontalFacing())); - logDirect("tunneling"); - return true; - } - if (msg.equals("render")) { - BetterBlockPos pf = ctx.playerFeet(); - int dist = (Minecraft.getMinecraft().gameSettings.renderDistanceChunks + 1) * 16; - Minecraft.getMinecraft().renderGlobal.markBlockRangeForRenderUpdate(pf.x - dist, pf.y - 256, pf.z - dist, pf.x + dist, pf.y + 256, pf.z + dist); - logDirect("okay"); - return true; - } - if (msg.equals("farm")) { - baritone.getFarmProcess().farm(); - logDirect("farming"); - return true; - } - if (msg.equals("chests")) { - for (Map.Entry entry : baritone.getWorldProvider().getCurrentWorld().getContainerMemory().getRememberedInventories().entrySet()) { - logDirect(BetterBlockPos.from(entry.getKey()) + ""); - log(entry.getValue().getContents()); - } - return true; - } - if (msg.startsWith("followentities")) { - baritone.getFollowProcess().follow(Entity.class::isInstance); - logDirect("Following any entities"); - return true; - } - if (msg.startsWith("followplayers")) { - baritone.getFollowProcess().follow(EntityPlayer.class::isInstance); // O P P A - logDirect("Following any players"); - return true; - } - if (msg.startsWith("followentity")) { - String name = msg.substring(12).trim(); - Optional toFollow = Optional.empty(); - for (Entity entity : ctx.world().loadedEntityList) { - String entityName = entity.getName().trim().toLowerCase(); - if ((entityName.contains(name) || name.contains(entityName)) && !(entity instanceof EntityItem || entity instanceof EntityPlayer)) { // We dont want it following players while `#follow` exists. - toFollow = Optional.of(entity); - } - } - if (!toFollow.isPresent()) { - logDirect("Entity not found"); - return true; - } - Entity effectivelyFinal = toFollow.get(); - baritone.getFollowProcess().follow(effectivelyFinal::equals); - logDirect("Following entity " + toFollow.get()); - return true; - } - if (msg.startsWith("follow")) { - String name = msg.substring(6).trim(); - Optional toFollow = Optional.empty(); - if (name.length() == 0) { - toFollow = ctx.getSelectedEntity(); - } else { - for (EntityPlayer pl : ctx.world().playerEntities) { - String theirName = pl.getName().trim().toLowerCase(); - if (!theirName.equals(ctx.player().getName().trim().toLowerCase()) && (theirName.contains(name) || name.contains(theirName))) { // don't follow ourselves lol - toFollow = Optional.of(pl); - } - } - } - if (!toFollow.isPresent()) { - logDirect("Not found"); - return true; - } - Entity effectivelyFinal = toFollow.get(); - baritone.getFollowProcess().follow(effectivelyFinal::equals); - logDirect("Following " + toFollow.get()); - return true; - } - if (msg.startsWith("explorefilter")) { - // explorefilter blah.json - // means that entries in blah.json are already explored - // explorefilter blah.json invert - // means that entries in blah.json are NOT already explored - String path = msg.substring("explorefilter".length()).trim(); - String[] parts = path.split(" "); - Path path1 = Minecraft.getMinecraft().gameDir.toPath().resolve(parts[0]); - boolean invert = parts.length > 1; - try { - baritone.getExploreProcess().applyJsonFilter(path1, invert); - logDirect("Loaded filter. Inverted: " + invert); - if (invert) { - logDirect("Chunks on this list will be treated as possibly unexplored, all others will be treated as certainly explored"); - } else { - logDirect("Chunks on this list will be treated as certainly explored, all others will be treated as possibly unexplored"); - } - } catch (Exception e) { - e.printStackTrace(); - logDirect("Unable to load " + path1); - } - return true; - } - if (msg.equals("reloadall")) { - baritone.getWorldProvider().getCurrentWorld().getCachedWorld().reloadAllFromDisk(); - logDirect("ok"); - return true; - } - if (msg.equals("saveall")) { - baritone.getWorldProvider().getCurrentWorld().getCachedWorld().save(); - logDirect("ok"); - return true; - } - if (msg.startsWith("explore")) { - String rest = msg.substring("explore".length()).trim(); - int centerX; - int centerZ; - try { - centerX = Integer.parseInt(rest.split(" ")[0]); - centerZ = Integer.parseInt(rest.split(" ")[1]); - } catch (Exception ex) { - centerX = ctx.playerFeet().x; - centerZ = ctx.playerFeet().z; - } - baritone.getExploreProcess().explore(centerX, centerZ); - logDirect("Exploring from " + centerX + "," + centerZ); - return true; - } - if (msg.equals("blacklist")) { - IGetToBlockProcess proc = baritone.getGetToBlockProcess(); - if (!proc.isActive()) { - logDirect("GetToBlockProcess is not currently active"); - return true; - } - if (proc.blacklistClosest()) { - logDirect("Blacklisted closest instances"); - } else { - logDirect("No known locations, unable to blacklist"); - } - return true; - } - if (msg.startsWith("find")) { - repack(); - String blockType = msg.substring(4).trim(); - ArrayList locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4); - logDirect("Have " + locs.size() + " locations"); - for (BlockPos pos : locs) { - Block actually = ctx.world().getBlockState(pos).getBlock(); - if (!BlockUtils.blockToString(actually).equalsIgnoreCase(blockType)) { - logDebug("Was looking for " + blockType + " but actually found " + actually + " " + BlockUtils.blockToString(actually)); - } - } - return true; - } - if (msg.startsWith("mine")) { - repack(); - String[] blockTypes = msg.substring(4).trim().split(" "); - try { - int quantity = Integer.parseInt(blockTypes[1]); - Block block = BlockUtils.stringToBlockRequired(blockTypes[0]); - baritone.getMineProcess().mine(quantity, block); - logDirect("Will mine " + quantity + " " + blockTypes[0]); - return true; - } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) { - } - for (String s : blockTypes) { - if (BlockUtils.stringToBlockNullable(s) == null) { - logDirect(s + " isn't a valid block name"); - return true; - } - - } - baritone.getMineProcess().mineByName(0, blockTypes); - logDirect("Started mining blocks of type " + Arrays.toString(blockTypes)); - return true; - } - if (msg.equals("click")) { - baritone.openClick(); - logDirect("aight dude"); - return true; - } - if (msg.startsWith("thisway") || msg.startsWith("forward")) { - try { - Goal goal = GoalXZ.fromDirection(ctx.playerFeetAsVec(), ctx.player().rotationYaw, Double.parseDouble(msg.substring(7).trim())); - customGoalProcess.setGoal(goal); - logDirect("Goal: " + goal); - } catch (NumberFormatException ex) { - logDirect("Error unable to parse '" + msg.substring(7).trim() + "' to a double."); - } - return true; - } - if (msg.startsWith("list") || msg.startsWith("get ") || msg.startsWith("show")) { - String waypointType = msg.substring(4).trim(); - if (waypointType.endsWith("s")) { - // for example, "show deaths" - waypointType = waypointType.substring(0, waypointType.length() - 1); - } - IWaypoint.Tag tag = IWaypoint.Tag.fromString(waypointType); - if (tag == null) { - logDirect("Not a valid tag. Tags are: " + Arrays.asList(IWaypoint.Tag.values()).toString().toLowerCase()); - return true; - } - Set waypoints = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getByTag(tag); - // might as well show them from oldest to newest - List sorted = new ArrayList<>(waypoints); - sorted.sort(Comparator.comparingLong(IWaypoint::getCreationTimestamp)); - logDirect("Waypoints under tag " + tag + ":"); - for (IWaypoint waypoint : sorted) { - logDirect(waypoint.toString()); - } - return true; - } - if (msg.startsWith("save")) { - String name = msg.substring(4).trim(); - BetterBlockPos pos = ctx.playerFeet(); - if (name.contains(" ")) { - logDirect("Name contains a space, assuming it's in the format 'save waypointName X Y Z'"); - String[] parts = name.split(" "); - if (parts.length != 4) { - logDirect("Unable to parse, expected four things"); - return true; - } - try { - pos = new BetterBlockPos(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3])); - } catch (NumberFormatException ex) { - logDirect("Unable to parse coordinate integers"); - return true; - } - name = parts[0]; - } - for (IWaypoint.Tag tag : IWaypoint.Tag.values()) { - if (tag.name().equalsIgnoreCase(name)) { - logDirect("Unable to use tags as name. Tags are: " + Arrays.asList(IWaypoint.Tag.values()).toString().toLowerCase()); - return true; - } - } - baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, IWaypoint.Tag.USER, pos)); - logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto " + name + "' to set goal, say 'list user' to list custom waypoints."); - return true; - } - if (msg.startsWith("delete")) { - String name = msg.substring(6).trim(); - IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getTag() == IWaypoint.Tag.USER && w.getName().equalsIgnoreCase(name)).findFirst().orElse(null); - if (waypoint == null) { - logDirect("No user defined position under the name '" + name + "' found."); - return true; - } - baritone.getWorldProvider().getCurrentWorld().getWaypoints().removeWaypoint(waypoint); - logDirect("Deleted user defined position under name '" + name + "'."); - return true; - } - if (msg.startsWith("goto")) { - repack(); - String waypointType = msg.substring(4).trim(); - if (waypointType.endsWith("s") && IWaypoint.Tag.fromString(waypointType.substring(0, waypointType.length() - 1)) != null) { - // for example, "show deaths" - waypointType = waypointType.substring(0, waypointType.length() - 1); - } - IWaypoint.Tag tag = IWaypoint.Tag.fromString(waypointType); - IWaypoint waypoint; - if (tag == null) { - String mining = waypointType; - Block block = BlockUtils.stringToBlockNullable(mining); - //logDirect("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase()); - if (block == null) { - waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null); - if (waypoint == null) { - Goal goal = parseGoal(waypointType.split(" ")); - if (goal != null) { - logDirect("Going to " + goal); - customGoalProcess.setGoalAndPath(goal); - } - return true; - } - } else { - baritone.getGetToBlockProcess().getToBlock(block); - return true; - } - } else { - waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(tag); - if (waypoint == null) { - logDirect("None saved for tag " + tag); - return true; - } - } - Goal goal = waypoint.getTag() == IWaypoint.Tag.BED ? new GoalGetToBlock(waypoint.getLocation()) : new GoalBlock(waypoint.getLocation()); - customGoalProcess.setGoalAndPath(goal); - return true; - } - if (msg.equals("spawn") || msg.equals("bed")) { - IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(IWaypoint.Tag.BED); - if (waypoint == null) { - BlockPos spawnPoint = ctx.player().getBedLocation(); - // for some reason the default spawnpoint is underground sometimes - Goal goal = new GoalXZ(spawnPoint.getX(), spawnPoint.getZ()); - logDirect("spawn not saved, defaulting to world spawn. set goal to " + goal); - customGoalProcess.setGoalAndPath(goal); - } else { - Goal goal = new GoalGetToBlock(waypoint.getLocation()); - customGoalProcess.setGoalAndPath(goal); - logDirect("Set goal to most recent bed " + goal); - } - return true; - } - if (msg.equals("sethome")) { - baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", IWaypoint.Tag.HOME, ctx.playerFeet())); - logDirect("Saved. Say home to set goal."); - return true; - } - if (msg.equals("home")) { - IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(IWaypoint.Tag.HOME); - if (waypoint == null) { - logDirect("home not saved"); - } else { - Goal goal = new GoalBlock(waypoint.getLocation()); - customGoalProcess.setGoalAndPath(goal); - logDirect("Going to saved home " + goal); - } - return true; - } - if (msg.equals("damn")) { - logDirect("daniel"); - } - return false; - } - - private int repack() { - ChunkProviderClient cli = (ChunkProviderClient) ctx.world().getChunkProvider(); - int playerChunkX = ctx.playerFeet().getX() >> 4; - int playerChunkZ = ctx.playerFeet().getZ() >> 4; - int count = 0; - for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) { - for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) { - Chunk chunk = cli.getLoadedChunk(x, z); - if (chunk != null && !chunk.isEmpty()) { - count++; - baritone.getWorldProvider().getCurrentWorld().getCachedWorld().queueForPacking(chunk); - } - } - } - return count; - } - - private int parseOrDefault(String str, int i, double dimensionFactor) { - return str.equals("~") ? i : str.startsWith("~") ? (int) (Integer.parseInt(str.substring(1)) * dimensionFactor) + i : (int) (Integer.parseInt(str) * dimensionFactor); - } - - private void log(List stacks) { - for (ItemStack stack : stacks) { - if (!stack.isEmpty()) { - logDirect(stack.getCount() + "x " + stack.getDisplayName() + "@" + stack.getItemDamage()); - } - } - } - - private Goal parseGoal(String[] params) { - Goal goal; - try { - BetterBlockPos playerFeet = ctx.playerFeet(); - - int length = params.length - 1; // length has to be smaller when a dimension parameter is added - if (params.length < 1 || (isCreatable(params[params.length - 1]) || params[params.length - 1].startsWith("~"))) { - length = params.length; - } - switch (length) { - case 0: - goal = new GoalBlock(playerFeet); - break; - case 1: - goal = new GoalYLevel(parseOrDefault(params[0], playerFeet.y, 1)); - break; - case 2: - goal = new GoalXZ(parseOrDefault(params[0], playerFeet.x, calculateDimensionFactor(params[params.length - 1])), parseOrDefault(params[1], playerFeet.z, calculateDimensionFactor(params[params.length - 1]))); - break; - case 3: - goal = new GoalBlock(new BlockPos(parseOrDefault(params[0], playerFeet.x, calculateDimensionFactor(params[params.length - 1])), parseOrDefault(params[1], playerFeet.y, 1), parseOrDefault(params[2], playerFeet.z, calculateDimensionFactor(params[params.length - 1])))); - break; - default: - logDirect("unable to understand lol"); - return null; - } - } catch (NumberFormatException ex) { - logDirect("unable to parse integer " + ex); - return null; - } - return goal; - } - - - private double calculateDimensionFactor(String to) { - return Math.pow(8, ctx.world().provider.getDimensionType().getId() - getDimensionByName(to.toLowerCase()).getId()); - } - - private DimensionType getDimensionByName(String name) { - if ("the_end".contains(name)) { - return DimensionType.THE_END; - } - if ("the_overworld".contains(name) || "surface".contains(name)) { - return DimensionType.OVERWORLD; - } - if ("the_nether".contains(name) || "hell".contains(name)) { - return DimensionType.NETHER; - } - return ctx.world().provider.getDimensionType(); - } - -} diff --git a/src/api/java/baritone/api/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java index 9bb573be..87884cd2 100755 --- a/src/api/java/baritone/api/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -39,14 +39,15 @@ public interface Helper { Helper HELPER = new Helper() {}; static ITextComponent getPrefix() { - return new TextComponentString("") {{ - getStyle().setColor(TextFormatting.DARK_PURPLE); - appendSibling(new TextComponentString("[")); - appendSibling(new TextComponentString(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone") {{ - getStyle().setColor(TextFormatting.LIGHT_PURPLE); - }}); - appendSibling(new TextComponentString("]")); - }}; + ITextComponent baritone = new TextComponentString(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone"); + baritone.getStyle().setColor(TextFormatting.LIGHT_PURPLE); + ITextComponent prefix = new TextComponentString(""); + prefix.getStyle().setColor(TextFormatting.DARK_PURPLE); + prefix.appendText("["); + prefix.appendSibling(baritone); + prefix.appendText("]"); + + return prefix; } Minecraft mc = Minecraft.getMinecraft(); @@ -71,31 +72,31 @@ public interface Helper { * @param components The components to send */ default void logDirect(ITextComponent... components) { - ITextComponent component = new TextComponentString("") {{ - appendSibling(getPrefix()); - appendSibling(new TextComponentString(" ")); - asList(components).forEach(this::appendSibling); - }}; - + ITextComponent component = new TextComponentString(""); + component.appendSibling(getPrefix()); + component.appendSibling(new TextComponentString(" ")); + asList(components).forEach(component::appendSibling); Minecraft.getMinecraft().addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component)); } /** - * Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command) + * Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a + * direct response to a chat command) * * @param message The message to display in chat * @param color The color to print that message in */ default void logDirect(String message, TextFormatting color) { - Arrays.stream(message.split("\\n")).forEach(line -> - logDirect(new TextComponentString(line.replace("\t", " ")) {{ - getStyle().setColor(color); - }}) - ); + Arrays.stream(message.split("\\n")).forEach(line -> { + ITextComponent component = new TextComponentString(line.replace("\t", " ")); + component.getStyle().setColor(color); + logDirect(component); + }); } /** - * Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command) + * Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a + * direct response to a chat command) * * @param message The message to display in chat */ diff --git a/src/api/java/baritone/api/utils/IPlayerContext.java b/src/api/java/baritone/api/utils/IPlayerContext.java index 457af87b..b461c389 100644 --- a/src/api/java/baritone/api/utils/IPlayerContext.java +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -48,6 +48,14 @@ public interface IPlayerContext { // TODO find a better way to deal with soul sand!!!!! BetterBlockPos feet = new BetterBlockPos(player().posX, player().posY + 0.1251, player().posZ); + // sometimes when calling this from another thread or while world is null, it'll throw a NullPointerException + // that causes the game to immediately crash + // + // so of course crashing on 2b is horribly bad due to queue times and logout spot + // catch the NPE and ignore it if it does happen + // + // this does not impact performance at all since we're not null checking constantly + // if there is an exception, the only overhead is Java generating the exception object... so we can ignore it try { if (world().getBlockState(feet).getBlock() instanceof BlockSlab) { return feet.up(); diff --git a/src/api/java/baritone/api/utils/ISchematic.java b/src/api/java/baritone/api/utils/ISchematic.java index 0b2f92d9..b2dfc308 100644 --- a/src/api/java/baritone/api/utils/ISchematic.java +++ b/src/api/java/baritone/api/utils/ISchematic.java @@ -20,9 +20,11 @@ package baritone.api.utils; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; +import java.util.List; + /** - * Basic representation of a schematic. Provides the dimensions and - * the desired statefor a given position relative to the origin. + * Basic representation of a schematic. Provides the dimensions and the desired statefor a given position relative to + * the origin. * * @author leijurv */ @@ -62,13 +64,14 @@ public interface ISchematic { /** * Returns the desired block state at a given (X, Y, Z) position relative to the origin (0, 0, 0). * - * @param x The x position of the block, relative to the origin - * @param y The y position of the block, relative to the origin - * @param z The z position of the block, relative to the origin - * @param current The current state of that block in the world, or null + * @param x The x position of the block, relative to the origin + * @param y The y position of the block, relative to the origin + * @param z The z position of the block, relative to the origin + * @param current The current state of that block in the world, or null + * @param approxPlaceable The list of blockstates estimated to be placeable * @return The desired block state at the specified position */ - IBlockState desiredState(int x, int y, int z, IBlockState current); + IBlockState desiredState(int x, int y, int z, IBlockState current, List approxPlaceable); /** * @return The width (X axis length) of this schematic diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index e726a9cc..5c8ab83f 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -121,6 +121,15 @@ public class SettingsUtil { return modified; } + /** + * Gets the type of a setting and returns it as a string, with package names stripped. + * + * For example, if the setting type is {@code java.util.List}, this function returns + * {@code List}. + * + * @param setting The setting + * @return The type + */ public static String settingTypeToString(Settings.Setting setting) { return setting.getType().getTypeName() .replaceAll("(?:\\w+\\.)+(\\w+)", "$1"); diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index a06887b2..df7bab65 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -20,6 +20,7 @@ package baritone.api.utils.command; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; +import baritone.api.accessor.IGuiScreen; import baritone.api.event.events.ChatEvent; import baritone.api.event.events.TabCompleteEvent; import baritone.api.event.listener.AbstractGameEventListener; @@ -33,6 +34,7 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.manager.CommandManager; import com.mojang.realmsclient.util.Pair; +import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; @@ -47,7 +49,6 @@ import java.util.stream.Stream; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; -import static java.util.stream.Stream.of; public class BaritoneChatControl implements Helper, AbstractGameEventListener { public final IBaritone baritone; @@ -67,10 +68,6 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { String prefix = settings.prefix.value; boolean forceRun = msg.startsWith(FORCE_COMMAND_PREFIX); - if (!forceRun && !settings.chatControl.value && !settings.chatControlAnyway.value && !settings.prefixControl.value) { - return; - } - if ((settings.prefixControl.value && msg.startsWith(prefix)) || forceRun) { event.cancel(); @@ -79,11 +76,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (!runCommand(commandStr) && !commandStr.trim().isEmpty()) { new CommandNotFoundException(CommandExecution.expand(commandStr).first()).handle(null, null); } - - return; - } - - if ((settings.chatControl.value || settings.chatControlAnyway.value) && runCommand(msg)) { + } else if ((settings.chatControl.value || settings.chatControlAnyway.value) && runCommand(msg)) { event.cancel(); } } @@ -92,18 +85,20 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (settings.echoCommands.value) { String msg = command + rest; String toDisplay = settings.censorRanCommands.value ? command + " ..." : msg; - logDirect(new TextComponentString(String.format("> %s", toDisplay)) {{ - getStyle() - .setColor(TextFormatting.WHITE) - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("Click to rerun command") - )) - .setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - FORCE_COMMAND_PREFIX + msg - )); - }}); + + ITextComponent component = new TextComponentString(String.format("> %s", toDisplay)); + component.getStyle() + .setColor(TextFormatting.WHITE) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to rerun command") + )) + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + FORCE_COMMAND_PREFIX + msg + )); + + logDirect(component); } } @@ -113,7 +108,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { return false; } else if (msg.trim().equalsIgnoreCase("orderpizza")) { try { - ((Lol) mc.currentScreen).openLink(new URI("https://www.dominos.com/en/pages/order/")); + ((IGuiScreen) mc.currentScreen).openLink(new URI("https://www.dominos.com/en/pages/order/")); } catch (NullPointerException | URISyntaxException ignored) {} return false; @@ -129,22 +124,18 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { ArgConsumer argc = new ArgConsumer(pair.second()); if (!argc.has()) { - for (Settings.Setting setting : settings.allSettings) { - if (setting.getName().equals("logger")) { - continue; + Settings.Setting setting = settings.byLowerName.get(command.toLowerCase(Locale.US)); + + if (setting != null) { + logRanCommand(command, rest); + + if (setting.getValueClass() == Boolean.class) { + CommandManager.execute(String.format("set toggle %s", setting.getName())); + } else { + CommandManager.execute(String.format("set %s", setting.getName())); } - if (setting.getName().equalsIgnoreCase(command)) { - logRanCommand(command, rest); - - if (setting.getValueClass() == Boolean.class) { - CommandManager.execute(String.format("set toggle %s", setting.getName())); - } else { - CommandManager.execute(String.format("set %s", setting.getName())); - } - - return true; - } + return true; } } else if (argc.hasExactlyOne()) { for (Settings.Setting setting : settings.allSettings) { @@ -217,14 +208,14 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { TabCompleteHelper helper = new TabCompleteHelper(); if ((Boolean) setting.value) { - helper.append(of("true", "false")); + helper.append(Stream.of("true", "false")); } else { - helper.append(of("false", "true")); + helper.append(Stream.of("false", "true")); } return helper.filterPrefix(argc.getString()).stream(); } else { - return of(SettingsUtil.settingValueToString(setting)); + return Stream.of(SettingsUtil.settingValueToString(setting)); } } } diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index 7fa3b2a8..410a34a9 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -27,8 +27,6 @@ import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.client.Minecraft; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; @@ -46,27 +44,20 @@ public abstract class Command implements Helper, AbstractGameEventListener { */ public final List names; - /** - * A single-line string containing a short description of this command's purpose. - */ - public final String shortDesc; - /** * Creates a new Baritone control command. * - * @param names The names of this command. This is what you put after the command prefix. - * @param shortDesc A single-line string containing a short description of this command's purpose. + * @param names The names of this command. This is what you put after the command prefix. */ - protected Command(List names, String shortDesc) { + protected Command(List names) { this.names = names.stream() .map(s -> s.toLowerCase(Locale.US)) - .collect(Collectors.toCollection(ArrayList::new)); - this.shortDesc = shortDesc; + .collect(Collectors.toList()); baritone.getGameEventHandler().registerEventListener(this); } - protected Command(String name, String shortDesc) { - this(Collections.singletonList(name), shortDesc); + protected Command(String name) { + this(Collections.singletonList(name)); } /** @@ -88,7 +79,7 @@ public abstract class Command implements Helper, AbstractGameEventListener { try { return tabCompleted(execution.label, execution.args, execution.settings); } catch (Throwable t) { - return Arrays.stream(new String[0]); + return Stream.empty(); } } @@ -103,6 +94,11 @@ public abstract class Command implements Helper, AbstractGameEventListener { */ protected abstract Stream tabCompleted(String label, ArgConsumer args, Settings settings); + /** + * @return A single-line string containing a short description of this command's purpose. + */ + public abstract String getShortDesc(); + /** * @return A list of lines that will be printed by the help command when the user wishes to view them. */ diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index 6b5d4761..619fa67a 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -22,8 +22,6 @@ import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.exception.CommandNoParserForTypeException; import baritone.api.utils.command.registry.Registry; -import java.util.Iterator; - import static java.util.Objects.isNull; public class ArgParserManager { @@ -38,16 +36,13 @@ public class ArgParserManager { * @return A parser that can parse arguments into this class, if found. */ public static ArgParser.Stateless getParserStateless(Class klass) { - for (Iterator it = REGISTRY.descendingIterator(); it.hasNext(); ) { - ArgParser parser = it.next(); - - if (parser instanceof ArgParser.Stateless && parser.getKlass().isAssignableFrom(klass)) { - //noinspection unchecked - return (ArgParser.Stateless) parser; - } - } - - return null; + //noinspection unchecked + return REGISTRY.descendingStream() + .filter(ArgParser.Stateless.class::isInstance) + .map(ArgParser.Stateless.class::cast) + .filter(parser -> parser.getKlass().isAssignableFrom(klass)) + .findFirst() + .orElse(null); } /** @@ -55,21 +50,27 @@ public class ArgParserManager { * @return A parser that can parse arguments into this class, if found. */ public static ArgParser.Stated getParserStated(Class klass, Class stateKlass) { - for (Iterator it = REGISTRY.descendingIterator(); it.hasNext(); ) { - ArgParser parser = it.next(); - - //noinspection unchecked - if (parser instanceof ArgParser.Stated - && parser.getKlass().isAssignableFrom(klass) - && ((ArgParser.Stated) parser).getStateKlass().isAssignableFrom(stateKlass)) { - //noinspection unchecked - return (ArgParser.Stated) parser; - } - } - - return null; + //noinspection unchecked + return REGISTRY.descendingStream() + .filter(ArgParser.Stated.class::isInstance) + .map(ArgParser.Stated.class::cast) + .filter(parser -> parser.getKlass().isAssignableFrom(klass)) + .filter(parser -> parser.getStateKlass().isAssignableFrom(stateKlass)) + .map(ArgParser.Stated.class::cast) + .findFirst() + .orElse(null); } + /** + * Attempt to parse the specified argument with a stateless {@link ArgParser} that outputs the specified class. + * + * @param klass The class to parse the argument into. + * @param arg The argument to parse. + * @return An instance of the specified class. + * @throws CommandNoParserForTypeException If no parser exists for that type + * @throws CommandInvalidTypeException If the parsing failed + * @see ArgParser.Stateless + */ public static T parseStateless(Class klass, CommandArgument arg) { ArgParser.Stateless parser = getParserStateless(klass); @@ -84,6 +85,17 @@ public class ArgParserManager { } } + /** + * Attempt to parse the specified argument with a stated {@link ArgParser} that outputs the specified class. + * + * @param klass The class to parse the argument into. + * @param arg The argument to parse. + * @param state The state to pass to the {@link ArgParser.Stated}. + * @return An instance of the specified class. + * @throws CommandNoParserForTypeException If no parser exists for that type + * @throws CommandInvalidTypeException If the parsing failed + * @see ArgParser.Stated + */ public static T parseStated(Class klass, Class stateKlass, CommandArgument arg, S state) { ArgParser.Stated parser = getParserStated(klass, stateKlass); diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index ae80734d..fe964bce 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -19,7 +19,6 @@ package baritone.api.utils.command.argparser; import baritone.api.utils.command.argument.CommandArgument; -import java.util.Collections; import java.util.List; import java.util.Locale; @@ -114,11 +113,11 @@ public class DefaultArgParsers { } } - public static final List> all = Collections.unmodifiableList(asList( + public static final List> all = asList( IntArgumentParser.INSTANCE, LongArgumentParser.INSTANCE, FloatArgumentParser.INSTANCE, DoubleArgumentParser.INSTANCE, BooleanArgumentParser.INSTANCE - )); + ); } diff --git a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java index 1d8890ed..c8ac7630 100644 --- a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java +++ b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java @@ -25,6 +25,11 @@ public interface IArgParser { */ Class getKlass(); + /** + * A stateless argument parser is just that. It takes a {@link CommandArgument} and outputs its type. + * + * @see ArgParserManager#REGISTRY + */ interface Stateless extends IArgParser { /** * @param arg The argument to parse. @@ -35,6 +40,12 @@ public interface IArgParser { T parseArg(CommandArgument arg) throws RuntimeException; } + /** + * A stated argument parser is similar to a stateless one. It also takes a {@link CommandArgument}, but it also + * takes a second argument that can be any type, referred to as the state. + * + * @see ArgParserManager#REGISTRY + */ interface Stated extends IArgParser { Class getStateKlass(); diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index 8309e696..5d297528 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -17,16 +17,27 @@ package baritone.api.utils.command.argument; +import baritone.api.utils.command.argparser.ArgParser; import baritone.api.utils.command.argparser.ArgParserManager; +import baritone.api.utils.command.exception.CommandInvalidArgumentException; import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.exception.CommandNoParserForTypeException; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.util.EnumFacing; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; -@SuppressWarnings("UnusedReturnValue") +/** + * A {@link CommandArgument} is an immutable object representing one command argument. It contains data on the index of + * that argument, its value, and the rest of the string that argument was found in + *

+ * You're recommended to use {@link ArgConsumer}s to handle these. Check out {@link ArgConsumer#from(String)} + */ public class CommandArgument { public final int index; public final String value; @@ -39,18 +50,54 @@ public class CommandArgument { this.rawRest = rawRest; } + /** + * Gets an enum value from the enum class with the same name as this argument's value + *

+ * For example if you getEnum as an {@link EnumFacing}, and this argument's value is "up", it will return {@link + * EnumFacing#UP} + * + * @param enumClass The enum class to search + * @return An enum constant of that class with the same name as this argument's value + * @throws CommandInvalidTypeException If the constant couldn't be found + * @see ArgConsumer#peekEnum(Class) + * @see ArgConsumer#peekEnum(Class, int) + * @see ArgConsumer#peekEnumOrNull(Class) + * @see ArgConsumer#peekEnumOrNull(Class, int) + * @see ArgConsumer#getEnum(Class) + * @see ArgConsumer#getEnumOrNull(Class) + */ public > E getEnum(Class enumClass) { - //noinspection OptionalGetWithoutIsPresent - return Arrays.stream(enumClass.getEnumConstants()) - .filter(e -> e.name().equalsIgnoreCase(value)) - .findFirst() - .get(); + try { + //noinspection OptionalGetWithoutIsPresent + return Arrays.stream(enumClass.getEnumConstants()) + .filter(e -> e.name().equalsIgnoreCase(value)) + .findFirst() + .get(); + } catch (NoSuchElementException e) { + throw new CommandInvalidTypeException(this, enumClass.getSimpleName()); + } } + /** + * Tries to use a stateless {@link ArgParser} to parse this argument into the specified class + * + * @param type The class to parse this argument into + * @return An instance of the specified type + * @throws CommandNoParserForTypeException If no parser exists for that type + * @throws CommandInvalidTypeException If the parsing failed + * @see ArgParser.Stateless + */ public T getAs(Class type) { return ArgParserManager.parseStateless(type, this); } + /** + * Tries to use a stateless {@link ArgParser} to parse this argument into the specified class + * + * @param type The class to parse this argument into + * @return If the parser succeeded + * @see ArgParser.Stateless + */ public boolean is(Class type) { try { getAs(type); @@ -60,10 +107,27 @@ public class CommandArgument { } } + /** + * Tries to use a stated {@link ArgParser} to parse this argument into the specified class + * + * @param type The class to parse this argument into + * @return An instance of the specified type + * @throws CommandNoParserForTypeException If no parser exists for that type + * @throws CommandInvalidTypeException If the parsing failed + * @see ArgParser.Stated + */ + @SuppressWarnings("UnusedReturnValue") public T getAs(Class type, Class stateType, S state) { return ArgParserManager.parseStated(type, stateType, this, state); } + /** + * Tries to use a stated {@link ArgParser} to parse this argument into the specified class + * + * @param type The class to parse this argument into + * @return If the parser succeeded + * @see ArgParser.Stated + */ public boolean is(Class type, Class stateType, S state) { try { getAs(type, stateType, state); @@ -73,6 +137,14 @@ public class CommandArgument { } } + /** + * Turn a string into a list of {@link CommandArgument}s. This is needed because of {@link CommandArgument#rawRest} + * + * @param string The string to convert + * @param preserveEmptyLast If the string ends with whitespace, add an empty {@link CommandArgument} to the end This + * is useful for tab completion + * @return A list of {@link CommandArgument}s + */ public static List from(String string, boolean preserveEmptyLast) { List args = new ArrayList<>(); Matcher argMatcher = argPattern.matcher(string); @@ -94,10 +166,19 @@ public class CommandArgument { return args; } + /** + * @see #from(String, boolean) + */ public static List from(String string) { return from(string, false); } + /** + * Returns an "unknown" {@link CommandArgument}. This shouldn't be used unless you absolutely have no information - + * ESPECIALLY not with {@link CommandInvalidArgumentException}s + * + * @return The unknown {@link CommandArgument} + */ public static CommandArgument unknown() { return new CommandArgument(-1, "", ""); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java index 13e3d686..617ccb57 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java @@ -36,7 +36,7 @@ public class BlockById implements IDatatypeFor { ResourceLocation id = new ResourceLocation(consumer.getString()); if ((block = Block.REGISTRY.getObject(id)) == Blocks.AIR) { - throw new RuntimeException("no block found by that id"); + throw new IllegalArgumentException("no block found by that id"); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java index ea22dc90..09cdbb92 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java @@ -38,7 +38,7 @@ public class EntityClassById implements IDatatypeFor> { ResourceLocation id = new ResourceLocation(consumer.getString()); if (isNull(entity = EntityList.REGISTRY.getObject(id))) { - throw new RuntimeException("no entity found by that id"); + throw new IllegalArgumentException("no entity found by that id"); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java index 90a1c71c..47b63480 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -29,8 +29,6 @@ import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ForWaypoints implements IDatatypeFor { private final IWaypoint[] waypoints; @@ -39,7 +37,7 @@ public class ForWaypoints implements IDatatypeFor { } public ForWaypoints(String arg) { - IWaypoint.Tag tag = getTagByName(arg); + IWaypoint.Tag tag = IWaypoint.Tag.getByName(arg); waypoints = tag == null ? getWaypointsByName(arg) : getWaypointsByTag(tag); } @@ -57,7 +55,7 @@ public class ForWaypoints implements IDatatypeFor { return new TabCompleteHelper() .append(getWaypointNames()) .sortAlphabetically() - .prepend(getTagNames()) + .prepend(IWaypoint.Tag.getAllNames()) .filterPrefix(consumer.getString()) .stream(); } @@ -70,28 +68,6 @@ public class ForWaypoints implements IDatatypeFor { .getWaypoints(); } - public static String[] getTagNames() { - Set names = new HashSet<>(); - - for (IWaypoint.Tag tag : IWaypoint.Tag.values()) { - names.addAll(asList(tag.names)); - } - - return names.toArray(new String[0]); - } - - public static IWaypoint.Tag getTagByName(String name) { - for (IWaypoint.Tag tag : IWaypoint.Tag.values()) { - for (String alias : tag.names) { - if (alias.equalsIgnoreCase(name)) { - return tag; - } - } - } - - return null; - } - public static IWaypoint[] getWaypoints() { return waypoints().getAllWaypoints().stream() .sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed()) diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java index 1684fd2f..5af2a0b8 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java @@ -17,6 +17,7 @@ package baritone.api.utils.command.datatypes; +import baritone.api.utils.command.argparser.ArgParser; import baritone.api.utils.command.exception.CommandInvalidArgumentException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -24,11 +25,23 @@ import java.util.stream.Stream; /** * Since interfaces cannot enforce the presence of a constructor, it's on you to make sure there is a constructor that - * accepts a single {@link ArgConsumer} argument. The constructor will perform all needed validation, and - * {@link ArgConsumer#getDatatype(Class)} will handle RuntimeExceptions and translate them into - * {@link CommandInvalidArgumentException}s. There must always be a constructor with no arguments so that - * {@link ArgConsumer} can create an instance for tab completion. + * accepts a single {@link ArgConsumer} argument. The constructor will perform all needed validation, and {@link + * ArgConsumer#getDatatype(Class)} will handle RuntimeExceptions and translate them into {@link + * CommandInvalidArgumentException}s. There must always be a constructor with no arguments so that {@link ArgConsumer} + * can create an instance for tab completion. */ public interface IDatatype { + /** + * One benefit over datatypes over {@link ArgParser}s is that instead of each command trying to guess what values + * the datatype will accept, or simply not tab completing at all, datatypes that support tab completion can provide + * accurate information using the same methods used to parse arguments in the first place. + *

+ * See {@link RelativeFile} for a very advanced example of tab completion. You wouldn't want this pasted into every + * command that uses files - right? Right? + * + * @param consumer The argument consumer to tab complete + * @return A stream representing the strings that can be tab completed. DO NOT INCLUDE SPACES IN ANY STRINGS. + * @see ArgConsumer#tabCompleteDatatype(Class) + */ Stream tabComplete(ArgConsumer consumer); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java index f38028bd..a3c54b48 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java +++ b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java @@ -46,7 +46,7 @@ public class PlayerByUsername implements IDatatypeFor { .findFirst() .orElse(null) )) { - throw new RuntimeException("no player found by that username"); + throw new IllegalArgumentException("no player found by that username"); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java index 8d5cc70b..866017c7 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java @@ -36,14 +36,10 @@ public class RelativeCoordinate implements IDatatypePost { } public RelativeCoordinate(ArgConsumer consumer) { - if (!consumer.has()) { - throw new RuntimeException("relative coordinate requires an argument"); - } - Matcher matcher = PATTERN.matcher(consumer.getString()); if (!matcher.matches()) { - throw new RuntimeException("pattern doesn't match"); + throw new IllegalArgumentException("pattern doesn't match"); } isRelative = !matcher.group(1).isEmpty(); diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index afc82978..fa0be0b4 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -42,7 +42,7 @@ public class RelativeFile implements IDatatypePost { try { path = FileSystems.getDefault().getPath(consumer.getString()); } catch (InvalidPathException e) { - throw new RuntimeException("invalid path"); + throw new IllegalArgumentException("invalid path"); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java index 1a907135..0730b517 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java @@ -17,7 +17,6 @@ package baritone.api.utils.command.datatypes; -import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java index dba4513e..9de56284 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -19,7 +19,6 @@ package baritone.api.utils.command.exception; import java.io.PrintWriter; import java.io.StringWriter; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -35,7 +34,7 @@ public class CommandUnhandledException extends CommandErrorMessageException { public static String getBaritoneStackTrace(String stackTrace) { List lines = Arrays.stream(stackTrace.split("\n")) - .collect(Collectors.toCollection(ArrayList::new)); + .collect(Collectors.toList()); int lastBaritoneLine = 0; for (int i = 0; i < lines.size(); i++) { diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index 3cf823a0..c68b77c2 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -17,102 +17,328 @@ package baritone.api.utils.command.helpers.arguments; +import baritone.api.utils.Helper; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.argparser.ArgParser; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.datatypes.IDatatype; import baritone.api.utils.command.datatypes.IDatatypeFor; import baritone.api.utils.command.datatypes.IDatatypePost; +import baritone.api.utils.command.datatypes.RelativeFile; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.exception.CommandNoParserForTypeException; import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.exception.CommandTooManyArgumentsException; import baritone.api.utils.command.exception.CommandUnhandledException; +import net.minecraft.util.EnumFacing; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; -import java.util.NoSuchElementException; import java.util.stream.Stream; -public class ArgConsumer { - public final List args; +/** + * The {@link ArgConsumer} is how {@link Command}s read the arguments passed to them. This class has many benefits: + * + *

    + *
  • Mutability. The whole concept of the {@link ArgConsumer} is to let you gradually consume arguments in any way + * you'd like. You can change your consumption based on earlier arguments, for subcommands for example.
  • + *
  • You don't need to keep track of your consumption. The {@link ArgConsumer} keeps track of the arguments you + * consume so that it can throw detailed exceptions whenever something is out of the ordinary. Additionally, if you + * need to retrieve an argument after you've already consumed it - look no further than {@link #consumed()}!
  • + *
  • Easy retrieval of many different types. If you need to retrieve an instance of an int or float for example, + * look no further than {@link #getAs(Class)}. If you need a more powerful way of retrieving data, try out the many + * {@link #getDatatype(Class)} methods.
  • + *
  • It's very easy to throw detailed exceptions. The {@link ArgConsumer} has many different methods that can + * enforce the number of arguments, the type of arguments, and more, throwing different types of + * {@link CommandException}s if something seems off. You're recommended to do all validation and store all needed + * data in variables BEFORE logging any data to chat via {@link Helper#logDirect(String)}, so that the error + * handlers can do their job and log the error to chat.
  • + *
+ */ +public class ArgConsumer implements Cloneable { + /** + * The list of arguments in this ArgConsumer + */ + public final LinkedList args; + + /** + * The list of consumed arguments for this ArgConsumer. The most recently consumed argument is the last one + */ public final Deque consumed; - private ArgConsumer(List args, Deque consumed) { - this.args = new ArrayList<>(args); + private ArgConsumer(Deque args, Deque consumed) { + this.args = new LinkedList<>(args); this.consumed = new LinkedList<>(consumed); } public ArgConsumer(List args) { - this(args, new LinkedList<>()); + this(new LinkedList<>(args), new LinkedList<>()); } + /** + * @param num The number of arguments to check for + * @return {@code true} if there are at least {@code num} arguments left in this {@link ArgConsumer} + * @see #has() + * @see #hasAtMost(int) + * @see #hasExactly(int) + */ public boolean has(int num) { return args.size() >= num; } + /** + * @return {@code true} if there is at least 1 argument left in this {@link ArgConsumer} + * @see #has(int) + * @see #hasAtMostOne() + * @see #hasExactlyOne() + */ public boolean has() { return has(1); } + /** + * @param num The number of arguments to check for + * @return {@code true} if there are at most {@code num} arguments left in this {@link ArgConsumer} + * @see #has(int) + * @see #hasAtMost(int) + * @see #hasExactly(int) + */ public boolean hasAtMost(int num) { return args.size() <= num; } + /** + * @return {@code true} if there is at most 1 argument left in this {@link ArgConsumer} + * @see #has() + * @see #hasAtMostOne() + * @see #hasExactlyOne() + */ public boolean hasAtMostOne() { return hasAtMost(1); } + /** + * @param num The number of arguments to check for + * @return {@code true} if there are exactly {@code num} arguments left in this {@link ArgConsumer} + * @see #has(int) + * @see #hasAtMost(int) + */ public boolean hasExactly(int num) { return args.size() == num; } + /** + * @return {@code true} if there is exactly 1 argument left in this {@link ArgConsumer} + * @see #has() + * @see #hasAtMostOne() + */ public boolean hasExactlyOne() { return hasExactly(1); } + /** + * @param index The index to peek + * @return The argument at index {@code index} in this {@link ArgConsumer}, with 0 being the next one. This does not + * mutate the {@link ArgConsumer} + * @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left + * @see #peek() + * @see #peekString(int) + * @see #peekAs(Class, int) + * @see #get() + */ public CommandArgument peek(int index) { - requireMin(1); + requireMin(index + 1); return args.get(index); } + /** + * @return The next argument in this {@link ArgConsumer}. This does not mutate the {@link ArgConsumer} + * @throws CommandNotEnoughArgumentsException If there is less than one argument left + * @see #peek(int) + * @see #peekString() + * @see #peekAs(Class) + * @see #peekDatatype(Class) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypePost(Class, Object) + * @see #get() + */ public CommandArgument peek() { return peek(0); } - public boolean is(Class type) { - return peek().is(type); + /** + * @param index The index to peek + * @param type The type to check for + * @return If an {@link ArgParser.Stateless} for the specified {@code type} would succeed in parsing the next + * argument + * @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left + * @see #peek() + * @see #getAs(Class) + */ + public boolean is(Class type, int index) { + return peek(index).is(type); } + /** + * @param type The type to check for + * @return If an {@link ArgParser.Stateless} for the specified {@code type} would succeed in parsing the next + * argument + * @throws CommandNotEnoughArgumentsException If there is less than one argument left + * @see #peek() + * @see #getAs(Class) + */ + public boolean is(Class type) { + return is(type, 0); + } + + /** + * @param index The index to peek + * @return The value of the argument at index {@code index} in this {@link ArgConsumer}, with 0 being the next one + * This does not mutate the {@link ArgConsumer} + * @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left + * @see #peek() + * @see #peekString() + */ public String peekString(int index) { return peek(index).value; } + /** + * @return The value of the next argument in this {@link ArgConsumer}. This does not mutate the {@link ArgConsumer} + * @throws CommandNotEnoughArgumentsException If there is less than one argument left + * @see #peekString(int) + * @see #getString() + */ public String peekString() { return peekString(0); } - public > E peekEnum(Class enumClass) { - return peek().getEnum(enumClass); + /** + * @param index The index to peek + * @param enumClass The class to search + * @return From the specified enum class, an enum constant of that class. The enum constant's name will match the + * next argument's value + * @throws java.util.NoSuchElementException If the constant couldn't be found + * @see #peekEnumOrNull(Class) + * @see #getEnum(Class) + * @see CommandArgument#getEnum(Class) + */ + public > E peekEnum(Class enumClass, int index) { + return peek(index).getEnum(enumClass); } - public > E peekEnumOrNull(Class enumClass) { + /** + * @param enumClass The class to search + * @return From the specified enum class, an enum constant of that class. The enum constant's name will match the + * next argument's value + * @throws CommandInvalidTypeException If the constant couldn't be found + * @see #peekEnumOrNull(Class) + * @see #getEnum(Class) + * @see CommandArgument#getEnum(Class) + */ + public > E peekEnum(Class enumClass) { + return peekEnum(enumClass, 0); + } + + /** + * @param index The index to peek + * @param enumClass The class to search + * @return From the specified enum class, an enum constant of that class. The enum constant's name will match the + * next argument's value. If no constant could be found, null + * @see #peekEnum(Class) + * @see #getEnumOrNull(Class) + * @see CommandArgument#getEnum(Class) + */ + public > E peekEnumOrNull(Class enumClass, int index) { try { - return peekEnum(enumClass); - } catch (NoSuchElementException e) { + return peekEnum(enumClass, index); + } catch (CommandInvalidTypeException e) { return null; } } + /** + * @param enumClass The class to search + * @return From the specified enum class, an enum constant of that class. The enum constant's name will match the + * next argument's value. If no constant could be found, null + * @see #peekEnum(Class) + * @see #getEnumOrNull(Class) + * @see CommandArgument#getEnum(Class) + */ + public > E peekEnumOrNull(Class enumClass) { + try { + return peekEnumOrNull(enumClass, 0); + } catch (CommandInvalidTypeException e) { + return null; + } + } + + /** + * Tries to use a stateless {@link ArgParser} to parse the argument at the specified index into the specified + * class + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param type The type to peek as + * @param index The index to peek + * @return An instance of the specified type + * @throws CommandNoParserForTypeException If no parser exists for that type + * @throws CommandInvalidTypeException If the parsing failed + * @see ArgParser + * @see ArgParser.Stateless + * @see #peekAs(Class) + * @see #peekAsOrDefault(Class, Object, int) + * @see #peekAsOrNull(Class, int) + */ public T peekAs(Class type, int index) { return peek(index).getAs(type); } + /** + * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param type The type to peek as + * @return An instance of the specified type + * @throws CommandNoParserForTypeException If no parser exists for that type + * @throws CommandInvalidTypeException If the parsing failed + * @see ArgParser + * @see ArgParser.Stateless + * @see #peekAs(Class, int) + * @see #peekAsOrDefault(Class, Object) + * @see #peekAsOrNull(Class) + */ public T peekAs(Class type) { return peekAs(type, 0); } + /** + * Tries to use a stateless {@link ArgParser} to parse the argument at the specified index into the specified + * class + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param type The type to peek as + * @param def The value to return if the argument can't be parsed + * @param index The index to peek + * @return An instance of the specified type, or {@code def} if it couldn't be parsed + * @see ArgParser + * @see ArgParser.Stateless + * @see #peekAsOrDefault(Class, Object) + * @see #peekAs(Class, int) + * @see #peekAsOrNull(Class, int) + */ public T peekAsOrDefault(Class type, T def, int index) { try { return peekAs(type, index); @@ -121,82 +347,466 @@ public class ArgConsumer { } } + /** + * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param type The type to peek as + * @param def The value to return if the argument can't be parsed + * @return An instance of the specified type, or {@code def} if it couldn't be parsed + * @see ArgParser + * @see ArgParser.Stateless + * @see #peekAsOrDefault(Class, Object, int) + * @see #peekAs(Class) + * @see #peekAsOrNull(Class) + */ public T peekAsOrDefault(Class type, T def) { return peekAsOrDefault(type, def, 0); } + + /** + * Tries to use a stateless {@link ArgParser} to parse the argument at the specified index into the specified + * class + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param type The type to peek as + * @param index The index to peek + * @return An instance of the specified type, or {@code null} if it couldn't be parsed + * @see ArgParser + * @see ArgParser.Stateless + * @see #peekAsOrNull(Class) + * @see #peekAs(Class, int) + * @see #peekAsOrDefault(Class, Object, int) + */ public T peekAsOrNull(Class type, int index) { - return peekAsOrDefault(type, null, 0); + return peekAsOrDefault(type, null, index); } + /** + * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param type The type to peek as + * @return An instance of the specified type, or {@code null} if it couldn't be parsed + * @see ArgParser + * @see ArgParser.Stateless + * @see #peekAsOrNull(Class, int) + * @see #peekAs(Class) + * @see #peekAsOrDefault(Class, Object) + */ public T peekAsOrNull(Class type) { return peekAsOrNull(type, 0); } + /** + * Attempts to get the specified datatype from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. + * + * @param datatype The datatype to get + * @return The datatype instance + * @see IDatatype + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + */ public T peekDatatype(Class datatype) { return clone().getDatatype(datatype); } + /** + * Attempts to get the specified datatype from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. + * + * @param datatype The datatype to get + * @return The datatype instance, or {@code null} if it throws an exception + * @see IDatatype + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + */ public T peekDatatypeOrNull(Class datatype) { - return new ArgConsumer(args, consumed).getDatatypeOrNull(datatype); + return clone().getDatatypeOrNull(datatype); } + /** + * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. + * + * @param datatype The datatype to get + * @return The datatype instance + * @see IDatatype + * @see IDatatypePost + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + */ public > T peekDatatypePost(Class datatype, O original) { - return new ArgConsumer(args, consumed).getDatatypePost(datatype, original); + return clone().getDatatypePost(datatype, original); } + /** + * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. + * + * @param datatype The datatype to get + * @param def The default value + * @return The datatype instance, or {@code def} if it throws an exception + * @see IDatatype + * @see IDatatypePost + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + */ public > T peekDatatypePostOrDefault(Class datatype, O original, T def) { - return new ArgConsumer(args, consumed).getDatatypePostOrDefault(datatype, original, def); + return clone().getDatatypePostOrDefault(datatype, original, def); } + /** + * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. + * + * @param datatype The datatype to get + * @return The datatype instance, or {@code null} if it throws an exception + * @see IDatatype + * @see IDatatypePost + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + */ public > T peekDatatypePostOrNull(Class datatype, O original) { return peekDatatypePostOrDefault(datatype, original, null); } + /** + * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. + * + * @param datatype The datatype to get + * @return The datatype instance + * @see IDatatype + * @see IDatatypeFor + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + */ public > T peekDatatypeFor(Class datatype) { - return new ArgConsumer(args, consumed).peekDatatypeFor(datatype); + return clone().peekDatatypeFor(datatype); } + /** + * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. + * + * @param datatype The datatype to get + * @param def The default value + * @return The datatype instance, or {@code def} if it throws an exception + * @see IDatatype + * @see IDatatypeFor + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + */ public > T peekDatatypeForOrDefault(Class datatype, T def) { - return new ArgConsumer(args, consumed).peekDatatypeForOrDefault(datatype, def); + return clone().peekDatatypeForOrDefault(datatype, def); } - public > T peekDatatypeForOrNull(Class datatype, T def) { + /** + * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. + * + * @param datatype The datatype to get + * @return The datatype instance, or {@code null} if it throws an exception + * @see IDatatype + * @see IDatatypeFor + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + */ + public > T peekDatatypeForOrNull(Class datatype) { return peekDatatypeForOrDefault(datatype, null); } + /** + * Gets the next argument and returns it. This consumes the first argument so that subsequent calls will return + * later arguments + * + * @return The next argument + * @throws CommandNotEnoughArgumentsException If there's less than one argument left + */ public CommandArgument get() { requireMin(1); - CommandArgument arg = args.remove(0); + CommandArgument arg = args.removeFirst(); consumed.add(arg); return arg; } + /** + * Gets the value of the next argument and returns it. This consumes the first argument so that subsequent calls + * will return later arguments + * + * @return The value of the next argument + * @throws CommandNotEnoughArgumentsException If there's less than one argument left + */ public String getString() { return get().value; } + /** + * Gets an enum value from the enum class with the same name as the next argument's value + *

+ * For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return + * {@link EnumFacing#UP} + * + * @param enumClass The enum class to search + * @return An enum constant of that class with the same name as the next argument's value + * @throws CommandInvalidTypeException If the constant couldn't be found + * @see #peekEnum(Class) + * @see #getEnumOrNull(Class) + * @see CommandArgument#getEnum(Class) + */ public > E getEnum(Class enumClass) { - try { - return get().getEnum(enumClass); - } catch (NoSuchElementException e) { - throw new CommandInvalidTypeException(consumed(), enumClass.getSimpleName()); - } + return get().getEnum(enumClass); } - public > E getEnumOrNull(Class enumClass) { + /** + * Gets an enum value from the enum class with the same name as the next argument's value + *

+ * For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return + * {@link EnumFacing#UP} + * + * @param enumClass The enum class to search + * @param def The default value + * @return An enum constant of that class with the same name as the next argument's value, or {@code def} if it + * couldn't be found + * @see #getEnum(Class) + * @see #getEnumOrNull(Class) + * @see #peekEnumOrNull(Class) + * @see CommandArgument#getEnum(Class) + */ + public > E getEnumOrDefault(Class enumClass, E def) { try { peekEnum(enumClass); return getEnum(enumClass); } catch (CommandInvalidTypeException e) { - return null; + return def; } } + /** + * Gets an enum value from the enum class with the same name as the next argument's value + *

+ * For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return + * {@link EnumFacing#UP} + * + * @param enumClass The enum class to search + * @return An enum constant of that class with the same name as the next argument's value, or {@code null} if it + * couldn't be found + * @see #getEnum(Class) + * @see #getEnumOrDefault(Class, Enum) + * @see #peekEnumOrNull(Class) + * @see CommandArgument#getEnum(Class) + */ + public > E getEnumOrNull(Class enumClass) { + return getEnumOrDefault(enumClass, null); + } + + /** + * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param type The type to peek as + * @return An instance of the specified type + * @throws CommandNoParserForTypeException If no parser exists for that type + * @throws CommandInvalidTypeException If the parsing failed + * @see ArgParser + * @see ArgParser.Stateless + * @see #get() + * @see #getAsOrDefault(Class, Object) + * @see #getAsOrNull(Class) + * @see #peekAs(Class) + * @see #peekAsOrDefault(Class, Object, int) + * @see #peekAsOrNull(Class, int) + */ public T getAs(Class type) { return get().getAs(type); } + /** + * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param type The type to peek as + * @param def The default value + * @return An instance of the specified type, or {@code def} if it couldn't be parsed + * @see ArgParser + * @see ArgParser.Stateless + * @see #get() + * @see #getAs(Class) + * @see #getAsOrNull(Class) + * @see #peekAs(Class) + * @see #peekAsOrDefault(Class, Object, int) + * @see #peekAsOrNull(Class, int) + */ public T getAsOrDefault(Class type, T def) { try { T val = peek().getAs(type); @@ -207,10 +817,55 @@ public class ArgConsumer { } } + /** + * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param type The type to peek as + * @return An instance of the specified type, or {@code null} if it couldn't be parsed + * @see ArgParser + * @see ArgParser.Stateless + * @see #get() + * @see #getAs(Class) + * @see #getAsOrDefault(Class, Object) + * @see #peekAs(Class) + * @see #peekAsOrDefault(Class, Object, int) + * @see #peekAsOrNull(Class, int) + */ public T getAsOrNull(Class type) { return getAsOrDefault(type, null); } + /** + * Attempts to get the specified datatype from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param datatype The datatype to get + * @return The datatype instance + * @see IDatatype + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + */ public T getDatatype(Class datatype) { try { return datatype.getConstructor(ArgConsumer.class).newInstance(this); @@ -221,46 +876,289 @@ public class ArgConsumer { } } + /** + * Attempts to get the specified datatype from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. + * + * @param datatype The datatype to get + * @return The datatype instance, or {@code null} if it throws an exception + * @see IDatatype + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + */ public T getDatatypeOrNull(Class datatype) { + List argsSnapshot = new ArrayList<>(args); + List consumedSnapshot = new ArrayList<>(consumed); + try { return getDatatype(datatype); } catch (CommandInvalidTypeException e) { + args.clear(); + args.addAll(argsSnapshot); + consumed.clear(); + consumed.addAll(consumedSnapshot); + return null; } } + /** + * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param datatype The datatype to get + * @return The datatype instance + * @see IDatatype + * @see IDatatypePost + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + */ public > T getDatatypePost(Class datatype, O original) { return getDatatype(datatype).apply(original); } + /** + * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. + * + * @param datatype The datatype to get + * @param def The default value + * @return The datatype instance, or {@code def} if it throws an exception + * @see IDatatype + * @see IDatatypePost + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + */ public > T getDatatypePostOrDefault(Class datatype, O original, T def) { + List argsSnapshot = new ArrayList<>(args); + List consumedSnapshot = new ArrayList<>(consumed); + try { return getDatatypePost(datatype, original); } catch (CommandException e) { + args.clear(); + args.addAll(argsSnapshot); + consumed.clear(); + consumed.addAll(consumedSnapshot); + return def; } } + /** + * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. + * + * @param datatype The datatype to get + * @return The datatype instance, or {@code null} if it throws an exception + * @see IDatatype + * @see IDatatypePost + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + */ public > T getDatatypePostOrNull(Class datatype, O original) { return getDatatypePostOrDefault(datatype, original, null); } + /** + * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + * + * @param datatype The datatype to get + * @return The datatype instance + * @see IDatatype + * @see IDatatypeFor + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + */ public > T getDatatypeFor(Class datatype) { return getDatatype(datatype).get(); } + /** + * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. + * + * @param datatype The datatype to get + * @param def The default value + * @return The datatype instance, or {@code def} if it throws an exception + * @see IDatatype + * @see IDatatypeFor + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + */ public > T getDatatypeForOrDefault(Class datatype, T def) { + List argsSnapshot = new ArrayList<>(args); + List consumedSnapshot = new ArrayList<>(consumed); + try { return getDatatypeFor(datatype); } catch (CommandInvalidTypeException e) { + args.clear(); + args.addAll(argsSnapshot); + consumed.clear(); + consumed.addAll(consumedSnapshot); + return def; } } + /** + * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer + *

+ * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. + * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * {@link ArgConsumer}. + *

+ * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. + * + * @param datatype The datatype to get + * @return The datatype instance, or {@code null} if it throws an exception + * @see IDatatype + * @see IDatatypeFor + * @see #getDatatype(Class) + * @see #getDatatypeOrNull(Class) + * @see #getDatatypePost(Class, Object) + * @see #getDatatypePostOrDefault(Class, Object, Object) + * @see #getDatatypePostOrNull(Class, Object) + * @see #getDatatypeFor(Class) + * @see #getDatatypeForOrDefault(Class, Object) + * @see #getDatatypeForOrNull(Class) + * @see #peekDatatype(Class) + * @see #peekDatatypeOrNull(Class) + * @see #peekDatatypePost(Class, Object) + * @see #peekDatatypePostOrDefault(Class, Object, Object) + * @see #peekDatatypePostOrNull(Class, Object) + * @see #peekDatatypeFor(Class) + * @see #peekDatatypeForOrDefault(Class, Object) + * @see #peekDatatypeForOrNull(Class) + */ public > T getDatatypeForOrNull(Class datatype) { return getDatatypeForOrDefault(datatype, null); } + /** + * One benefit over datatypes over {@link ArgParser}s is that instead of each command trying to guess what values + * the datatype will accept, or simply not tab completing at all, datatypes that support tab completion can provide + * accurate information using the same methods used to parse arguments in the first place. + *

+ * See {@link RelativeFile} for a very advanced example of tab completion. You wouldn't want this pasted into every + * command that uses files - right? Right? + * + * @param datatype The datatype to get tab completions from + * @return A stream representing the strings that can be tab completed. DO NOT INCLUDE SPACES IN ANY STRINGS. + * @see IDatatype#tabComplete(ArgConsumer) + */ public Stream tabCompleteDatatype(Class datatype) { try { return datatype.getConstructor().newInstance().tabComplete(this); @@ -271,45 +1169,104 @@ public class ArgConsumer { return Stream.empty(); } + /** + * Returns the "raw rest" of the string. For example, from a string arg1 arg2  arg3, split + * into three {@link CommandArgument}s {@code "arg1"}, {@code "arg2"}, and {@code "arg3"}: + * + *

    + *
  • {@code rawRest()} would return arg1 arg2  arg3
  • + *
  • After calling {@link #get()}, {@code rawRest()} would return arg2  arg3 (note the + * double space - it is preserved!)
  • + *
  • After calling {@link #get()} again, {@code rawRest()} would return {@code "arg3"}
  • + *
  • After calling {@link #get()} one last time, {@code rawRest()} would return {@code ""}
  • + *
+ * + * @return The "raw rest" of the string. + */ public String rawRest() { - return args.size() > 0 ? args.get(0).rawRest : ""; + return args.size() > 0 ? args.getFirst().rawRest : ""; } + /** + * @param min The minimum amount of arguments to require. + * @throws CommandNotEnoughArgumentsException If there are less than {@code min} arguments left. + * @see #requireMax(int) + * @see #requireExactly(int) + */ public void requireMin(int min) { if (args.size() < min) { throw new CommandNotEnoughArgumentsException(min + consumed.size()); } } + /** + * @param max The maximum amount of arguments allowed. + * @throws CommandNotEnoughArgumentsException If there are more than {@code max} arguments left. + * @see #requireMin(int) + * @see #requireExactly(int) + */ public void requireMax(int max) { if (args.size() > max) { throw new CommandTooManyArgumentsException(max + consumed.size()); } } + /** + * @param args The exact amount of arguments to require. + * @throws CommandNotEnoughArgumentsException If there are less than {@code args} arguments left. + * @throws CommandTooManyArgumentsException If there are more than {@code args} arguments left. + * @see #requireMin(int) + * @see #requireMax(int) + */ public void requireExactly(int args) { requireMin(args); requireMax(args); } + /** + * @return If this {@link ArgConsumer} has consumed at least one argument. + * @see #consumed() + * @see #consumedString() + */ public boolean hasConsumed() { return !consumed.isEmpty(); } + /** + * @return The last argument this {@link ArgConsumer} has consumed, or the {@link CommandArgument#unknown() unknown} + * argument if no arguments have been consumed yet. + * @see #consumedString() + * @see #hasConsumed() + */ public CommandArgument consumed() { return consumed.size() > 0 ? consumed.getLast() : CommandArgument.unknown(); } + /** + * @return The value of thelast argument this {@link ArgConsumer} has consumed, or an empty string if no arguments + * have been consumed yet + * @see #consumed() + * @see #hasConsumed() + */ public String consumedString() { return consumed().value; } + /** + * @return A clone of this {@link ArgConsumer}. It has the same arguments (both consumed and not), but does not + * affect or mutate this instance. Useful for the various {@code peek} functions + */ @SuppressWarnings("MethodDoesntCallSuperMethod") @Override public ArgConsumer clone() { return new ArgConsumer(args, consumed); } + /** + * @param string The string to split + * @return A new {@link ArgConsumer} constructed from the specified string + * @see CommandArgument#from(String) + */ public static ArgConsumer from(String string) { return new ArgConsumer(CommandArgument.from(string)); } diff --git a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java index 24d0b6a3..2fb2f5bc 100644 --- a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java +++ b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java @@ -79,45 +79,45 @@ public class Paginator implements Helper { boolean hasPrevPage = nonNull(commandPrefix) && validPage(page - 1); boolean hasNextPage = nonNull(commandPrefix) && validPage(page + 1); - logDirect(new TextComponentString("") {{ - getStyle().setColor(TextFormatting.GRAY); + ITextComponent prevPageComponent = new TextComponentString("<<"); - appendSibling(new TextComponentString("<<") {{ - if (hasPrevPage) { - getStyle() - .setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - String.format("%s %d", commandPrefix, page - 1) - )) - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("Click to view previous page") - )); - } else { - getStyle().setColor(TextFormatting.DARK_GRAY); - } - }}); + if (hasPrevPage) { + prevPageComponent.getStyle() + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format("%s %d", commandPrefix, page - 1) + )) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to view previous page") + )); + } else { + prevPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY); + } - appendText(" | "); + ITextComponent nextPageComponent = new TextComponentString(">>"); - appendSibling(new TextComponentString(">>") {{ - if (hasNextPage) { - getStyle() - .setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - commandPrefix + " " + (page + 1) - )) - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("Click to view next page") - )); - } else { - getStyle().setColor(TextFormatting.DARK_GRAY); - } - }}); + if (hasNextPage) { + nextPageComponent.getStyle() + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format("%s %d", commandPrefix, page + 1) + )) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to view next page") + )); + } else { + nextPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY); + } - appendText(String.format(" %d/%d", page, getMaxPage())); - }}); + ITextComponent pagerComponent = new TextComponentString(""); + pagerComponent.getStyle().setColor(TextFormatting.GRAY); + pagerComponent.appendSibling(prevPageComponent); + pagerComponent.appendText(" | "); + pagerComponent.appendSibling(nextPageComponent); + pagerComponent.appendText(String.format(" %d/%d", page, getMaxPage())); + logDirect(pagerComponent); } public void display(Function transform) { diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index ce689b0b..972b634d 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -19,7 +19,10 @@ package baritone.api.utils.command.helpers.tabcomplete; import baritone.api.BaritoneAPI; import baritone.api.Settings; +import baritone.api.event.events.TabCompleteEvent; import baritone.api.utils.SettingsUtil; +import baritone.api.utils.command.execution.CommandExecution; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.manager.CommandManager; import net.minecraft.util.ResourceLocation; @@ -31,9 +34,24 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; -import static java.util.stream.Stream.concat; -import static java.util.stream.Stream.of; - +/** + * The {@link TabCompleteHelper} is a single-use object that helps you handle tab completion. It includes helper + * methods for appending and prepending streams, sorting, filtering by prefix, and so on. + *

+ * The recommended way to use this class is: + *

    + *
  • Create a new instance with the empty constructor
  • + *
  • Use {@code append}, {@code prepend} or {@code add} methods to add completions
  • + *
  • Sort using {@link #sort(Comparator)} or {@link #sortAlphabetically()} and then filter by prefix using + * {@link #filterPrefix(String)}
  • + *
  • Get the stream using {@link #stream()}
  • + *
  • Pass it up to whatever's calling your tab complete function (i.e. + * {@link CommandManager#tabComplete(CommandExecution)} or {@link ArgConsumer#tabCompleteDatatype(Class)})
  • + *
+ *

+ * For advanced users: if you're intercepting {@link TabCompleteEvent}s directly, use {@link #build()} instead for an + * array. + */ public class TabCompleteHelper { private Stream stream; @@ -49,16 +67,49 @@ public class TabCompleteHelper { this(new String[0]); } + /** + * Appends the specified stream to this {@link TabCompleteHelper} and returns it for chaining + * + * @param source The stream to append + * @return This {@link TabCompleteHelper} after having appended the stream + * @see #append(String...) + * @see #append(Class) + * @see #prepend(Stream) + * @see #prepend(String...) + * @see #prepend(Class) + */ public TabCompleteHelper append(Stream source) { - stream = concat(stream, source); + stream = Stream.concat(stream, source); return this; } + /** + * Appends the specified strings to this {@link TabCompleteHelper} and returns it for chaining + * + * @param source The stream to append + * @return This {@link TabCompleteHelper} after having appended the strings + * @see #append(Stream) + * @see #append(Class) + * @see #prepend(Stream) + * @see #prepend(String...) + * @see #prepend(Class) + */ public TabCompleteHelper append(String... source) { - return append(of(source)); + return append(Stream.of(source)); } + /** + * Appends all values of the specified enum to this {@link TabCompleteHelper} and returns it for chaining + * + * @param num The enum to append the values of + * @return This {@link TabCompleteHelper} after having appended the values + * @see #append(Stream) + * @see #append(String...) + * @see #prepend(Stream) + * @see #prepend(String...) + * @see #prepend(Class) + */ public TabCompleteHelper append(Class> num) { return append( Arrays.stream(num.getEnumConstants()) @@ -67,16 +118,49 @@ public class TabCompleteHelper { ); } + /** + * Prepends the specified stream to this {@link TabCompleteHelper} and returns it for chaining + * + * @param source The stream to prepend + * @return This {@link TabCompleteHelper} after having prepended the stream + * @see #append(Stream) + * @see #append(String...) + * @see #append(Class) + * @see #prepend(String...) + * @see #prepend(Class) + */ public TabCompleteHelper prepend(Stream source) { - stream = concat(source, stream); + stream = Stream.concat(source, stream); return this; } + /** + * Prepends the specified strings to this {@link TabCompleteHelper} and returns it for chaining + * + * @param source The stream to prepend + * @return This {@link TabCompleteHelper} after having prepended the strings + * @see #append(Stream) + * @see #append(String...) + * @see #append(Class) + * @see #prepend(Stream) + * @see #prepend(Class) + */ public TabCompleteHelper prepend(String... source) { - return prepend(of(source)); + return prepend(Stream.of(source)); } + /** + * Prepends all values of the specified enum to this {@link TabCompleteHelper} and returns it for chaining + * + * @param num The enum to prepend the values of + * @return This {@link TabCompleteHelper} after having prepended the values + * @see #append(Stream) + * @see #append(String...) + * @see #append(Class) + * @see #prepend(Stream) + * @see #prepend(String...) + */ public TabCompleteHelper prepend(Class> num) { return prepend( Arrays.stream(num.getEnumConstants()) @@ -85,44 +169,98 @@ public class TabCompleteHelper { ); } + /** + * Apply the specified {@code transform} to every element currently in this {@link TabCompleteHelper} and + * return this object for chaining + * + * @param transform The transform to apply + * @return This {@link TabCompleteHelper} + */ public TabCompleteHelper map(Function transform) { stream = stream.map(transform); return this; } + /** + * Apply the specified {@code filter} to every element currently in this {@link TabCompleteHelper} and return + * this object for chaining + * + * @param filter The filter to apply + * @return This {@link TabCompleteHelper} + */ public TabCompleteHelper filter(Predicate filter) { stream = stream.filter(filter); return this; } + /** + * Apply the specified {@code sort} to every element currently in this {@link TabCompleteHelper} and return + * this object for chaining + * + * @param comparator The comparator to use + * @return This {@link TabCompleteHelper} + */ public TabCompleteHelper sort(Comparator comparator) { stream = stream.sorted(comparator); return this; } + /** + * Sort every element currently in this {@link TabCompleteHelper} alphabetically and return this object for + * chaining + * + * @return This {@link TabCompleteHelper} + */ public TabCompleteHelper sortAlphabetically() { return sort(String.CASE_INSENSITIVE_ORDER); } + /** + * Filter out any element that doesn't start with {@code prefix} and return this object for chaining + * + * @param prefix The prefix to filter for + * @return This {@link TabCompleteHelper} + */ public TabCompleteHelper filterPrefix(String prefix) { return filter(x -> x.toLowerCase(Locale.US).startsWith(prefix.toLowerCase(Locale.US))); } + /** + * Filter out any element that doesn't start with {@code prefix} and return this object for chaining + *

+ * Assumes every element in this {@link TabCompleteHelper} is a {@link ResourceLocation} + * + * @param prefix The prefix to filter for + * @return This {@link TabCompleteHelper} + */ public TabCompleteHelper filterPrefixNamespaced(String prefix) { return filterPrefix(new ResourceLocation(prefix).toString()); } + /** + * @return An array containing every element in this {@link TabCompleteHelper} + * @see #stream() + */ public String[] build() { return stream.toArray(String[]::new); } + /** + * @return A stream containing every element in this {@link TabCompleteHelper} + * @see #build() + */ public Stream stream() { return stream; } + /** + * Appends every command in the {@link CommandManager#REGISTRY} to this {@link TabCompleteHelper} + * + * @return This {@link TabCompleteHelper} + */ public TabCompleteHelper addCommands() { return append( CommandManager.REGISTRY.descendingStream() @@ -131,6 +269,11 @@ public class TabCompleteHelper { ); } + /** + * Appends every setting in the {@link Settings} to this {@link TabCompleteHelper} + * + * @return This {@link TabCompleteHelper} + */ public TabCompleteHelper addSettings() { return append( BaritoneAPI.getSettings().allSettings.stream() @@ -140,6 +283,11 @@ public class TabCompleteHelper { ); } + /** + * Appends every modified setting in the {@link Settings} to this {@link TabCompleteHelper} + * + * @return This {@link TabCompleteHelper} + */ public TabCompleteHelper addModifiedSettings() { return append( SettingsUtil.modifiedSettings(BaritoneAPI.getSettings()).stream() @@ -148,6 +296,11 @@ public class TabCompleteHelper { ); } + /** + * Appends every {@link Boolean} setting in the {@link Settings} to this {@link TabCompleteHelper} + * + * @return This {@link TabCompleteHelper} + */ public TabCompleteHelper addToggleableSettings() { return append( BaritoneAPI.getSettings().getAllValuesByType(Boolean.class).stream() diff --git a/src/api/java/baritone/api/utils/command/registry/Registry.java b/src/api/java/baritone/api/utils/command/registry/Registry.java index c92d4d56..b17997d3 100644 --- a/src/api/java/baritone/api/utils/command/registry/Registry.java +++ b/src/api/java/baritone/api/utils/command/registry/Registry.java @@ -20,10 +20,10 @@ package baritone.api.utils.command.registry; import java.util.Collection; import java.util.Collections; import java.util.Deque; -import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; -import java.util.Map; +import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; @@ -50,11 +50,11 @@ public class Registry { private final Deque _entries = new LinkedList<>(); /** - * A HashMap containing keys for every entry currently registered. Map entries are added to this map when something - * is registered and removed from the map when they are unregistered. An entry simply being present in this map - * indicates that it is currently registered and therefore can be removed and should not be reregistered. + * A HashSet containing every entry currently registered. Entries are added to this set when something is registered + * and removed from the set when they are unregistered. An entry being present in this set indicates that it is + * currently registered, can be removed, and should not be reregistered until it is removed. */ - private final Map registered = new HashMap<>(); + private final Set registered = new HashSet<>(); /** * The collection of entries that are currently in this registry. This is a collection (and not a list) because, @@ -67,7 +67,7 @@ public class Registry { * @return If this entry is currently registered in this registry. */ public boolean registered(V entry) { - return registered.containsKey(entry); + return registered.contains(entry); } /** @@ -81,7 +81,7 @@ public class Registry { public boolean register(V entry) { if (!registered(entry)) { _entries.addFirst(entry); - registered.put(entry, true); + registered.add(entry); return true; } diff --git a/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java index 39fbb19d..1cbf32e7 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java +++ b/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java @@ -25,13 +25,22 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(GuiChat.ChatTabCompleter.class) public abstract class MixinChatTabCompleter extends MixinTabCompleter { - @Inject(method = "*", at = @At("RETURN")) + @Inject( + method = "*", + at = @At("RETURN") + ) private void onConstruction(CallbackInfo ci) { isChatCompleter = true; } - @Inject(method = "complete", at = @At("HEAD"), cancellable = true) + @Inject( + method = "complete", + at = @At("HEAD"), + cancellable = true + ) private void onComplete(CallbackInfo ci) { - if (dontComplete) ci.cancel(); + if (dontComplete) { + ci.cancel(); + } } } diff --git a/src/launch/java/baritone/launch/mixins/MixinGuiChat.java b/src/launch/java/baritone/launch/mixins/MixinGuiChat.java index 9af0a3e9..86f2b1b0 100644 --- a/src/launch/java/baritone/launch/mixins/MixinGuiChat.java +++ b/src/launch/java/baritone/launch/mixins/MixinGuiChat.java @@ -31,7 +31,11 @@ public abstract class MixinGuiChat implements net.minecraft.util.ITabCompleter { @Shadow private TabCompleter tabCompleter; - @Inject(method = "setCompletions", at = @At("HEAD"), cancellable = true) + @Inject( + method = "setCompletions", + at = @At("HEAD"), + cancellable = true + ) private void onSetCompletions(String[] newCompl, CallbackInfo ci) { if (((ITabCompleter) tabCompleter).onGuiChatSetCompletions(newCompl)) { ci.cancel(); diff --git a/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java b/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java index 35fcc38b..78da7b21 100644 --- a/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java +++ b/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java @@ -17,7 +17,7 @@ package baritone.launch.mixins; -import baritone.api.utils.command.Lol; +import baritone.api.accessor.IGuiScreen; import net.minecraft.client.gui.GuiScreen; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; @@ -25,7 +25,7 @@ import org.spongepowered.asm.mixin.gen.Invoker; import java.net.URI; @Mixin(GuiScreen.class) -public abstract class MixinGuiScreen implements Lol { +public abstract class MixinGuiScreen implements IGuiScreen { @Override @Invoker("openWebLink") public abstract void openLink(URI url); diff --git a/src/launch/java/baritone/launch/mixins/MixinItemStack.java b/src/launch/java/baritone/launch/mixins/MixinItemStack.java index 4f27152d..03f5e25f 100644 --- a/src/launch/java/baritone/launch/mixins/MixinItemStack.java +++ b/src/launch/java/baritone/launch/mixins/MixinItemStack.java @@ -44,12 +44,18 @@ public abstract class MixinItemStack implements IItemStack { baritoneHash = item == null ? -1 : item.hashCode() + itemDamage; } - @Inject(method = "*", at = @At("RETURN")) + @Inject( + method = "*", + at = @At("RETURN") + ) private void onInit(CallbackInfo ci) { recalculateHash(); } - @Inject(method = "setItemDamage", at = @At("TAIL")) + @Inject( + method = "setItemDamage", + at = @At("TAIL") + ) private void onItemDamageSet(CallbackInfo ci) { recalculateHash(); } diff --git a/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java b/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java index 9e2e2396..de74a4db 100644 --- a/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java +++ b/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java @@ -40,7 +40,10 @@ public abstract class MixinStateImplementation { @Unique private int hashCode; - @Inject(method = "*", at = @At("RETURN")) + @Inject( + method = "*", + at = @At("RETURN") + ) private void onInit(CallbackInfo ci) { hashCode = properties.hashCode(); } diff --git a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java index 6046ed21..b07dd9d0 100644 --- a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java +++ b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java @@ -63,17 +63,17 @@ public abstract class MixinTabCompleter implements ITabCompleter { textField.setCursorPosition(prefix.length()); } - @Inject(method = "requestCompletions", at = @At("HEAD"), cancellable = true) + @Inject( + method = "requestCompletions", + at = @At("HEAD"), + cancellable = true + ) private void onRequestCompletions(String prefix, CallbackInfo ci) { if (!isChatCompleter) { return; } - IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(Minecraft.getMinecraft().player); - - if (isNull(baritone)) { - return; - } + IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone(); TabCompleteEvent.Pre event = new TabCompleteEvent.Pre(prefix); baritone.getGameEventHandler().onPreTabComplete(event); diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 0b7e614f..4b00c797 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -113,9 +113,6 @@ public class Baritone implements IBaritone { memoryBehavior = new MemoryBehavior(this); inventoryBehavior = new InventoryBehavior(this); inputOverrideHandler = new InputOverrideHandler(this); - - DefaultCommands.commands.forEach(CommandManager.REGISTRY::register); - new BaritoneChatControl(this); } this.pathingControlManager = new PathingControlManager(this); @@ -138,6 +135,9 @@ public class Baritone implements IBaritone { } this.initialized = true; + + DefaultCommands.COMMANDS.forEach(CommandManager.REGISTRY::register); + new BaritoneChatControl(this); } @Override diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 0d600853..c278738a 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -133,7 +133,7 @@ public final class InventoryBehavior extends Behavior { } public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) { - IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, ctx.world().getBlockState(new BlockPos(x, y, z))); + IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, baritone.bsi.get0(x, y, z)); if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && maybe.equals(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(ctx.world(), ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ, stack.getItem().getMetadata(stack.getMetadata()), ctx.player())))) { return true; // gotem } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index d1d9a7d5..c3aa2ad9 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -291,11 +291,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return hasPath() && !pausedThisTick; } - @Override - public boolean hasPath() { - return current != null; - } - @Override public PathExecutor getCurrent() { return current; diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index 3acd9661..458e7afe 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -17,7 +17,9 @@ 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.IBlockStateContainer; @@ -26,6 +28,7 @@ import net.minecraft.client.multiplayer.ChunkProviderClient; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import java.util.ArrayList; @@ -35,6 +38,8 @@ import java.util.Comparator; import java.util.List; import java.util.stream.IntStream; +import static java.util.Objects.nonNull; + public enum WorldScanner implements IWorldScanner { INSTANCE; @@ -44,6 +49,11 @@ public enum WorldScanner implements IWorldScanner { @Override public List scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLookup filter, int max, int yLevelThreshold, int maxSearchRadius) { ArrayList res = new ArrayList<>(); + + if (filter.blocks().isEmpty()) { + return res; + } + ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); int maxSearchRadiusSq = maxSearchRadius * maxSearchRadius; @@ -79,8 +89,8 @@ public enum WorldScanner implements IWorldScanner { } } if ((allUnloaded && foundChunks) - || (res.size() >= max - && (searchRadiusSq > maxSearchRadiusSq || (searchRadiusSq > 1 && foundWithinY))) + || (res.size() >= max + && (searchRadiusSq > maxSearchRadiusSq || (searchRadiusSq > 1 && foundWithinY))) ) { return res; } @@ -90,6 +100,10 @@ public enum WorldScanner implements IWorldScanner { @Override public List scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold) { + if (filter.blocks().isEmpty()) { + return Collections.emptyList(); + } + ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); Chunk chunk = chunkProvider.getLoadedChunk(pos.x, pos.z); int playerY = ctx.playerFeet().getY(); @@ -121,7 +135,7 @@ public enum WorldScanner implements IWorldScanner { for (int i = 0; i < imax; i++) { IBlockState state = bsc.getAtPalette(storage[i]); if (filter.has(state)) { - int y = yReal | (i >> 8 & 15); + int y = yReal | ((i >> 8) & 15); if (result.size() >= max) { if (Math.abs(y - playerY) < yLevelThreshold) { foundWithinY = true; @@ -133,10 +147,32 @@ public enum WorldScanner implements IWorldScanner { } } } - result.add(new BlockPos(chunkX | (i & 15), y, chunkZ | (i >> 4 & 15))); + result.add(new BlockPos(chunkX | (i & 15), y, chunkZ | ((i >> 4) & 15))); } } } return foundWithinY; } + + public int repack(IPlayerContext ctx) { + 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 queued = 0; + for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) { + for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) { + Chunk chunk = chunkProvider.getLoadedChunk(x, z); + + if (nonNull(chunk) && !chunk.isEmpty()) { + queued++; + cachedWorld.queueForPacking(chunk); + } + } + } + + return queued; + } } diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 5bd19bc2..b8739d1c 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -177,7 +177,7 @@ public interface MovementHelper extends ActionCosts, Helper { return block.isPassable(null, null); } - static boolean isReplacable(int x, int y, int z, IBlockState state, BlockStateInterface bsi) { + static boolean isReplaceable(int x, int y, int z, IBlockState state, BlockStateInterface bsi) { // for MovementTraverse and MovementAscend // block double plant defaults to true when the block doesn't match, so don't need to check that case // all other overrides just return true or false @@ -207,6 +207,11 @@ public interface MovementHelper extends ActionCosts, Helper { return state.getMaterial().isReplaceable(); } + @Deprecated + static boolean isReplacable(int x, int y, int z, IBlockState state, BlockStateInterface bsi) { + return isReplaceable(x, y, z, state, bsi); + } + static boolean isDoorPassable(IPlayerContext ctx, BlockPos doorPos, BlockPos playerPos) { if (playerPos.equals(doorPos)) { return false; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index cbc8cdd8..66827a35 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -73,7 +73,7 @@ public class MovementAscend extends Movement { if (additionalPlacementCost >= COST_INF) { return COST_INF; } - if (!MovementHelper.isReplacable(destX, y, destZ, toPlace, context.bsi)) { + if (!MovementHelper.isReplaceable(destX, y, destZ, toPlace, context.bsi)) { return COST_INF; } boolean foundPlaceOption = false; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 8e660aff..41a183f8 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -152,7 +152,7 @@ public class MovementParkour extends Movement { return; } IBlockState toReplace = context.get(destX, y - 1, destZ); - if (!MovementHelper.isReplacable(destX, y - 1, destZ, toReplace, context.bsi)) { + if (!MovementHelper.isReplaceable(destX, y - 1, destZ, toReplace, context.bsi)) { return; } if (!checkOvershootSafety(context.bsi, destX + xDiff, y, destZ + zDiff)) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 4eab7144..c1f5ed01 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -111,7 +111,7 @@ public class MovementTraverse extends Movement { if (srcDown == Blocks.LADDER || srcDown == Blocks.VINE) { return COST_INF; } - if (MovementHelper.isReplacable(destX, y - 1, destZ, destOn, context.bsi)) { + if (MovementHelper.isReplaceable(destX, y - 1, destZ, destOn, context.bsi)) { boolean throughWater = MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock()); if (MovementHelper.isWater(destOn.getBlock()) && throughWater) { // this happens when assume walk on water is true and this is a traverse in water, which isn't allowed diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 6bea9a7c..4d3c2e5c 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -79,6 +79,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil private int ticks; private boolean paused; private int layer; + private List approxPlaceable; public BuilderProcess(Baritone baritone) { super(baritone); @@ -147,6 +148,11 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil build("clear area", new FillSchematic(widthX, heightY, lengthZ, Blocks.AIR.getDefaultState()), origin); } + @Override + public List getApproxPlaceable() { + return new ArrayList<>(approxPlaceable); + } + private static ISchematic parse(NBTTagCompound schematic) { return Baritone.settings().mapArtMode.value ? new MapArtSchematic(schematic) : new Schematic(schematic); } @@ -163,7 +169,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil if (!schematic.inSchematic(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current)) { return null; } - IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current); + IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current, this.approxPlaceable); if (state.getBlock() == Blocks.AIR) { return null; } @@ -214,7 +220,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } } - private Optional searchForPlacables(BuilderCalculationContext bcc, List desirableOnHotbar) { + private Optional searchForPlaceables(BuilderCalculationContext bcc, List desirableOnHotbar) { BetterBlockPos center = ctx.playerFeet(); for (int dx = -5; dx <= 5; dx++) { for (int dy = -5; dy <= 1; dy++) { @@ -227,7 +233,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil continue; // irrelevant } IBlockState curr = bcc.bsi.get0(x, y, z); - if (MovementHelper.isReplacable(x, y, z, curr, bcc.bsi) && !valid(curr, desired)) { + if (MovementHelper.isReplaceable(x, y, z, curr, bcc.bsi) && !valid(curr, desired)) { if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() == Blocks.AIR) { continue; } @@ -247,7 +253,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil for (EnumFacing against : EnumFacing.values()) { BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against); IBlockState placeAgainstState = bsi.get0(placeAgainstPos); - if (MovementHelper.isReplacable(placeAgainstPos.x, placeAgainstPos.y, placeAgainstPos.z, placeAgainstState, bsi)) { + if (MovementHelper.isReplaceable(placeAgainstPos.x, placeAgainstPos.y, placeAgainstPos.z, placeAgainstState, bsi)) { continue; } if (!ctx.world().mayPlace(toPlace.getBlock(), new BetterBlockPos(x, y, z), false, against, null)) { @@ -304,16 +310,16 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil private static Vec3d[] aabbSideMultipliers(EnumFacing side) { switch (side) { case UP: - return new Vec3d[] {new Vec3d(0.5, 1, 0.5), new Vec3d(0.1, 1, 0.5), new Vec3d(0.9, 1, 0.5), new Vec3d(0.5, 1, 0.1), new Vec3d(0.5, 1, 0.9)}; + return new Vec3d[]{new Vec3d(0.5, 1, 0.5), new Vec3d(0.1, 1, 0.5), new Vec3d(0.9, 1, 0.5), new Vec3d(0.5, 1, 0.1), new Vec3d(0.5, 1, 0.9)}; case DOWN: - return new Vec3d[] {new Vec3d(0.5, 0, 0.5), new Vec3d(0.1, 0, 0.5), new Vec3d(0.9, 0, 0.5), new Vec3d(0.5, 0, 0.1), new Vec3d(0.5, 0, 0.9)}; + return new Vec3d[]{new Vec3d(0.5, 0, 0.5), new Vec3d(0.1, 0, 0.5), new Vec3d(0.9, 0, 0.5), new Vec3d(0.5, 0, 0.1), new Vec3d(0.5, 0, 0.9)}; case NORTH: case SOUTH: case EAST: case WEST: double x = side.getXOffset() == 0 ? 0.5 : (1 + side.getXOffset()) / 2D; double z = side.getZOffset() == 0 ? 0.5 : (1 + side.getZOffset()) / 2D; - return new Vec3d[] {new Vec3d(x, 0.25, z), new Vec3d(x, 0.75, z)}; + return new Vec3d[]{new Vec3d(x, 0.25, z), new Vec3d(x, 0.75, z)}; default: // null throw new IllegalStateException(); } @@ -321,6 +327,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + approxPlaceable = approxPlaceable(36); if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) { ticks = 5; } else { @@ -348,8 +355,8 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } schematic = new ISchematic() { @Override - public IBlockState desiredState(int x, int y, int z, IBlockState current) { - return realSchematic.desiredState(x, y, z, current); + public IBlockState desiredState(int x, int y, int z, IBlockState current, List approxPlaceable) { + return realSchematic.desiredState(x, y, z, current, BuilderProcess.this.approxPlaceable); } @Override @@ -416,7 +423,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); } List desirableOnHotbar = new ArrayList<>(); - Optional toPlace = searchForPlacables(bcc, desirableOnHotbar); + Optional toPlace = searchForPlaceables(bcc, desirableOnHotbar); if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) { Rotation rot = toPlace.get().rot; baritone.getLookBehavior().updateTarget(rot, true); @@ -428,14 +435,13 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); } - List approxPlacable = placable(36); if (Baritone.settings().allowInventory.value) { ArrayList usefulSlots = new ArrayList<>(); List noValidHotbarOption = new ArrayList<>(); outer: for (IBlockState desired : desirableOnHotbar) { for (int i = 0; i < 9; i++) { - if (valid(approxPlacable.get(i), desired)) { + if (valid(approxPlaceable.get(i), desired)) { usefulSlots.add(i); continue outer; } @@ -446,7 +452,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil outer: for (int i = 9; i < 36; i++) { for (IBlockState desired : noValidHotbarOption) { - if (valid(approxPlacable.get(i), desired)) { + if (valid(approxPlaceable.get(i), desired)) { baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains); break outer; } @@ -454,9 +460,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } } - Goal goal = assemble(bcc, approxPlacable.subList(0, 9)); + Goal goal = assemble(bcc, approxPlaceable.subList(0, 9)); if (goal == null) { - goal = assemble(bcc, approxPlacable); // we're far away, so assume that we have our whole inventory to recalculate placable properly + goal = assemble(bcc, approxPlaceable); // we're far away, so assume that we have our whole inventory to recalculate placeable properly if (goal == null) { logDirect("Unable to do it. Pausing. resume to resume, cancel to cancel"); paused = true; @@ -528,7 +534,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } if (bcc.bsi.worldContainsLoadedChunk(blockX, blockZ)) { // check if its in render distance, not if its in cache // we can directly observe this block, it is in render distance - if (valid(bcc.bsi.get0(blockX, blockY, blockZ), schematic.desiredState(x, y, z, current))) { + if (valid(bcc.bsi.get0(blockX, blockY, blockZ), schematic.desiredState(x, y, z, current, this.approxPlaceable))) { observedCompleted.add(BetterBlockPos.longHash(blockX, blockY, blockZ)); } else { incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ)); @@ -553,14 +559,14 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } } - private Goal assemble(BuilderCalculationContext bcc, List approxPlacable) { + private Goal assemble(BuilderCalculationContext bcc, List approxPlaceable) { List placeable = new ArrayList<>(); List breakable = new ArrayList<>(); List sourceLiquids = new ArrayList<>(); incorrectPositions.forEach(pos -> { IBlockState state = bcc.bsi.get0(pos); if (state.getBlock() instanceof BlockAir) { - if (approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z, state))) { + if (approxPlaceable.contains(bcc.getSchematic(pos.x, pos.y, pos.z, state))) { placeable.add(pos); } } else { @@ -642,8 +648,8 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) { // TODO can this even happen? return new GoalPlace(pos); } - IBlockState current = ctx.world().getBlockState(pos.up()); - boolean allowSameLevel = current.getBlock() != Blocks.AIR; + boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR; + IBlockState current = ctx.world().getBlockState(pos); for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) { //noinspection ConstantConditions if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ(), current).getBlock(), pos, false, facing, null)) { @@ -727,7 +733,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil return paused ? "Builder Paused" : "Building " + name; } - private List placable(int size) { + private List approxPlaceable(int size) { List result = new ArrayList<>(); for (int i = 0; i < size; i++) { ItemStack stack = ctx.player().inventory.mainInventory.get(i); @@ -751,7 +757,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } public class BuilderCalculationContext extends CalculationContext { - private final List placable; + private final List placeable; private final ISchematic schematic; private final int originX; private final int originY; @@ -759,7 +765,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil public BuilderCalculationContext() { super(BuilderProcess.this.baritone, true); // wew lad - this.placable = placable(9); + this.placeable = approxPlaceable(9); this.schematic = BuilderProcess.this.schematic; this.originX = origin.getX(); this.originY = origin.getY(); @@ -771,7 +777,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil private IBlockState getSchematic(int x, int y, int z, IBlockState current) { if (schematic.inSchematic(x - originX, y - originY, z - originZ, current)) { - return schematic.desiredState(x - originX, y - originY, z - originZ, current); + return schematic.desiredState(x - originX, y - originY, z - originZ, current, BuilderProcess.this.approxPlaceable); } else { return null; } @@ -790,7 +796,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil // this won't be a schematic block, this will be a throwaway return placeBlockCost * 2; // we're going to have to break it eventually } - if (placable.contains(sch)) { + if (placeable.contains(sch)) { return 0; // thats right we gonna make it FREE to place a block where it should go in a structure // no place block penalty at all 😎 // i'm such an idiot that i just tried to copy and paste the epic gamer moment emoji too diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 4defff5d..3c0ef0a2 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -87,7 +87,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo .filter(this::followable) .filter(this.filter) .distinct() - .collect(Collectors.toCollection(ArrayList::new)); + .collect(Collectors.toList()); } @Override diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index b7eb2bb8..a741c6d6 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -320,6 +320,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(block)) { BetterBlockPos pf = ctx.baritone.getPlayerContext().playerFeet(); + // maxRegionDistanceSq 2 means adjacent directly or adjacent diagonally; nothing further than that locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf( BlockUtils.blockToString(block), Baritone.settings().maxCachedWorldScanCount.value, @@ -414,11 +415,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro @Override public void mineByName(int quantity, String... blocks) { - mine(quantity, new BlockOptionalMetaLookup( - Arrays.stream(Objects.requireNonNull(blocks)) - .map(BlockOptionalMeta::new) - .toArray(BlockOptionalMeta[]::new) - )); + mine(quantity, new BlockOptionalMetaLookup(blocks)); } @Override diff --git a/src/main/java/baritone/selection/SelectionRenderer.java b/src/main/java/baritone/selection/SelectionRenderer.java index a696fe67..435f7dc7 100644 --- a/src/main/java/baritone/selection/SelectionRenderer.java +++ b/src/main/java/baritone/selection/SelectionRenderer.java @@ -3,10 +3,12 @@ package baritone.selection; import baritone.api.event.events.RenderEvent; import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.selection.ISelection; -import baritone.api.utils.IRenderer; +import baritone.utils.IRenderer; import net.minecraft.util.math.AxisAlignedBB; public class SelectionRenderer implements IRenderer, AbstractGameEventListener { + public static final double SELECTION_BOX_EXPANSION = .005D; + private final SelectionManager manager; SelectionRenderer(SelectionManager manager) { @@ -26,7 +28,7 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener { IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth, ignoreDepth); for (ISelection selection : selections) { - IRenderer.drawAABB(selection.aabb(), .005f); + IRenderer.drawAABB(selection.aabb(), SELECTION_BOX_EXPANSION); } if (settings.renderSelectionCorners.value) { diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index 9f805387..48b80231 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -22,7 +22,6 @@ import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.IRenderer; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; diff --git a/src/api/java/baritone/api/utils/IRenderer.java b/src/main/java/baritone/utils/IRenderer.java similarity index 97% rename from src/api/java/baritone/api/utils/IRenderer.java rename to src/main/java/baritone/utils/IRenderer.java index 534c509e..f9315de6 100644 --- a/src/api/java/baritone/api/utils/IRenderer.java +++ b/src/main/java/baritone/utils/IRenderer.java @@ -15,11 +15,12 @@ * along with Baritone. If not, see . */ -package baritone.api.utils; +package baritone.utils; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; +import baritone.api.utils.Helper; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; @@ -110,7 +111,7 @@ public interface IRenderer { tessellator.draw(); } - static void drawAABB(AxisAlignedBB aabb, float expand) { + static void drawAABB(AxisAlignedBB aabb, double expand) { drawAABB(aabb.grow(expand, expand, expand)); } } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 3d141216..bfa0dc2d 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -29,7 +29,6 @@ import baritone.api.pathing.goals.GoalXZ; import baritone.api.pathing.goals.GoalYLevel; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Helper; -import baritone.api.utils.IRenderer; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.behavior.PathingBehavior; import baritone.pathing.path.PathExecutor; @@ -205,7 +204,7 @@ public final class PathRenderer implements IRenderer { toDraw = state.getSelectedBoundingBox(player.world, pos); } - IRenderer.drawAABB(toDraw, .002f); + IRenderer.drawAABB(toDraw, .002D); }); IRenderer.endLines(settings.renderSelectionBoxesIgnoreDepth.value); diff --git a/src/main/java/baritone/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java index 59f63867..794af0c5 100644 --- a/src/main/java/baritone/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -30,7 +30,7 @@ import static java.util.Arrays.asList; public class AxisCommand extends Command { public AxisCommand() { - super(asList("axis", "highway"), "Set a goal to the axes"); + super(asList("axis", "highway")); } @Override @@ -46,6 +46,11 @@ public class AxisCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Set a goal to the axes"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index bb19480f..1152ee08 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -30,7 +30,7 @@ import static java.util.Arrays.asList; public class BlacklistCommand extends Command { public BlacklistCommand() { - super("blacklist", "Blacklist closest block"); + super("blacklist"); } @Override @@ -54,6 +54,11 @@ public class BlacklistCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Blacklist closest block"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index 1c64f118..dd789ccb 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -37,7 +37,7 @@ public class BuildCommand extends Command { private static final File schematicsDir = new File(Minecraft.getMinecraft().gameDir, "schematics"); public BuildCommand() { - super("build", "Build a schematic"); + super("build"); } @Override @@ -81,6 +81,11 @@ public class BuildCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Build a schematic"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index a07bfc3b..49fdc537 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -28,7 +28,7 @@ import static java.util.Arrays.asList; public class CancelCommand extends Command { public CancelCommand() { - super(asList("cancel", "stop"), "Cancel what Baritone is currently doing"); + super(asList("cancel", "stop")); } @Override @@ -43,6 +43,11 @@ public class CancelCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Cancel what Baritone is currently doing"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index 6d4fac07..72e07da1 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -36,7 +36,7 @@ import static java.util.Arrays.asList; public class ChestsCommand extends Command { public ChestsCommand() { - super("chests", "Display remembered inventories"); + super("chests"); } @Override @@ -69,6 +69,11 @@ public class ChestsCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Display remembered inventories"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index 974a9867..68fc547e 100644 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -33,7 +33,7 @@ import static java.util.Arrays.asList; public class ClearareaCommand extends Command { public ClearareaCommand() { - super("cleararea", "Clear an area of all blocks"); + super("cleararea"); } @Override @@ -65,6 +65,11 @@ public class ClearareaCommand extends Command { return args.tabCompleteDatatype(RelativeBlockPos.class); } + @Override + public String getShortDesc() { + return "Clear an area of all blocks"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java index 559752bd..494ae8f7 100644 --- a/src/main/java/baritone/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -28,7 +28,7 @@ import static java.util.Arrays.asList; public class ClickCommand extends Command { public ClickCommand() { - super("click", "Open click"); + super("click"); } @Override @@ -43,6 +43,11 @@ public class ClickCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Open click"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index 0b5f40ce..cfbf1f46 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -33,7 +33,7 @@ import static java.util.Objects.isNull; public class ComeCommand extends Command { public ComeCommand() { - super("come", "Start heading towards your camera"); + super("come"); } @Override @@ -54,12 +54,17 @@ public class ComeCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Start heading towards your camera"; + } + @Override public List getLongDesc() { return asList( "The come command tells Baritone to head towards your camera.", "", - "I'm... not actually sure how useful this is, to be honest.", + "This can be useful in hacked clients where freecam doesn't move your player position.", "", "Usage:", "> come" diff --git a/src/main/java/baritone/utils/command/defaults/CommandAlias.java b/src/main/java/baritone/utils/command/defaults/CommandAlias.java index 0ffaf427..c407ca69 100644 --- a/src/main/java/baritone/utils/command/defaults/CommandAlias.java +++ b/src/main/java/baritone/utils/command/defaults/CommandAlias.java @@ -27,15 +27,18 @@ import java.util.List; import java.util.stream.Stream; public class CommandAlias extends Command { + private final String shortDesc; public final String target; public CommandAlias(List names, String shortDesc, String target) { - super(names, shortDesc); + super(names); + this.shortDesc = shortDesc; this.target = target; } public CommandAlias(String name, String shortDesc, String target) { - super(name, shortDesc); + super(name); + this.shortDesc = shortDesc; this.target = target; } @@ -49,6 +52,11 @@ public class CommandAlias extends Command { return CommandManager.tabComplete(String.format("%s %s", target, args.rawRest())); } + @Override + public String getShortDesc() { + return shortDesc; + } + @Override public List getLongDesc() { return Collections.singletonList(String.format("This command is an alias, for: %s ...", target)); diff --git a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java index a52d252a..213bd393 100644 --- a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java +++ b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.utils.command.Command; -import baritone.api.utils.command.manager.CommandManager; import java.util.Collections; import java.util.List; @@ -26,7 +25,7 @@ import java.util.List; import static java.util.Arrays.asList; public class DefaultCommands { - public static final List commands = Collections.unmodifiableList(asList( + public static final List COMMANDS = Collections.unmodifiableList(asList( new HelpCommand(), new SetCommand(), new CommandAlias(asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), diff --git a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java index 15951182..9298f32a 100644 --- a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java +++ b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java @@ -28,7 +28,7 @@ import static java.util.Arrays.asList; public class EmptyCommand extends Command { public EmptyCommand() { - super(asList("name1", "name2"), "Short description"); + super(asList("name1", "name2")); } @Override @@ -41,6 +41,11 @@ public class EmptyCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Short description"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index 24e02f26..c0925342 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -30,7 +30,7 @@ import static java.util.Arrays.asList; public class ExploreCommand extends Command { public ExploreCommand() { - super("explore", "Explore things"); + super("explore"); } @Override @@ -58,6 +58,11 @@ public class ExploreCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Explore things"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index 848e913b..9f637257 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -34,7 +34,7 @@ import static java.util.Arrays.asList; public class ExploreFilterCommand extends Command { public ExploreFilterCommand() { - super("explorefilter", "Explore chunks from a json"); + super("explorefilter"); } @Override @@ -73,6 +73,11 @@ public class ExploreFilterCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Explore chunks from a json"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java index 8c265912..4390585c 100644 --- a/src/main/java/baritone/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -28,7 +28,7 @@ import static java.util.Arrays.asList; public class FarmCommand extends Command { public FarmCommand() { - super("farm", "Farm nearby crops"); + super("farm"); } @Override @@ -43,6 +43,11 @@ public class FarmCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Farm nearby crops"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index 6fd620d1..4f71366a 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -32,7 +32,7 @@ import static java.util.Arrays.asList; public class FindCommand extends Command { public FindCommand() { - super("find", "Find positions of a certain block"); + super("find"); } @Override @@ -65,6 +65,11 @@ public class FindCommand extends Command { return args.tabCompleteDatatype(BlockById.class); } + @Override + public String getShortDesc() { + return "Find positions of a certain block"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index 0107ee3b..7588edd2 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -44,7 +44,7 @@ import static java.util.Objects.nonNull; public class FollowCommand extends Command { public FollowCommand() { - super("follow", "Follow entity things"); + super("follow"); } @Override @@ -131,6 +131,11 @@ public class FollowCommand extends Command { } } + @Override + public String getShortDesc() { + return "Follow entity things"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index 685db0c3..5bd7d58a 100644 --- a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -29,7 +29,7 @@ import static java.util.Arrays.asList; public class ForceCancelCommand extends Command { public ForceCancelCommand() { - super("forcecancel", "Force cancel"); + super("forcecancel"); } @Override @@ -46,6 +46,11 @@ public class ForceCancelCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Force cancel"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index 17e241cf..7e838c6f 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -28,7 +28,7 @@ import static java.util.Arrays.asList; public class GcCommand extends Command { public GcCommand() { - super("gc", "Call System.gc()"); + super("gc"); } @Override @@ -45,6 +45,11 @@ public class GcCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Call System.gc()"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index 883aed7e..55f09928 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -36,7 +36,7 @@ import static java.util.Objects.nonNull; public class GoalCommand extends Command { public GoalCommand() { - super("goal", "Set or clear the goal"); + super("goal"); } @Override @@ -86,6 +86,11 @@ public class GoalCommand extends Command { return helper.filterPrefix(args.getString()).stream(); } + @Override + public String getShortDesc() { + return "Set or clear the goal"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index 16bb128a..ccd7d640 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -24,12 +24,12 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.pagination.Paginator; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.manager.CommandManager; +import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.HoverEvent; -import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -41,7 +41,7 @@ import static java.util.Objects.isNull; public class HelpCommand extends Command { public HelpCommand() { - super(asList("help", "?"), "View all commands or help on specific ones"); + super(asList("help", "?")); } @Override @@ -53,40 +53,35 @@ public class HelpCommand extends Command { args, new Paginator<>( CommandManager.REGISTRY.descendingStream() .filter(command -> !command.hiddenFromHelp()) - .collect(Collectors.toCollection(ArrayList::new)) + .collect(Collectors.toList()) ), () -> logDirect("All Baritone commands (clickable):"), command -> { String names = String.join("/", command.names); String name = command.names.get(0); - return new TextComponentString(name) {{ - getStyle() - .setColor(TextFormatting.GRAY) - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("") {{ - getStyle().setColor(TextFormatting.GRAY); + ITextComponent shortDescComponent = new TextComponentString(" - " + command.getShortDesc()); + shortDescComponent.getStyle().setColor(TextFormatting.DARK_GRAY); - appendSibling(new TextComponentString(names + "\n") {{ - getStyle().setColor(TextFormatting.WHITE); - }}); + ITextComponent namesComponent = new TextComponentString(names); + namesComponent.getStyle().setColor(TextFormatting.WHITE); - appendText(command.shortDesc); - appendText("\n\nClick to view full help"); - }} - )) - .setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - FORCE_COMMAND_PREFIX + String.format("help %s", command.names.get(0)) - )); + ITextComponent hoverComponent = new TextComponentString(""); + hoverComponent.getStyle().setColor(TextFormatting.GRAY); + hoverComponent.appendSibling(namesComponent); + hoverComponent.appendText("\n" + command.getShortDesc()); + hoverComponent.appendText("\n\nClick to view full help"); + String clickCommand = FORCE_COMMAND_PREFIX + String.format("%s %s", label, command.names.get(0)); - appendSibling(new TextComponentString(" - " + command.shortDesc) {{ - getStyle().setColor(TextFormatting.DARK_GRAY); - }}); - }}; + ITextComponent component = new TextComponentString(name); + component.getStyle().setColor(TextFormatting.GRAY); + component.appendSibling(shortDescComponent); + component.getStyle() + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent)) + .setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, clickCommand)); + return component; }, - FORCE_COMMAND_PREFIX + "help" + FORCE_COMMAND_PREFIX + label ); } else { String commandName = args.getString().toLowerCase(); @@ -96,16 +91,18 @@ public class HelpCommand extends Command { throw new CommandNotFoundException(commandName); } - logDirect(String.format("%s - %s", String.join(" / ", command.names), command.shortDesc)); + logDirect(String.format("%s - %s", String.join(" / ", command.names), command.getShortDesc())); logDirect(""); command.getLongDesc().forEach(this::logDirect); logDirect(""); - logDirect(new TextComponentString("Click to return to the help menu") {{ - getStyle().setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - FORCE_COMMAND_PREFIX + "help" - )); - }}); + + ITextComponent returnComponent = new TextComponentString("Click to return to the help menu"); + returnComponent.getStyle().setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + FORCE_COMMAND_PREFIX + label + )); + + logDirect(returnComponent); } } @@ -118,6 +115,11 @@ public class HelpCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "View all commands or help on specific ones"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index a29f2c9b..1a46bdc7 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -33,7 +33,7 @@ import static java.util.Objects.isNull; public class InvertCommand extends Command { public InvertCommand() { - super("invert", "Run away from the current goal"); + super("invert"); } @Override @@ -62,6 +62,11 @@ public class InvertCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Run away from the current goal"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index ebfb7fe1..0f155e74 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -23,6 +23,7 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.BlockById; import baritone.api.utils.command.datatypes.ForBlockOptionalMeta; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.cache.WorldScanner; import java.util.ArrayList; import java.util.List; @@ -32,7 +33,7 @@ import static java.util.Arrays.asList; public class MineCommand extends Command { public MineCommand() { - super("mine", "Mine some blocks"); + super("mine"); } @Override @@ -45,6 +46,7 @@ public class MineCommand extends Command { boms.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); } + WorldScanner.INSTANCE.repack(ctx); baritone.getMineProcess().mine(quantity, boms.toArray(new BlockOptionalMeta[0])); logDirect(String.format("Mining %s", boms.toString())); } @@ -54,13 +56,24 @@ public class MineCommand extends Command { return args.tabCompleteDatatype(BlockById.class); } + @Override + public String getShortDesc() { + return "Mine some blocks"; + } + @Override public List getLongDesc() { return asList( + "The mine command allows you to tell Baritone to search for and mine individual blocks.", "", + "The specified blocks can be ores (which are commonly cached), or any other block.", + "", + "Also see the legitMine settings (see #set l legitMine).", "", "Usage:", - "> " + "> mine diamond_ore - Mines all diamonds it can find.", + "> mine redstone_ore lit_redstone_ore - Mines redstone ore.", + "> mine log:0 - Mines only oak logs." ); } } diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index d65819fa..b2c7e69f 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -26,6 +26,7 @@ import baritone.api.utils.command.datatypes.RelativeGoal; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import baritone.cache.WorldScanner; import java.util.List; import java.util.stream.Stream; @@ -35,7 +36,7 @@ import static java.util.Objects.isNull; public class PathCommand extends Command { public PathCommand() { - super("path", "Start heading towards a goal"); + super(asList("path", "goto")); } @Override @@ -51,6 +52,7 @@ public class PathCommand extends Command { } args.requireMax(0); + WorldScanner.INSTANCE.repack(ctx); customGoalProcess.setGoalAndPath(goal); logDirect("Now pathing"); } @@ -77,6 +79,11 @@ public class PathCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Start heading towards a goal"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index 2b3919e4..b8b3f91f 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -79,7 +79,7 @@ public class PauseResumeCommands { } ); - pauseCommand = new Command("pause", "Pauses Baritone until you use resume") { + pauseCommand = new Command("pause") { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); @@ -97,6 +97,11 @@ public class PauseResumeCommands { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Pauses Baritone until you use resume"; + } + @Override public List getLongDesc() { return asList( @@ -110,7 +115,7 @@ public class PauseResumeCommands { } }; - resumeCommand = new Command("resume", "Resumes Baritone after a pause") { + resumeCommand = new Command("resume") { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); @@ -128,6 +133,11 @@ public class PauseResumeCommands { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Resumes Baritone after a pause"; + } + @Override public List getLongDesc() { return asList( @@ -139,7 +149,7 @@ public class PauseResumeCommands { } }; - pausedCommand = new Command("paused", "Tells you if Baritone is paused") { + pausedCommand = new Command("paused") { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); @@ -152,6 +162,11 @@ public class PauseResumeCommands { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Tells you if Baritone is paused"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index 469089f6..a0ada87f 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -33,7 +33,7 @@ import static java.util.Objects.isNull; public class ProcCommand extends Command { public ProcCommand() { - super("proc", "View process state information"); + super("proc"); } @Override @@ -69,6 +69,11 @@ public class ProcCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "View process state information"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index 73a0245d..a7904bda 100644 --- a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -28,7 +28,7 @@ import static java.util.Arrays.asList; public class ReloadAllCommand extends Command { public ReloadAllCommand() { - super("reloadall", "Reloads Baritone's cache for this world"); + super("reloadall"); } @Override @@ -43,6 +43,11 @@ public class ReloadAllCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Reloads Baritone's cache for this world"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index 3fa07ca3..90a260a5 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -29,7 +29,7 @@ import static java.util.Arrays.asList; public class RenderCommand extends Command { public RenderCommand() { - super("render", "Fix glitched chunks"); + super("render"); } @Override @@ -55,6 +55,11 @@ public class RenderCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Fix glitched chunks"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java index 0cf2ae78..357197ee 100644 --- a/src/main/java/baritone/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -18,47 +18,24 @@ package baritone.utils.command.defaults; import baritone.api.Settings; -import baritone.api.cache.ICachedWorld; -import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.IChunkProvider; +import baritone.cache.WorldScanner; import java.util.List; import java.util.stream.Stream; import static java.util.Arrays.asList; -import static java.util.Objects.nonNull; public class RepackCommand extends Command { public RepackCommand() { - super(asList("repack", "rescan"), "Re-cache chunks"); + super(asList("repack", "rescan")); } @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - - 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 queued = 0; - for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) { - for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) { - Chunk chunk = chunkProvider.getLoadedChunk(x, z); - - if (nonNull(chunk) && !chunk.isEmpty()) { - queued++; - cachedWorld.queueForPacking(chunk); - } - } - } - - logDirect(String.format("Queued %d chunks for repacking", queued)); + logDirect(String.format("Queued %d chunks for repacking", WorldScanner.INSTANCE.repack(ctx))); } @Override @@ -66,6 +43,11 @@ public class RepackCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Re-cache chunks"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index a34a6a58..953e7527 100644 --- a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -28,7 +28,7 @@ import static java.util.Arrays.asList; public class SaveAllCommand extends Command { public SaveAllCommand() { - super("saveall", "Saves Baritone's cache for this world"); + super("saveall"); } @Override @@ -43,6 +43,11 @@ public class SaveAllCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Saves Baritone's cache for this world"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index edef29a7..be455bc2 100644 --- a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -28,7 +28,7 @@ import static java.util.Arrays.asList; public class SchematicaCommand extends Command { public SchematicaCommand() { - super("schematica", "Opens a Schematica schematic?"); + super("schematica"); } @Override @@ -42,10 +42,15 @@ public class SchematicaCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Builds the loaded schematic"; + } + @Override public List getLongDesc() { return asList( - "I'm not actually sure what this does.", + "Builds the schematica currently open in Schematica.", "", "Usage:", "> schematica" diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index c6529d3d..f04e0970 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -20,7 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.event.events.RenderEvent; import baritone.api.schematic.CompositeSchematic; -import baritone.api.schematic.FillBomSchematic; +import baritone.api.schematic.FillSchematic; import baritone.api.schematic.ReplaceSchematic; import baritone.api.schematic.ShellSchematic; import baritone.api.schematic.WallsSchematic; @@ -29,7 +29,6 @@ import baritone.api.selection.ISelectionManager; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.BlockOptionalMetaLookup; -import baritone.api.utils.IRenderer; import baritone.api.utils.ISchematic; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.ForBlockOptionalMeta; @@ -39,6 +38,7 @@ import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import baritone.utils.IRenderer; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; @@ -59,7 +59,7 @@ public class SelCommand extends Command { private BetterBlockPos pos1 = null; public SelCommand() { - super(asList("sel", "selection", "s"), "WorldEdit-like commands"); + super(asList("sel", "selection", "s")); } @Override @@ -118,10 +118,13 @@ public class SelCommand extends Command { List replacesList = new ArrayList<>(); - while (args.has()) { + replacesList.add(type); + + while (args.has(2)) { replacesList.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); } + type = args.getDatatypeFor(ForBlockOptionalMeta.class); replaces = new BlockOptionalMetaLookup(replacesList.toArray(new BlockOptionalMeta[0])); } else { args.requireMax(0); @@ -149,7 +152,7 @@ public class SelCommand extends Command { Vec3i size = selection.size(); BetterBlockPos min = selection.min(); - ISchematic schematic = new FillBomSchematic(baritone, size.getX(), size.getY(), size.getZ(), type); + ISchematic schematic = new FillSchematic(baritone, size.getX(), size.getY(), size.getZ(), type); if (action == Action.WALLS) { schematic = new WallsSchematic(baritone, schematic); @@ -242,6 +245,11 @@ public class SelCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "WorldEdit-like commands"; + } + @Override public List getLongDesc() { return asList( @@ -263,7 +271,7 @@ public class SelCommand extends Command { "> 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 cleararea/ca - Basically 'set air'.", - "> sel replace/r - Replaces, with 'place', all blocks listed after it.", + "> sel replace/r - Replaces blocks with another block.", "", "> sel expand - Expand the targets.", "> sel contract - Contract the targets.", diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index 3bf6267e..4588c450 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -24,18 +24,17 @@ import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.pagination.Paginator; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.HoverEvent; -import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; import java.util.stream.Stream; -import static baritone.api.utils.SettingsUtil.settingDefaultToString; import static baritone.api.utils.SettingsUtil.settingTypeToString; import static baritone.api.utils.SettingsUtil.settingValueToString; import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; @@ -46,7 +45,7 @@ import static java.util.stream.Stream.of; public class SetCommand extends Command { public SetCommand() { - super(asList("set", "setting", "settings"), "View or change settings"); + super(asList("set", "setting", "settings")); } @Override @@ -71,7 +70,7 @@ public class SetCommand extends Command { .filter(s -> !s.getName().equals("logger")) .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.toCollection(ArrayList::new)); + .collect(Collectors.toList()); Paginator.paginate( args, @@ -81,31 +80,29 @@ public class SetCommand extends Command { ? String.format("All %ssettings containing the string '%s':", viewModified ? "modified " : "", search) : String.format("All %ssettings:", viewModified ? "modified " : "") ), - setting -> new TextComponentString(setting.getName()) {{ - getStyle() - .setColor(TextFormatting.GRAY) - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("") {{ - getStyle().setColor(TextFormatting.GRAY); - appendText(setting.getName()); - appendText(String.format("\nType: %s", settingTypeToString(setting))); - appendText(String.format("\n\nValue:\n%s", settingValueToString(setting))); + setting -> { + ITextComponent typeComponent = new TextComponentString(String.format( + " (%s)", + settingTypeToString(setting) + )); + typeComponent.getStyle().setColor(TextFormatting.DARK_GRAY); - if (setting.value != setting.defaultValue) { - appendText(String.format("\n\nDefault:\n%s", settingDefaultToString(setting))); - } - }} - )) - .setClickEvent(new ClickEvent( - ClickEvent.Action.SUGGEST_COMMAND, - settings.prefix.value + String.format("set %s ", setting.getName()) - )); + ITextComponent hoverComponent = new TextComponentString(""); + hoverComponent.getStyle().setColor(TextFormatting.GRAY); + hoverComponent.appendText(setting.getName()); + hoverComponent.appendText(String.format("\nType: %s", settingTypeToString(setting))); + hoverComponent.appendText(String.format("\n\nValue:\n%s", settingValueToString(setting))); + String commandSuggestion = settings.prefix.value + String.format("set %s ", setting.getName()); - appendSibling(new TextComponentString(String.format(" (%s)", settingTypeToString(setting))) {{ - getStyle().setColor(TextFormatting.DARK_GRAY); - }}); - }}, + ITextComponent component = new TextComponentString(setting.getName()); + component.getStyle().setColor(TextFormatting.GRAY); + component.appendSibling(typeComponent); + component.getStyle() + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent)) + .setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, commandSuggestion)); + + return component; + }, FORCE_COMMAND_PREFIX + "set " + arg + " " + search ); @@ -187,18 +184,19 @@ public class SetCommand extends Command { )); } - logDirect(new TextComponentString(String.format("Old value: %s", oldValue)) {{ - getStyle() - .setColor(TextFormatting.GRAY) - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("Click to set the setting back to this value") - )) - .setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue) - )); - }}); + ITextComponent oldValueComponent = new TextComponentString(String.format("Old value: %s", oldValue)); + oldValueComponent.getStyle() + .setColor(TextFormatting.GRAY) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to set the setting back to this value") + )) + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue) + )); + + logDirect(oldValueComponent); if ((setting.getName().equals("chatControl") && !(Boolean) setting.value && !settings.chatControlAnyway.value) || setting.getName().equals("chatControlAnyway") && !(Boolean) setting.value && !settings.chatControl.value) { @@ -260,6 +258,11 @@ public class SetCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "View or change settings"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index d16dbd94..2f83cb0c 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -29,7 +29,7 @@ import static java.util.Arrays.asList; public class ThisWayCommand extends Command { public ThisWayCommand() { - super(asList("thisway", "forward"), "Travel in your current direction"); + super(asList("thisway", "forward")); } @Override @@ -51,6 +51,11 @@ public class ThisWayCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Travel in your current direction"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index 00d9e67c..8d59fba6 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -30,7 +30,7 @@ import static java.util.Arrays.asList; public class TunnelCommand extends Command { public TunnelCommand() { - super("tunnel", "Set a goal to tunnel in your current direction"); + super("tunnel"); } @Override @@ -51,6 +51,11 @@ public class TunnelCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Set a goal to tunnel in your current direction"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index 6cd06f9c..71b30c19 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -30,7 +30,7 @@ import static java.util.Objects.isNull; public class VersionCommand extends Command { public VersionCommand() { - super("version", "View the Baritone version"); + super("version"); } @Override @@ -51,6 +51,11 @@ public class VersionCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "View the Baritone version"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 894b23a0..7069e02f 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -50,7 +50,7 @@ import static java.util.Arrays.asList; public class WaypointsCommand extends Command { public WaypointsCommand() { - super(asList("waypoints", "waypoint", "wp"), "Manage waypoints"); + super(asList("waypoints", "waypoint", "wp")); } @Override @@ -87,7 +87,7 @@ public class WaypointsCommand extends Command { FORCE_COMMAND_PREFIX, label, _action.names[0], - waypoint.getTag().names[0], + waypoint.getTag().getName(), waypoint.getCreationTimestamp() )) ); @@ -99,7 +99,7 @@ public class WaypointsCommand extends Command { toComponent.apply(waypoint, action == Action.LIST ? Action.INFO : action); if (action == Action.LIST) { - IWaypoint.Tag tag = args.has() ? ForWaypoints.getTagByName(args.peekString()) : null; + IWaypoint.Tag tag = args.has() ? IWaypoint.Tag.getByName(args.peekString()) : null; if (tag != null) { args.get(); @@ -125,7 +125,7 @@ public class WaypointsCommand extends Command { FORCE_COMMAND_PREFIX, label, action.names[0], - tag != null ? " " + tag.names[0] : "" + tag != null ? " " + tag.getName() : "" ) ); } else { @@ -137,7 +137,7 @@ public class WaypointsCommand extends Command { ); } } else if (action == Action.SAVE) { - IWaypoint.Tag tag = ForWaypoints.getTagByName(args.getString()); + IWaypoint.Tag tag = IWaypoint.Tag.getByName(args.getString()); if (tag == null) { throw new CommandInvalidStateException(String.format("'%s' is not a tag ", args.consumedString())); @@ -159,7 +159,7 @@ public class WaypointsCommand extends Command { logDirect(component); } else if (action == Action.CLEAR) { args.requireMax(1); - IWaypoint.Tag tag = ForWaypoints.getTagByName(args.getString()); + IWaypoint.Tag tag = IWaypoint.Tag.getByName(args.getString()); IWaypoint[] waypoints = ForWaypoints.getWaypointsByTag(tag); for (IWaypoint waypoint : waypoints) { @@ -221,7 +221,7 @@ public class WaypointsCommand extends Command { "%s%s delete %s @ %d", FORCE_COMMAND_PREFIX, label, - waypoint.getTag().names[0], + waypoint.getTag().getName(), waypoint.getCreationTimestamp() ) )); @@ -232,7 +232,7 @@ public class WaypointsCommand extends Command { "%s%s goal %s @ %d", FORCE_COMMAND_PREFIX, label, - waypoint.getTag().names[0], + waypoint.getTag().getName(), waypoint.getCreationTimestamp() ) )); @@ -275,7 +275,7 @@ public class WaypointsCommand extends Command { if (args.hasExactlyOne()) { if (action == Action.LIST || action == Action.SAVE || action == Action.CLEAR) { return new TabCompleteHelper() - .append(ForWaypoints.getTagNames()) + .append(IWaypoint.Tag.getAllNames()) .sortAlphabetically() .filterPrefix(args.getString()) .stream(); @@ -293,6 +293,11 @@ public class WaypointsCommand extends Command { return Stream.empty(); } + @Override + public String getShortDesc() { + return "Manage waypoints"; + } + @Override public List getLongDesc() { return asList( diff --git a/src/main/java/baritone/utils/schematic/FillSchematic.java b/src/main/java/baritone/utils/schematic/FillSchematic.java index 6bac6ce6..86fc7bae 100644 --- a/src/main/java/baritone/utils/schematic/FillSchematic.java +++ b/src/main/java/baritone/utils/schematic/FillSchematic.java @@ -19,7 +19,8 @@ package baritone.utils.schematic; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; -import net.minecraft.init.Blocks; + +import java.util.List; public class FillSchematic implements ISchematic { private final int widthX; @@ -35,7 +36,7 @@ public class FillSchematic implements ISchematic { } @Override - public IBlockState desiredState(int x, int y, int z, IBlockState current) { + public IBlockState desiredState(int x, int y, int z, IBlockState current, List approxPlaceable) { return state; } diff --git a/src/main/java/baritone/utils/schematic/Schematic.java b/src/main/java/baritone/utils/schematic/Schematic.java index 3efb2404..93e78120 100644 --- a/src/main/java/baritone/utils/schematic/Schematic.java +++ b/src/main/java/baritone/utils/schematic/Schematic.java @@ -22,6 +22,8 @@ import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; +import java.util.List; + public class Schematic implements ISchematic { public final int widthX; public final int heightY; @@ -68,7 +70,7 @@ public class Schematic implements ISchematic { } @Override - public IBlockState desiredState(int x, int y, int z, IBlockState current) { + public IBlockState desiredState(int x, int y, int z, IBlockState current, List approxPlaceable) { return states[x][z][y]; } diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java index 3ba9c314..548e3e37 100644 --- a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java @@ -23,6 +23,8 @@ import com.github.lunatrius.schematica.client.world.SchematicWorld; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; +import java.util.List; + public final class SchematicAdapter implements ISchematic { private final SchematicWorld schematic; @@ -31,7 +33,7 @@ public final class SchematicAdapter implements ISchematic { } @Override - public IBlockState desiredState(int x, int y, int z, IBlockState current) { + public IBlockState desiredState(int x, int y, int z, IBlockState current, List approxPlaceable) { return schematic.getSchematic().getBlockState(new BlockPos(x, y, z)); } From aefc82e47ce0fd559c6e7de9780e95ab8f484563 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 6 Sep 2019 17:22:55 -0700 Subject: [PATCH 623/682] Review 2 --- .../api/schematic/AbstractSchematic.java | 20 +- .../api/schematic/CompositeSchematic.java | 5 +- .../baritone/api/schematic/FillSchematic.java | 5 +- .../baritone/api/schematic/MaskSchematic.java | 7 +- .../api/schematic/ReplaceSchematic.java | 14 +- .../api/schematic/ShellSchematic.java | 6 +- .../api/schematic/WallsSchematic.java | 6 +- .../command/argparser/ArgParserManager.java | 2 +- .../command/argparser/DefaultArgParsers.java | 2 +- .../command/argument/CommandArgument.java | 14 +- .../utils/command/datatypes/ForWaypoints.java | 14 +- .../command/datatypes/PlayerByUsername.java | 14 +- .../helpers/arguments/ArgConsumer.java | 256 ------------------ .../java/baritone/utils/PathRenderer.java | 7 +- .../utils/command/defaults/SelCommand.java | 10 +- 15 files changed, 44 insertions(+), 338 deletions(-) diff --git a/src/api/java/baritone/api/schematic/AbstractSchematic.java b/src/api/java/baritone/api/schematic/AbstractSchematic.java index 27bf6936..c1cb6bde 100644 --- a/src/api/java/baritone/api/schematic/AbstractSchematic.java +++ b/src/api/java/baritone/api/schematic/AbstractSchematic.java @@ -17,32 +17,14 @@ package baritone.api.schematic; -import baritone.api.IBaritone; -import baritone.api.utils.IPlayerContext; import baritone.api.utils.ISchematic; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.init.Blocks; -import net.minecraft.item.Item; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.NonNullList; - -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.List; public abstract class AbstractSchematic implements ISchematic { - protected final IBaritone baritone; - protected final IPlayerContext ctx; protected int x; protected int y; protected int z; - public AbstractSchematic(IBaritone baritone, int x, int y, int z) { - this.baritone = baritone; - this.ctx = baritone == null ? null : baritone.getPlayerContext(); + public AbstractSchematic(int x, int y, int z) { this.x = x; this.y = y; this.z = z; diff --git a/src/api/java/baritone/api/schematic/CompositeSchematic.java b/src/api/java/baritone/api/schematic/CompositeSchematic.java index d278fa4c..ecb0dd70 100644 --- a/src/api/java/baritone/api/schematic/CompositeSchematic.java +++ b/src/api/java/baritone/api/schematic/CompositeSchematic.java @@ -17,7 +17,6 @@ package baritone.api.schematic; -import baritone.api.IBaritone; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; @@ -38,8 +37,8 @@ public class CompositeSchematic extends AbstractSchematic { } } - public CompositeSchematic(IBaritone baritone, int x, int y, int z) { - super(baritone, x, y, z); + public CompositeSchematic(int x, int y, int z) { + super(x, y, z); schematics = new ArrayList<>(); recalcArr(); } diff --git a/src/api/java/baritone/api/schematic/FillSchematic.java b/src/api/java/baritone/api/schematic/FillSchematic.java index 8a55376f..20b1c250 100644 --- a/src/api/java/baritone/api/schematic/FillSchematic.java +++ b/src/api/java/baritone/api/schematic/FillSchematic.java @@ -17,7 +17,6 @@ package baritone.api.schematic; -import baritone.api.IBaritone; import baritone.api.utils.BlockOptionalMeta; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -27,8 +26,8 @@ import java.util.List; public class FillSchematic extends AbstractSchematic { private final BlockOptionalMeta bom; - public FillSchematic(IBaritone baritone, int x, int y, int z, BlockOptionalMeta bom) { - super(baritone, x, y, z); + public FillSchematic(int x, int y, int z, BlockOptionalMeta bom) { + super(x, y, z); this.bom = bom; } diff --git a/src/api/java/baritone/api/schematic/MaskSchematic.java b/src/api/java/baritone/api/schematic/MaskSchematic.java index 63a4f86f..a0589cee 100644 --- a/src/api/java/baritone/api/schematic/MaskSchematic.java +++ b/src/api/java/baritone/api/schematic/MaskSchematic.java @@ -17,7 +17,6 @@ package baritone.api.schematic; -import baritone.api.IBaritone; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; @@ -26,8 +25,8 @@ import java.util.List; public abstract class MaskSchematic extends AbstractSchematic { private final ISchematic schematic; - public MaskSchematic(IBaritone baritone, ISchematic schematic) { - super(baritone, schematic.widthX(), schematic.heightY(), schematic.lengthZ()); + public MaskSchematic(ISchematic schematic) { + super(schematic.widthX(), schematic.heightY(), schematic.lengthZ()); this.schematic = schematic; } @@ -35,7 +34,7 @@ public abstract class MaskSchematic extends AbstractSchematic { @Override public boolean inSchematic(int x, int y, int z, IBlockState currentState) { - return schematic.inSchematic(x, y, z, currentState) && partOfMask(x, y, z, currentState); + return partOfMask(x, y, z, currentState) && schematic.inSchematic(x, y, z, currentState); } @Override diff --git a/src/api/java/baritone/api/schematic/ReplaceSchematic.java b/src/api/java/baritone/api/schematic/ReplaceSchematic.java index b74c564f..ca2577c8 100644 --- a/src/api/java/baritone/api/schematic/ReplaceSchematic.java +++ b/src/api/java/baritone/api/schematic/ReplaceSchematic.java @@ -17,7 +17,6 @@ package baritone.api.schematic; -import baritone.api.IBaritone; import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; @@ -26,15 +25,18 @@ public class ReplaceSchematic extends MaskSchematic { private final BlockOptionalMetaLookup filter; private final Boolean[][][] cache; - public ReplaceSchematic(IBaritone baritone, ISchematic schematic, BlockOptionalMetaLookup filter) { - super(baritone, schematic); + public ReplaceSchematic(ISchematic schematic, BlockOptionalMetaLookup filter) { + super(schematic); this.filter = filter; this.cache = new Boolean[widthX()][heightY()][lengthZ()]; } + @Override protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { - return cache[x][y][z] == null - ? cache[x][y][z] = filter.has(currentState) - : cache[x][y][z]; + if (cache[x][y][z] == null) { + cache[x][y][z] = filter.has(currentState); + } + + return cache[x][y][z]; } } diff --git a/src/api/java/baritone/api/schematic/ShellSchematic.java b/src/api/java/baritone/api/schematic/ShellSchematic.java index aa249ea0..d6a734be 100644 --- a/src/api/java/baritone/api/schematic/ShellSchematic.java +++ b/src/api/java/baritone/api/schematic/ShellSchematic.java @@ -17,15 +17,15 @@ package baritone.api.schematic; -import baritone.api.IBaritone; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; public class ShellSchematic extends MaskSchematic { - public ShellSchematic(IBaritone baritone, ISchematic schematic) { - super(baritone, schematic); + public ShellSchematic(ISchematic schematic) { + super(schematic); } + @Override protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { return x == 0 || y == 0 || z == 0 || x == widthX() - 1 || y == heightY() - 1 || z == lengthZ() - 1; } diff --git a/src/api/java/baritone/api/schematic/WallsSchematic.java b/src/api/java/baritone/api/schematic/WallsSchematic.java index bc632564..388fdb4d 100644 --- a/src/api/java/baritone/api/schematic/WallsSchematic.java +++ b/src/api/java/baritone/api/schematic/WallsSchematic.java @@ -17,15 +17,15 @@ package baritone.api.schematic; -import baritone.api.IBaritone; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; public class WallsSchematic extends MaskSchematic { - public WallsSchematic(IBaritone baritone, ISchematic schematic) { - super(baritone, schematic); + public WallsSchematic(ISchematic schematic) { + super(schematic); } + @Override protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { return x == 0 || z == 0 || x == widthX() - 1 || z == lengthZ() - 1; } diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index 619fa67a..c96418a4 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -28,7 +28,7 @@ public class ArgParserManager { public static final Registry REGISTRY = new Registry<>(); static { - DefaultArgParsers.all.forEach(REGISTRY::register); + DefaultArgParsers.ALL.forEach(REGISTRY::register); } /** diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index fe964bce..2f51bbad 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -113,7 +113,7 @@ public class DefaultArgParsers { } } - public static final List> all = asList( + public static final List> ALL = asList( IntArgumentParser.INSTANCE, LongArgumentParser.INSTANCE, FloatArgumentParser.INSTANCE, diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index 5d297528..e793b8b5 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -28,7 +28,6 @@ import net.minecraft.util.EnumFacing; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -67,15 +66,10 @@ public class CommandArgument { * @see ArgConsumer#getEnumOrNull(Class) */ public > E getEnum(Class enumClass) { - try { - //noinspection OptionalGetWithoutIsPresent - return Arrays.stream(enumClass.getEnumConstants()) - .filter(e -> e.name().equalsIgnoreCase(value)) - .findFirst() - .get(); - } catch (NoSuchElementException e) { - throw new CommandInvalidTypeException(this, enumClass.getSimpleName()); - } + return Arrays.stream(enumClass.getEnumConstants()) + .filter(e -> e.name().equalsIgnoreCase(value)) + .findFirst() + .orElseThrow(() -> new CommandInvalidTypeException(this, enumClass.getSimpleName())); } /** diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java index 47b63480..3cb27a50 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -25,8 +25,6 @@ import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import java.util.Arrays; import java.util.Comparator; -import java.util.HashSet; -import java.util.Set; import java.util.stream.Stream; public class ForWaypoints implements IDatatypeFor { @@ -88,14 +86,8 @@ public class ForWaypoints implements IDatatypeFor { } public static IWaypoint[] getWaypointsByName(String name) { - Set found = new HashSet<>(); - - for (IWaypoint waypoint : getWaypoints()) { - if (waypoint.getName().equalsIgnoreCase(name)) { - found.add(waypoint); - } - } - - return found.toArray(new IWaypoint[0]); + return Arrays.stream(getWaypoints()) + .filter(waypoint -> waypoint.getName().equalsIgnoreCase(name)) + .toArray(IWaypoint[]::new); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java index a3c54b48..6ef22b93 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java +++ b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java @@ -39,13 +39,13 @@ public class PlayerByUsername implements IDatatypeFor { public PlayerByUsername(ArgConsumer consumer) { String username = consumer.getString(); - if (isNull( - player = players - .stream() - .filter(s -> s.getName().equalsIgnoreCase(username)) - .findFirst() - .orElse(null) - )) { + player = players + .stream() + .filter(s -> s.getName().equalsIgnoreCase(username)) + .findFirst() + .orElse(null); + + if (isNull(player)) { throw new IllegalArgumentException("no player found by that username"); } } diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index c68b77c2..75cf5962 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -420,22 +420,6 @@ public class ArgConsumer implements Cloneable { * @param datatype The datatype to get * @return The datatype instance * @see IDatatype - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) */ public T peekDatatype(Class datatype) { return clone().getDatatype(datatype); @@ -453,22 +437,6 @@ public class ArgConsumer implements Cloneable { * @param datatype The datatype to get * @return The datatype instance, or {@code null} if it throws an exception * @see IDatatype - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) */ public T peekDatatypeOrNull(Class datatype) { return clone().getDatatypeOrNull(datatype); @@ -487,22 +455,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance * @see IDatatype * @see IDatatypePost - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) */ public > T peekDatatypePost(Class datatype, O original) { return clone().getDatatypePost(datatype, original); @@ -522,22 +474,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance, or {@code def} if it throws an exception * @see IDatatype * @see IDatatypePost - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) */ public > T peekDatatypePostOrDefault(Class datatype, O original, T def) { return clone().getDatatypePostOrDefault(datatype, original, def); @@ -556,22 +492,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance, or {@code null} if it throws an exception * @see IDatatype * @see IDatatypePost - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) */ public > T peekDatatypePostOrNull(Class datatype, O original) { return peekDatatypePostOrDefault(datatype, original, null); @@ -590,22 +510,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance * @see IDatatype * @see IDatatypeFor - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) */ public > T peekDatatypeFor(Class datatype) { return clone().peekDatatypeFor(datatype); @@ -625,22 +529,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance, or {@code def} if it throws an exception * @see IDatatype * @see IDatatypeFor - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) */ public > T peekDatatypeForOrDefault(Class datatype, T def) { return clone().peekDatatypeForOrDefault(datatype, def); @@ -659,22 +547,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance, or {@code null} if it throws an exception * @see IDatatype * @see IDatatypeFor - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) */ public > T peekDatatypeForOrNull(Class datatype) { return peekDatatypeForOrDefault(datatype, null); @@ -849,22 +721,6 @@ public class ArgConsumer implements Cloneable { * @param datatype The datatype to get * @return The datatype instance * @see IDatatype - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) */ public T getDatatype(Class datatype) { try { @@ -888,22 +744,6 @@ public class ArgConsumer implements Cloneable { * @param datatype The datatype to get * @return The datatype instance, or {@code null} if it throws an exception * @see IDatatype - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) */ public T getDatatypeOrNull(Class datatype) { List argsSnapshot = new ArrayList<>(args); @@ -932,22 +772,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance * @see IDatatype * @see IDatatypePost - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) */ public > T getDatatypePost(Class datatype, O original) { return getDatatype(datatype).apply(original); @@ -967,22 +791,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance, or {@code def} if it throws an exception * @see IDatatype * @see IDatatypePost - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) */ public > T getDatatypePostOrDefault(Class datatype, O original, T def) { List argsSnapshot = new ArrayList<>(args); @@ -1013,22 +821,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance, or {@code null} if it throws an exception * @see IDatatype * @see IDatatypePost - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) */ public > T getDatatypePostOrNull(Class datatype, O original) { return getDatatypePostOrDefault(datatype, original, null); @@ -1045,22 +837,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance * @see IDatatype * @see IDatatypeFor - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) */ public > T getDatatypeFor(Class datatype) { return getDatatype(datatype).get(); @@ -1080,22 +856,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance, or {@code def} if it throws an exception * @see IDatatype * @see IDatatypeFor - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) */ public > T getDatatypeForOrDefault(Class datatype, T def) { List argsSnapshot = new ArrayList<>(args); @@ -1126,22 +886,6 @@ public class ArgConsumer implements Cloneable { * @return The datatype instance, or {@code null} if it throws an exception * @see IDatatype * @see IDatatypeFor - * @see #getDatatype(Class) - * @see #getDatatypeOrNull(Class) - * @see #getDatatypePost(Class, Object) - * @see #getDatatypePostOrDefault(Class, Object, Object) - * @see #getDatatypePostOrNull(Class, Object) - * @see #getDatatypeFor(Class) - * @see #getDatatypeForOrDefault(Class, Object) - * @see #getDatatypeForOrNull(Class) - * @see #peekDatatype(Class) - * @see #peekDatatypeOrNull(Class) - * @see #peekDatatypePost(Class, Object) - * @see #peekDatatypePostOrDefault(Class, Object, Object) - * @see #peekDatatypePostOrNull(Class, Object) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypeForOrDefault(Class, Object) - * @see #peekDatatypeForOrNull(Class) */ public > T getDatatypeForOrNull(Class datatype) { return getDatatypeForOrDefault(datatype, null); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index bfa0dc2d..b64995c2 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -47,12 +47,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import static org.lwjgl.opengl.GL11.GL_LIGHTING_BIT; -import static org.lwjgl.opengl.GL11.GL_LINES; -import static org.lwjgl.opengl.GL11.GL_LINE_LOOP; -import static org.lwjgl.opengl.GL11.GL_LINE_STRIP; -import static org.lwjgl.opengl.GL11.glPopAttrib; -import static org.lwjgl.opengl.GL11.glPushAttrib; +import static org.lwjgl.opengl.GL11.*; /** * @author Brady diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index f04e0970..fcaae5ed 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -137,7 +137,7 @@ public class SelCommand extends Command { } BetterBlockPos origin = selections[0].min(); - CompositeSchematic composite = new CompositeSchematic(baritone, 0, 0, 0); + CompositeSchematic composite = new CompositeSchematic(0, 0, 0); for (ISelection selection : selections) { BetterBlockPos min = selection.min(); @@ -152,14 +152,14 @@ public class SelCommand extends Command { Vec3i size = selection.size(); BetterBlockPos min = selection.min(); - ISchematic schematic = new FillSchematic(baritone, size.getX(), size.getY(), size.getZ(), type); + ISchematic schematic = new FillSchematic(size.getX(), size.getY(), size.getZ(), type); if (action == Action.WALLS) { - schematic = new WallsSchematic(baritone, schematic); + schematic = new WallsSchematic(schematic); } else if (action == Action.SHELL) { - schematic = new ShellSchematic(baritone, schematic); + schematic = new ShellSchematic(schematic); } else if (action == Action.REPLACE) { - schematic = new ReplaceSchematic(baritone, schematic, replaces); + schematic = new ReplaceSchematic(schematic, replaces); } composite.put(schematic, min.x - origin.x, min.y - origin.y, min.z - origin.z); From 9db07faf49b41317480ff1d6f3718b7075a30b49 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 6 Sep 2019 17:31:41 -0700 Subject: [PATCH 624/682] import * --- .../api/utils/command/datatypes/RelativeGoalBlock.java | 2 +- .../api/utils/command/datatypes/RelativeGoalXZ.java | 2 +- .../utils/command/helpers/arguments/ArgConsumer.java | 7 +------ .../baritone/api/utils/command/registry/Registry.java | 10 +--------- src/main/java/baritone/utils/IRenderer.java | 6 +----- src/main/java/baritone/utils/PathRenderer.java | 8 +------- 6 files changed, 6 insertions(+), 29 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java index 0730b517..a4dc75bd 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java @@ -31,7 +31,7 @@ public class RelativeGoalBlock implements IDatatypePost { } public RelativeGoalXZ(ArgConsumer consumer) { - coords = new RelativeCoordinate[] { + coords = new RelativeCoordinate[]{ consumer.getDatatype(RelativeCoordinate.class), consumer.getDatatype(RelativeCoordinate.class) }; diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index 75cf5962..a0c1f793 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -25,12 +25,7 @@ import baritone.api.utils.command.datatypes.IDatatype; import baritone.api.utils.command.datatypes.IDatatypeFor; import baritone.api.utils.command.datatypes.IDatatypePost; import baritone.api.utils.command.datatypes.RelativeFile; -import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.exception.CommandInvalidTypeException; -import baritone.api.utils.command.exception.CommandNoParserForTypeException; -import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; -import baritone.api.utils.command.exception.CommandTooManyArgumentsException; -import baritone.api.utils.command.exception.CommandUnhandledException; +import baritone.api.utils.command.exception.*; import net.minecraft.util.EnumFacing; import java.lang.reflect.InvocationTargetException; diff --git a/src/api/java/baritone/api/utils/command/registry/Registry.java b/src/api/java/baritone/api/utils/command/registry/Registry.java index b17997d3..4a8badd2 100644 --- a/src/api/java/baritone/api/utils/command/registry/Registry.java +++ b/src/api/java/baritone/api/utils/command/registry/Registry.java @@ -17,15 +17,7 @@ package baritone.api.utils.command.registry; -import java.util.Collection; -import java.util.Collections; -import java.util.Deque; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Set; -import java.util.Spliterator; -import java.util.Spliterators; +import java.util.*; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; diff --git a/src/main/java/baritone/utils/IRenderer.java b/src/main/java/baritone/utils/IRenderer.java index f9315de6..2de47ed7 100644 --- a/src/main/java/baritone/utils/IRenderer.java +++ b/src/main/java/baritone/utils/IRenderer.java @@ -30,11 +30,7 @@ import net.minecraft.util.math.AxisAlignedBB; import java.awt.Color; -import static org.lwjgl.opengl.GL11.GL_LINES; -import static org.lwjgl.opengl.GL11.GL_ONE; -import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA; -import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA; -import static org.lwjgl.opengl.GL11.GL_ZERO; +import static org.lwjgl.opengl.GL11.*; public interface IRenderer { Tessellator tessellator = Tessellator.getInstance(); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index b64995c2..8f8a3578 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -20,13 +20,7 @@ package baritone.utils; import baritone.api.BaritoneAPI; import baritone.api.event.events.RenderEvent; import baritone.api.pathing.calc.IPath; -import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.goals.GoalComposite; -import baritone.api.pathing.goals.GoalGetToBlock; -import baritone.api.pathing.goals.GoalInverted; -import baritone.api.pathing.goals.GoalTwoBlocks; -import baritone.api.pathing.goals.GoalXZ; -import baritone.api.pathing.goals.GoalYLevel; +import baritone.api.pathing.goals.*; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Helper; import baritone.api.utils.interfaces.IGoalRenderPos; From c54dcdba2418442cdf07387551823ad38e1066d1 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 6 Sep 2019 17:41:27 -0700 Subject: [PATCH 625/682] "stAnDaRd" ConTinuATion InDEnT --- .../utils/command/BaritoneChatControl.java | 26 +++++------ .../baritone/api/utils/command/Command.java | 4 +- .../command/argparser/ArgParserManager.java | 24 +++++----- .../command/argparser/DefaultArgParsers.java | 10 ++--- .../command/argument/CommandArgument.java | 12 ++--- .../utils/command/datatypes/BlockById.java | 16 +++---- .../command/datatypes/EntityClassById.java | 16 +++---- .../command/datatypes/ForEnumFacing.java | 14 +++--- .../utils/command/datatypes/ForWaypoints.java | 36 +++++++-------- .../command/datatypes/PlayerByUsername.java | 26 +++++------ .../command/datatypes/RelativeBlockPos.java | 6 +-- .../utils/command/datatypes/RelativeFile.java | 14 +++--- .../utils/command/datatypes/RelativeGoal.java | 12 ++--- .../command/datatypes/RelativeGoalBlock.java | 12 ++--- .../command/datatypes/RelativeGoalXZ.java | 8 ++-- .../CommandInvalidArgumentException.java | 6 +-- .../exception/CommandUnhandledException.java | 6 +-- .../command/execution/CommandExecution.java | 6 +-- .../command/helpers/pagination/Paginator.java | 44 +++++++++---------- .../tabcomplete/TabCompleteHelper.java | 38 ++++++++-------- .../utils/command/manager/CommandManager.java | 6 +-- .../api/utils/command/registry/Registry.java | 6 +-- .../java/baritone/utils/PathRenderer.java | 24 +++++----- 23 files changed, 186 insertions(+), 186 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index df7bab65..23bbd4a7 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -88,15 +88,15 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { ITextComponent component = new TextComponentString(String.format("> %s", toDisplay)); component.getStyle() - .setColor(TextFormatting.WHITE) - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("Click to rerun command") - )) - .setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - FORCE_COMMAND_PREFIX + msg - )); + .setColor(TextFormatting.WHITE) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to rerun command") + )) + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + FORCE_COMMAND_PREFIX + msg + )); logDirect(component); } @@ -195,10 +195,10 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (argc.hasAtMost(2)) { if (argc.hasExactly(1)) { return new TabCompleteHelper() - .addCommands() - .addSettings() - .filterPrefix(argc.getString()) - .stream(); + .addCommands() + .addSettings() + .filterPrefix(argc.getString()) + .stream(); } Settings.Setting setting = settings.byLowerName.get(argc.getString().toLowerCase(Locale.US)); diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index 410a34a9..bb00c8a7 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -51,8 +51,8 @@ public abstract class Command implements Helper, AbstractGameEventListener { */ protected Command(List names) { this.names = names.stream() - .map(s -> s.toLowerCase(Locale.US)) - .collect(Collectors.toList()); + .map(s -> s.toLowerCase(Locale.US)) + .collect(Collectors.toList()); baritone.getGameEventHandler().registerEventListener(this); } diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index c96418a4..7237ea07 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -38,11 +38,11 @@ public class ArgParserManager { public static ArgParser.Stateless getParserStateless(Class klass) { //noinspection unchecked return REGISTRY.descendingStream() - .filter(ArgParser.Stateless.class::isInstance) - .map(ArgParser.Stateless.class::cast) - .filter(parser -> parser.getKlass().isAssignableFrom(klass)) - .findFirst() - .orElse(null); + .filter(ArgParser.Stateless.class::isInstance) + .map(ArgParser.Stateless.class::cast) + .filter(parser -> parser.getKlass().isAssignableFrom(klass)) + .findFirst() + .orElse(null); } /** @@ -52,13 +52,13 @@ public class ArgParserManager { public static ArgParser.Stated getParserStated(Class klass, Class stateKlass) { //noinspection unchecked return REGISTRY.descendingStream() - .filter(ArgParser.Stated.class::isInstance) - .map(ArgParser.Stated.class::cast) - .filter(parser -> parser.getKlass().isAssignableFrom(klass)) - .filter(parser -> parser.getStateKlass().isAssignableFrom(stateKlass)) - .map(ArgParser.Stated.class::cast) - .findFirst() - .orElse(null); + .filter(ArgParser.Stated.class::isInstance) + .map(ArgParser.Stated.class::cast) + .filter(parser -> parser.getKlass().isAssignableFrom(klass)) + .filter(parser -> parser.getStateKlass().isAssignableFrom(stateKlass)) + .map(ArgParser.Stated.class::cast) + .findFirst() + .orElse(null); } /** diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index 2f51bbad..7518e459 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -114,10 +114,10 @@ public class DefaultArgParsers { } public static final List> ALL = asList( - IntArgumentParser.INSTANCE, - LongArgumentParser.INSTANCE, - FloatArgumentParser.INSTANCE, - DoubleArgumentParser.INSTANCE, - BooleanArgumentParser.INSTANCE + IntArgumentParser.INSTANCE, + LongArgumentParser.INSTANCE, + FloatArgumentParser.INSTANCE, + DoubleArgumentParser.INSTANCE, + BooleanArgumentParser.INSTANCE ); } diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index e793b8b5..49d8f477 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -67,9 +67,9 @@ public class CommandArgument { */ public > E getEnum(Class enumClass) { return Arrays.stream(enumClass.getEnumConstants()) - .filter(e -> e.name().equalsIgnoreCase(value)) - .findFirst() - .orElseThrow(() -> new CommandInvalidTypeException(this, enumClass.getSimpleName())); + .filter(e -> e.name().equalsIgnoreCase(value)) + .findFirst() + .orElseThrow(() -> new CommandInvalidTypeException(this, enumClass.getSimpleName())); } /** @@ -145,9 +145,9 @@ public class CommandArgument { int lastEnd = -1; while (argMatcher.find()) { args.add(new CommandArgument( - args.size(), - argMatcher.group(), - string.substring(argMatcher.start()) + args.size(), + argMatcher.group(), + string.substring(argMatcher.start()) )); lastEnd = argMatcher.end(); diff --git a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java index 617ccb57..e8d1589c 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java @@ -48,13 +48,13 @@ public class BlockById implements IDatatypeFor { @Override public Stream tabComplete(ArgConsumer consumer) { return new TabCompleteHelper() - .append( - Block.REGISTRY.getKeys() - .stream() - .map(Object::toString) - ) - .filterPrefixNamespaced(consumer.getString()) - .sortAlphabetically() - .stream(); + .append( + Block.REGISTRY.getKeys() + .stream() + .map(Object::toString) + ) + .filterPrefixNamespaced(consumer.getString()) + .sortAlphabetically() + .stream(); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java index 09cdbb92..fd053584 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java @@ -50,13 +50,13 @@ public class EntityClassById implements IDatatypeFor> { @Override public Stream tabComplete(ArgConsumer consumer) { return new TabCompleteHelper() - .append( - EntityList.getEntityNameList() - .stream() - .map(Object::toString) - ) - .filterPrefixNamespaced(consumer.getString()) - .sortAlphabetically() - .stream(); + .append( + EntityList.getEntityNameList() + .stream() + .map(Object::toString) + ) + .filterPrefixNamespaced(consumer.getString()) + .sortAlphabetically() + .stream(); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java index 2dbadd9d..f91eea0a 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java @@ -44,12 +44,12 @@ public class ForEnumFacing implements IDatatypeFor { @Override public Stream tabComplete(ArgConsumer consumer) { return new TabCompleteHelper() - .append( - Arrays.stream(EnumFacing.values()) - .map(EnumFacing::getName) - .map(String::toLowerCase) - ) - .filterPrefix(consumer.getString()) - .stream(); + .append( + Arrays.stream(EnumFacing.values()) + .map(EnumFacing::getName) + .map(String::toLowerCase) + ) + .filterPrefix(consumer.getString()) + .stream(); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java index 3cb27a50..c6720b1c 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -51,43 +51,43 @@ public class ForWaypoints implements IDatatypeFor { @Override public Stream tabComplete(ArgConsumer consumer) { return new TabCompleteHelper() - .append(getWaypointNames()) - .sortAlphabetically() - .prepend(IWaypoint.Tag.getAllNames()) - .filterPrefix(consumer.getString()) - .stream(); + .append(getWaypointNames()) + .sortAlphabetically() + .prepend(IWaypoint.Tag.getAllNames()) + .filterPrefix(consumer.getString()) + .stream(); } public static IWaypointCollection waypoints() { return BaritoneAPI.getProvider() - .getPrimaryBaritone() - .getWorldProvider() - .getCurrentWorld() - .getWaypoints(); + .getPrimaryBaritone() + .getWorldProvider() + .getCurrentWorld() + .getWaypoints(); } public static IWaypoint[] getWaypoints() { return waypoints().getAllWaypoints().stream() - .sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed()) - .toArray(IWaypoint[]::new); + .sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed()) + .toArray(IWaypoint[]::new); } public static String[] getWaypointNames() { return Arrays.stream(getWaypoints()) - .map(IWaypoint::getName) - .filter(name -> !name.equals("")) - .toArray(String[]::new); + .map(IWaypoint::getName) + .filter(name -> !name.equals("")) + .toArray(String[]::new); } public static IWaypoint[] getWaypointsByTag(IWaypoint.Tag tag) { return waypoints().getByTag(tag).stream() - .sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed()) - .toArray(IWaypoint[]::new); + .sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed()) + .toArray(IWaypoint[]::new); } public static IWaypoint[] getWaypointsByName(String name) { return Arrays.stream(getWaypoints()) - .filter(waypoint -> waypoint.getName().equalsIgnoreCase(name)) - .toArray(IWaypoint[]::new); + .filter(waypoint -> waypoint.getName().equalsIgnoreCase(name)) + .toArray(IWaypoint[]::new); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java index 6ef22b93..376f6b63 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java +++ b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java @@ -29,7 +29,7 @@ import static java.util.Objects.isNull; public class PlayerByUsername implements IDatatypeFor { private final List players = - BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().playerEntities; + BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().playerEntities; public final EntityPlayer player; public PlayerByUsername() { @@ -40,10 +40,10 @@ public class PlayerByUsername implements IDatatypeFor { String username = consumer.getString(); player = players - .stream() - .filter(s -> s.getName().equalsIgnoreCase(username)) - .findFirst() - .orElse(null); + .stream() + .filter(s -> s.getName().equalsIgnoreCase(username)) + .findFirst() + .orElse(null); if (isNull(player)) { throw new IllegalArgumentException("no player found by that username"); @@ -58,13 +58,13 @@ public class PlayerByUsername implements IDatatypeFor { @Override public Stream tabComplete(ArgConsumer consumer) { return new TabCompleteHelper() - .append( - players - .stream() - .map(EntityPlayer::getName) - ) - .filterPrefix(consumer.getString()) - .sortAlphabetically() - .stream(); + .append( + players + .stream() + .map(EntityPlayer::getName) + ) + .filterPrefix(consumer.getString()) + .sortAlphabetically() + .stream(); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java index ab728ede..f8b778df 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java @@ -44,9 +44,9 @@ public class RelativeBlockPos implements IDatatypePost { File currentFile = currentPath.isAbsolute() ? currentPath.toFile() : new File(base, currentPathStringThing); return Arrays.stream(Objects.requireNonNull(SHUT_THE_FUCK_UP_IOEXCEPTION_NOBODY_LIKES_YOU( - useParent - ? currentFile.getParentFile() - : currentFile + useParent + ? currentFile.getParentFile() + : currentFile ).listFiles())) - .map(f -> (currentPath.isAbsolute() ? f : basePath.relativize(f.toPath()).toString()) + - (f.isDirectory() ? File.separator : "")) - .filter(s -> s.toLowerCase(Locale.US).startsWith(currentPathStringThing.toLowerCase(Locale.US))) - .filter(s -> !s.contains(" ")); + .map(f -> (currentPath.isAbsolute() ? f : basePath.relativize(f.toPath()).toString()) + + (f.isDirectory() ? File.separator : "")) + .filter(s -> s.toLowerCase(Locale.US).startsWith(currentPathStringThing.toLowerCase(Locale.US))) + .filter(s -> !s.contains(" ")); } @Override diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java index a0f94cee..4b4170a9 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java @@ -56,18 +56,18 @@ public class RelativeGoal implements IDatatypePost { return new GoalBlock(origin); case 1: return new GoalYLevel( - coords[0].applyFloor(origin.y) + coords[0].applyFloor(origin.y) ); case 2: return new GoalXZ( - coords[0].applyFloor(origin.x), - coords[1].applyFloor(origin.z) + coords[0].applyFloor(origin.x), + coords[1].applyFloor(origin.z) ); case 3: return new GoalBlock( - coords[0].applyFloor(origin.x), - coords[1].applyFloor(origin.y), - coords[2].applyFloor(origin.z) + coords[0].applyFloor(origin.x), + coords[1].applyFloor(origin.y), + coords[2].applyFloor(origin.z) ); default: throw new IllegalStateException("Unexpected coords size: " + coords.length); diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java index a4dc75bd..ff332493 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java @@ -32,18 +32,18 @@ public class RelativeGoalBlock implements IDatatypePost { public RelativeGoalXZ(ArgConsumer consumer) { coords = new RelativeCoordinate[]{ - consumer.getDatatype(RelativeCoordinate.class), - consumer.getDatatype(RelativeCoordinate.class) + consumer.getDatatype(RelativeCoordinate.class), + consumer.getDatatype(RelativeCoordinate.class) }; } @Override public GoalXZ apply(BetterBlockPos origin) { return new GoalXZ( - coords[0].applyFloor(origin.x), - coords[1].applyFloor(origin.z) + coords[0].applyFloor(origin.x), + coords[1].applyFloor(origin.z) ); } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java b/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java index 342cf336..76d63979 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java @@ -24,9 +24,9 @@ public abstract class CommandInvalidArgumentException extends CommandErrorMessag protected CommandInvalidArgumentException(CommandArgument arg, String reason) { super(String.format( - "Error at argument #%s: %s", - arg.index == -1 ? "" : Integer.toString(arg.index + 1), - reason + "Error at argument #%s: %s", + arg.index == -1 ? "" : Integer.toString(arg.index + 1), + reason )); this.arg = arg; diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java index 9de56284..9c1f2f35 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -34,7 +34,7 @@ public class CommandUnhandledException extends CommandErrorMessageException { public static String getBaritoneStackTrace(String stackTrace) { List lines = Arrays.stream(stackTrace.split("\n")) - .collect(Collectors.toList()); + .collect(Collectors.toList()); int lastBaritoneLine = 0; for (int i = 0; i < lines.size(); i++) { @@ -76,8 +76,8 @@ public class CommandUnhandledException extends CommandErrorMessageException { public CommandUnhandledException(Throwable cause) { super(String.format( - "An unhandled exception has occurred:\n\n%s", - getFriendlierStackTrace(cause) + "An unhandled exception has occurred:\n\n%s", + getFriendlierStackTrace(cause) )); } } diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java index 2999666a..1563405e 100644 --- a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java +++ b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java @@ -97,9 +97,9 @@ public class CommandExecution { } return new CommandExecution( - command, - label, - args + command, + label, + args ); } diff --git a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java index 2fb2f5bc..22c796d0 100644 --- a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java +++ b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java @@ -83,14 +83,14 @@ public class Paginator implements Helper { if (hasPrevPage) { prevPageComponent.getStyle() - .setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - String.format("%s %d", commandPrefix, page - 1) - )) - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("Click to view previous page") - )); + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format("%s %d", commandPrefix, page - 1) + )) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to view previous page") + )); } else { prevPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY); } @@ -99,14 +99,14 @@ public class Paginator implements Helper { if (hasNextPage) { nextPageComponent.getStyle() - .setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - String.format("%s %d", commandPrefix, page + 1) - )) - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("Click to view next page") - )); + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format("%s %d", commandPrefix, page + 1) + )) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to view next page") + )); } else { nextPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY); } @@ -134,12 +134,12 @@ public class Paginator implements Helper { if (!pagi.validPage(page)) { throw new CommandInvalidTypeException( - consumer.consumed(), - String.format( - "a valid page (1-%d)", - pagi.getMaxPage() - ), - consumer.consumed().value + consumer.consumed(), + String.format( + "a valid page (1-%d)", + pagi.getMaxPage() + ), + consumer.consumed().value ); } } diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index 972b634d..2878b8df 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -112,9 +112,9 @@ public class TabCompleteHelper { */ public TabCompleteHelper append(Class> num) { return append( - Arrays.stream(num.getEnumConstants()) - .map(Enum::name) - .map(String::toLowerCase) + Arrays.stream(num.getEnumConstants()) + .map(Enum::name) + .map(String::toLowerCase) ); } @@ -163,9 +163,9 @@ public class TabCompleteHelper { */ public TabCompleteHelper prepend(Class> num) { return prepend( - Arrays.stream(num.getEnumConstants()) - .map(Enum::name) - .map(String::toLowerCase) + Arrays.stream(num.getEnumConstants()) + .map(Enum::name) + .map(String::toLowerCase) ); } @@ -263,9 +263,9 @@ public class TabCompleteHelper { */ public TabCompleteHelper addCommands() { return append( - CommandManager.REGISTRY.descendingStream() - .flatMap(command -> command.names.stream()) - .distinct() + CommandManager.REGISTRY.descendingStream() + .flatMap(command -> command.names.stream()) + .distinct() ); } @@ -276,10 +276,10 @@ public class TabCompleteHelper { */ public TabCompleteHelper addSettings() { return append( - BaritoneAPI.getSettings().allSettings.stream() - .map(Settings.Setting::getName) - .filter(s -> !s.equalsIgnoreCase("logger")) - .sorted(String.CASE_INSENSITIVE_ORDER) + BaritoneAPI.getSettings().allSettings.stream() + .map(Settings.Setting::getName) + .filter(s -> !s.equalsIgnoreCase("logger")) + .sorted(String.CASE_INSENSITIVE_ORDER) ); } @@ -290,9 +290,9 @@ public class TabCompleteHelper { */ public TabCompleteHelper addModifiedSettings() { return append( - SettingsUtil.modifiedSettings(BaritoneAPI.getSettings()).stream() - .map(Settings.Setting::getName) - .sorted(String.CASE_INSENSITIVE_ORDER) + SettingsUtil.modifiedSettings(BaritoneAPI.getSettings()).stream() + .map(Settings.Setting::getName) + .sorted(String.CASE_INSENSITIVE_ORDER) ); } @@ -303,9 +303,9 @@ public class TabCompleteHelper { */ public TabCompleteHelper addToggleableSettings() { return append( - BaritoneAPI.getSettings().getAllValuesByType(Boolean.class).stream() - .map(Settings.Setting::getName) - .sorted(String.CASE_INSENSITIVE_ORDER) + BaritoneAPI.getSettings().getAllValuesByType(Boolean.class).stream() + .map(Settings.Setting::getName) + .sorted(String.CASE_INSENSITIVE_ORDER) ); } } diff --git a/src/api/java/baritone/api/utils/command/manager/CommandManager.java b/src/api/java/baritone/api/utils/command/manager/CommandManager.java index 287acaa5..425da5ef 100644 --- a/src/api/java/baritone/api/utils/command/manager/CommandManager.java +++ b/src/api/java/baritone/api/utils/command/manager/CommandManager.java @@ -78,9 +78,9 @@ public class CommandManager { if (args.isEmpty()) { return new TabCompleteHelper() - .addCommands() - .filterPrefix(label) - .stream(); + .addCommands() + .filterPrefix(label) + .stream(); } else { return tabComplete(pair); } diff --git a/src/api/java/baritone/api/utils/command/registry/Registry.java b/src/api/java/baritone/api/utils/command/registry/Registry.java index 4a8badd2..82a3dc6f 100644 --- a/src/api/java/baritone/api/utils/command/registry/Registry.java +++ b/src/api/java/baritone/api/utils/command/registry/Registry.java @@ -132,9 +132,9 @@ public class Registry { */ public Stream descendingStream() { return StreamSupport.stream(Spliterators.spliterator( - descendingIterator(), - _entries.size(), - Spliterator.SIZED | Spliterator.SUBSIZED + descendingIterator(), + _entries.size(), + Spliterator.SIZED | Spliterator.SUBSIZED ), false); } } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 8f8a3578..58917436 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -131,9 +131,9 @@ public final class PathRenderer implements IRenderer { int dirZ = end.z - start.z; while (next + 1 < positions.size() && (!fadeOut || next + 1 < fadeStart) && - (dirX == positions.get(next + 1).x - end.x && - dirY == positions.get(next + 1).y - end.y && - dirZ == positions.get(next + 1).z - end.z)) { + (dirX == positions.get(next + 1).x - end.x && + dirY == positions.get(next + 1).y - end.y && + dirZ == positions.get(next + 1).z - end.z)) { end = positions.get(++next); } @@ -239,15 +239,15 @@ public final class PathRenderer implements IRenderer { } TileEntityBeaconRenderer.renderBeamSegment( - goalPos.getX() - renderPosX, - -renderPosY, - goalPos.getZ() - renderPosZ, - partialTicks, - 1.0, - player.world.getTotalWorldTime(), - 0, - 256, - color.getColorComponents(null) + goalPos.getX() - renderPosX, + -renderPosY, + goalPos.getZ() - renderPosZ, + partialTicks, + 1.0, + player.world.getTotalWorldTime(), + 0, + 256, + color.getColorComponents(null) ); if (settings.renderGoalIgnoreDepth.value) { From 240af75ff777eb08b7499b1471e963f5ba87c72f Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 6 Sep 2019 17:45:34 -0700 Subject: [PATCH 626/682] that specific continuation indent --- .../java/baritone/process/BuilderProcess.java | 34 ++++++------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 4d3c2e5c..0d84d952 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -25,11 +25,7 @@ import baritone.api.pathing.goals.GoalGetToBlock; import baritone.api.process.IBuilderProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.ISchematic; -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; @@ -52,20 +48,12 @@ import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.Tuple; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.math.Vec3i; +import net.minecraft.util.math.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.OptionalInt; +import java.util.*; import static baritone.api.pathing.movement.ActionCosts.COST_INF; @@ -289,14 +277,14 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil ctx.player().rotationYaw = rot.getYaw(); ctx.player().rotationPitch = rot.getPitch(); IBlockState wouldBePlaced = ((ItemBlock) stack.getItem()).getBlock().getStateForPlacement( - ctx.world(), - result.getBlockPos().offset(result.sideHit), - result.sideHit, - (float) result.hitVec.x - result.getBlockPos().getX(), // as in PlayerControllerMP - (float) result.hitVec.y - result.getBlockPos().getY(), - (float) result.hitVec.z - result.getBlockPos().getZ(), - stack.getItem().getMetadata(stack.getMetadata()), - ctx.player() + ctx.world(), + result.getBlockPos().offset(result.sideHit), + result.sideHit, + (float) result.hitVec.x - result.getBlockPos().getX(), // as in PlayerControllerMP + (float) result.hitVec.y - result.getBlockPos().getY(), + (float) result.hitVec.z - result.getBlockPos().getZ(), + stack.getItem().getMetadata(stack.getMetadata()), + ctx.player() ); ctx.player().rotationYaw = originalYaw; ctx.player().rotationPitch = originalPitch; From 147884f76d1987353691f8c0c1737fdccaa8ee1e Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 6 Sep 2019 17:46:26 -0700 Subject: [PATCH 627/682] mineprocess reformat too --- .../java/baritone/process/MineProcess.java | 72 ++++++++----------- 1 file changed, 28 insertions(+), 44 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index a741c6d6..01c24884 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -18,21 +18,11 @@ package baritone.process; import baritone.Baritone; -import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.goals.GoalBlock; -import baritone.api.pathing.goals.GoalComposite; -import baritone.api.pathing.goals.GoalRunAway; -import baritone.api.pathing.goals.GoalTwoBlocks; +import baritone.api.pathing.goals.*; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.BlockOptionalMeta; -import baritone.api.utils.BlockOptionalMetaLookup; -import baritone.api.utils.BlockUtils; -import baritone.api.utils.IPlayerContext; -import baritone.api.utils.Rotation; -import baritone.api.utils.RotationUtils; +import baritone.api.utils.*; import baritone.api.utils.input.Input; import baritone.cache.CachedChunk; import baritone.cache.WorldScanner; @@ -51,13 +41,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; -import java.util.Optional; +import java.util.*; import java.util.stream.Collectors; import static baritone.api.pathing.movement.ActionCosts.COST_INF; @@ -91,8 +75,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (desiredQuantity > 0) { int curr = ctx.player().inventory.mainInventory.stream() - .filter(stack -> filter.has(stack)) - .mapToInt(ItemStack::getCount).sum(); + .filter(stack -> filter.has(stack)) + .mapToInt(ItemStack::getCount).sum(); System.out.println("Currently have " + curr + " valid items"); if (curr >= desiredQuantity) { logDirect("Have " + curr + " valid items"); @@ -126,10 +110,10 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro addNearby(); } Optional shaft = curr.stream() - .filter(pos -> pos.getX() == ctx.playerFeet().getX() && pos.getZ() == ctx.playerFeet().getZ()) - .filter(pos -> pos.getY() >= ctx.playerFeet().getY()) - .filter(pos -> !(BlockStateInterface.get(ctx, pos).getBlock() instanceof BlockAir)) // after breaking a block, it takes mineGoalUpdateInterval ticks for it to actually update this list =( - .min(Comparator.comparingDouble(ctx.player()::getDistanceSq)); + .filter(pos -> pos.getX() == ctx.playerFeet().getX() && pos.getZ() == ctx.playerFeet().getZ()) + .filter(pos -> pos.getY() >= ctx.playerFeet().getY()) + .filter(pos -> !(BlockStateInterface.get(ctx, pos).getBlock() instanceof BlockAir)) // after breaking a block, it takes mineGoalUpdateInterval ticks for it to actually update this list =( + .min(Comparator.comparingDouble(ctx.player()::getDistanceSq)); baritone.getInputOverrideHandler().clearAllKeys(); if (shaft.isPresent() && ctx.player().onGround) { BlockPos pos = shaft.get(); @@ -322,11 +306,11 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro // maxRegionDistanceSq 2 means adjacent directly or adjacent diagonally; nothing further than that locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf( - BlockUtils.blockToString(block), - Baritone.settings().maxCachedWorldScanCount.value, - pf.x, - pf.z, - 2 + BlockUtils.blockToString(block), + Baritone.settings().maxCachedWorldScanCount.value, + pf.x, + pf.z, + 2 )); } else { untracked.add(block); @@ -337,11 +321,11 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (!untracked.isEmpty() || (Baritone.settings().extendCacheOnThreshold.value && locs.size() < max)) { locs.addAll(WorldScanner.INSTANCE.scanChunkRadius( - ctx.getBaritone().getPlayerContext(), - filter, - max, - 10, - 32 + ctx.getBaritone().getPlayerContext(), + filter, + max, + 10, + 32 )); // maxSearchRadius is NOT sq } @@ -384,19 +368,19 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return false; }); List locs = locs2 - .stream() - .distinct() + .stream() + .distinct() - // remove any that are within loaded chunks that aren't actually what we want - .filter(pos -> !ctx.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ()) || filter.has(ctx.get(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos)) + // remove any that are within loaded chunks that aren't actually what we want + .filter(pos -> !ctx.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ()) || filter.has(ctx.get(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos)) - // remove any that are implausible to mine (encased in bedrock, or touching lava) - .filter(pos -> MineProcess.plausibleToBreak(ctx, pos)) + // remove any that are implausible to mine (encased in bedrock, or touching lava) + .filter(pos -> MineProcess.plausibleToBreak(ctx, pos)) - .filter(pos -> !blacklist.contains(pos)) + .filter(pos -> !blacklist.contains(pos)) - .sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().player()::getDistanceSq)) - .collect(Collectors.toList()); + .sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().player()::getDistanceSq)) + .collect(Collectors.toList()); if (locs.size() > max) { return locs.subList(0, max); From 1bb4e44b710c57c20ae75d639fd730431418f445 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 6 Sep 2019 17:50:55 -0700 Subject: [PATCH 628/682] bom import * --- .../baritone/api/utils/BlockOptionalMeta.java | 73 +++++-------------- 1 file changed, 20 insertions(+), 53 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index 3776baf3..22ba74ea 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -19,35 +19,7 @@ package baritone.api.utils; import baritone.api.accessor.IItemStack; import com.google.common.collect.ImmutableSet; -import net.minecraft.block.Block; -import net.minecraft.block.BlockBanner; -import net.minecraft.block.BlockBed; -import net.minecraft.block.BlockBrewingStand; -import net.minecraft.block.BlockButton; -import net.minecraft.block.BlockChorusPlant; -import net.minecraft.block.BlockDirt; -import net.minecraft.block.BlockDoor; -import net.minecraft.block.BlockDoublePlant; -import net.minecraft.block.BlockFence; -import net.minecraft.block.BlockFire; -import net.minecraft.block.BlockGrass; -import net.minecraft.block.BlockLeaves; -import net.minecraft.block.BlockLever; -import net.minecraft.block.BlockLog; -import net.minecraft.block.BlockPane; -import net.minecraft.block.BlockQuartz; -import net.minecraft.block.BlockRailBase; -import net.minecraft.block.BlockRedstoneWire; -import net.minecraft.block.BlockSapling; -import net.minecraft.block.BlockSkull; -import net.minecraft.block.BlockSlab; -import net.minecraft.block.BlockStairs; -import net.minecraft.block.BlockStandingSign; -import net.minecraft.block.BlockStem; -import net.minecraft.block.BlockTrapDoor; -import net.minecraft.block.BlockTripWire; -import net.minecraft.block.BlockVine; -import net.minecraft.block.BlockWall; +import net.minecraft.block.*; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; @@ -56,12 +28,7 @@ import net.minecraft.util.ResourceLocation; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Random; -import java.util.Set; +import java.util.*; import java.util.function.Consumer; import java.util.regex.MatchResult; import java.util.regex.Matcher; @@ -230,22 +197,22 @@ public final class BlockOptionalMeta { if (normalizations.containsKey(property)) { try { newState = newState.withProperty( - castToIProperty(property), - castToIPropertyValue(property, normalizations.get(property)) + castToIProperty(property), + castToIPropertyValue(property, normalizations.get(property)) ); } catch (IllegalArgumentException ignored) {} } else if (normalizations.containsKey(state.getValue(property))) { try { newState = newState.withProperty( - castToIProperty(property), - castToIPropertyValue(property, normalizations.get(state.getValue(property))) + castToIProperty(property), + castToIPropertyValue(property, normalizations.get(state.getValue(property))) ); } catch (IllegalArgumentException ignored) {} } else if (normalizations.containsKey(valueClass)) { try { newState = newState.withProperty( - castToIProperty(property), - castToIPropertyValue(property, normalizations.get(valueClass)) + castToIProperty(property), + castToIPropertyValue(property, normalizations.get(valueClass)) ); } catch (IllegalArgumentException ignored) {} } @@ -260,28 +227,28 @@ public final class BlockOptionalMeta { private static Set getStates(@Nonnull Block block, @Nullable Integer meta) { return block.getBlockState().getValidStates().stream() - .filter(blockstate -> meta == null || stateMeta(blockstate) == meta) - .collect(Collectors.toSet()); + .filter(blockstate -> meta == null || stateMeta(blockstate) == meta) + .collect(Collectors.toSet()); } private static ImmutableSet getStateHashes(Set blockstates) { return ImmutableSet.copyOf( - blockstates.stream() - .map(IBlockState::hashCode) - .toArray(Integer[]::new) + blockstates.stream() + .map(IBlockState::hashCode) + .toArray(Integer[]::new) ); } private static ImmutableSet getStackHashes(Set blockstates) { //noinspection ConstantConditions return ImmutableSet.copyOf( - blockstates.stream() - .map(state -> new ItemStack( - state.getBlock().getItemDropped(state, new Random(), 0), - state.getBlock().damageDropped(state) - )) - .map(stack -> ((IItemStack) (Object) stack).getBaritoneHash()) - .toArray(Integer[]::new) + blockstates.stream() + .map(state -> new ItemStack( + state.getBlock().getItemDropped(state, new Random(), 0), + state.getBlock().damageDropped(state) + )) + .map(stack -> ((IItemStack) (Object) stack).getBaritoneHash()) + .toArray(Integer[]::new) ); } From fc63c16ee0b0d55f2dbd054dd216141077be5085 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sat, 7 Sep 2019 00:21:54 -0700 Subject: [PATCH 629/682] initialize chat control only once ever --- src/main/java/baritone/Baritone.java | 3 --- src/main/java/baritone/BaritoneProvider.java | 8 ++++++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 4b00c797..7f70bbea 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -135,9 +135,6 @@ public class Baritone implements IBaritone { } this.initialized = true; - - DefaultCommands.COMMANDS.forEach(CommandManager.REGISTRY::register); - new BaritoneChatControl(this); } @Override diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index 44715f4c..9fdd0489 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -20,7 +20,10 @@ package baritone; import baritone.api.IBaritone; import baritone.api.IBaritoneProvider; import baritone.api.cache.IWorldScanner; +import baritone.api.utils.command.BaritoneChatControl; +import baritone.api.utils.command.manager.CommandManager; import baritone.cache.WorldScanner; +import baritone.utils.command.defaults.DefaultCommands; import java.util.Collections; import java.util.List; @@ -34,6 +37,11 @@ public final class BaritoneProvider implements IBaritoneProvider { private final Baritone primary = new Baritone(); private final List all = Collections.singletonList(primary); + { + DefaultCommands.COMMANDS.forEach(CommandManager.REGISTRY::register); + new BaritoneChatControl(primary); + } + @Override public IBaritone getPrimaryBaritone() { return primary; From bf03a000d15afffa0edd7e7384644ac26deba92e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 9 Sep 2019 23:06:11 -0700 Subject: [PATCH 630/682] diagonal ascend --- src/api/java/baritone/api/Settings.java | 7 ++ .../pathing/movement/CalculationContext.java | 2 + .../movement/movements/MovementDiagonal.java | 73 +++++++++++++++---- 3 files changed, 66 insertions(+), 16 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 6e682509..614f2340 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -140,6 +140,13 @@ public final class Settings { */ public final Setting allowDiagonalDescend = new Setting<>(false); + /** + * Allow diagonal ascending + *

+ * Actually pretty safe, much safer than diagonal descend tbh + */ + public final Setting allowDiagonalAscend = new Setting<>(false); + /** * Allow mining the block directly beneath its feet *

diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 2f82513e..8e2fc518 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -61,6 +61,7 @@ public class CalculationContext { public final boolean allowParkourAscend; public final boolean assumeWalkOnWater; public final boolean allowDiagonalDescend; + public final boolean allowDiagonalAscend; public final boolean allowDownward; public final int maxFallHeightNoWater; public final int maxFallHeightBucket; @@ -94,6 +95,7 @@ public class CalculationContext { this.allowParkourAscend = Baritone.settings().allowParkourAscend.value; this.assumeWalkOnWater = Baritone.settings().assumeWalkOnWater.value; this.allowDiagonalDescend = Baritone.settings().allowDiagonalDescend.value; + this.allowDiagonalAscend = Baritone.settings().allowDiagonalAscend.value; this.allowDownward = Baritone.settings().allowDownward.value; this.maxFallHeightNoWater = Baritone.settings().maxFallHeightNoWater.value; this.maxFallHeightBucket = Baritone.settings().maxFallHeightBucket.value; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index c036a459..450144c0 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -70,24 +70,37 @@ public class MovementDiagonal extends Movement { protected Set calculateValidPositions() { BetterBlockPos diagA = new BetterBlockPos(src.x, src.y, dest.z); BetterBlockPos diagB = new BetterBlockPos(dest.x, src.y, src.z); - if (dest.y != src.y) { // only if allowDiagonalDescend + if (dest.y < src.y) { return ImmutableSet.of(src, dest.up(), diagA, diagB, dest, diagA.down(), diagB.down()); } + if (dest.y > src.y) { + return ImmutableSet.of(src, src.up(), diagA, diagB, dest, diagA.up(), diagB.up()); + } return ImmutableSet.of(src, dest, diagA, diagB); } public static void cost(CalculationContext context, int x, int y, int z, int destX, int destZ, MutableMoveResult res) { - IBlockState destInto = context.get(destX, y, destZ); - if (!MovementHelper.canWalkThrough(context.bsi, destX, y, destZ, destInto) || !MovementHelper.canWalkThrough(context.bsi, destX, y + 1, destZ)) { + if (!MovementHelper.canWalkThrough(context.bsi, destX, y + 1, destZ)) { return; } - IBlockState destWalkOn = context.get(destX, y - 1, destZ); + IBlockState destInto = context.get(destX, y, destZ); + boolean ascend = false; + IBlockState destWalkOn; boolean descend = false; - if (!MovementHelper.canWalkOn(context.bsi, destX, y - 1, destZ, destWalkOn)) { - descend = true; - if (!context.allowDiagonalDescend || !MovementHelper.canWalkOn(context.bsi, destX, y - 2, destZ) || !MovementHelper.canWalkThrough(context.bsi, destX, y - 1, destZ, destWalkOn)) { + if (!MovementHelper.canWalkThrough(context.bsi, destX, y, destZ, destInto)) { + ascend = true; + if (!context.allowDiagonalAscend || !MovementHelper.canWalkThrough(context.bsi, x, y + 2, z) || !MovementHelper.canWalkOn(context.bsi, destX, y, destZ, destInto) || !MovementHelper.canWalkThrough(context.bsi, destX, y + 2, destZ)) { return; } + destWalkOn = destInto; + } else { + destWalkOn = context.get(destX, y - 1, destZ); + if (!MovementHelper.canWalkOn(context.bsi, destX, y - 1, destZ, destWalkOn)) { + descend = true; + if (!context.allowDiagonalDescend || !MovementHelper.canWalkOn(context.bsi, destX, y - 2, destZ) || !MovementHelper.canWalkThrough(context.bsi, destX, y - 1, destZ, destWalkOn)) { + return; + } + } } double multiplier = WALK_ONE_BLOCK_COST; // For either possible soul sand, that affects half of our walking @@ -111,8 +124,42 @@ public class MovementDiagonal extends Movement { if (cuttingOver2 == Blocks.MAGMA || MovementHelper.isLava(cuttingOver2)) { return; } + Block startIn = context.getBlock(x, y, z); + boolean water = false; + if (MovementHelper.isWater(startIn) || MovementHelper.isWater(destInto.getBlock())) { + if (ascend) { + return; + } + // Ignore previous multiplier + // Whatever we were walking on (possibly soul sand) doesn't matter as we're actually floating on water + // Not even touching the blocks below + multiplier = context.waterWalkSpeed; + water = true; + } IBlockState pb0 = context.get(x, y, destZ); IBlockState pb2 = context.get(destX, y, z); + if (ascend) { + boolean ATop = MovementHelper.canWalkThrough(context.bsi, x, y + 2, destZ); + boolean AMid = MovementHelper.canWalkThrough(context.bsi, x, y + 1, destZ); + boolean ALow = MovementHelper.canWalkThrough(context.bsi, x, y, destZ, pb0); + boolean BTop = MovementHelper.canWalkThrough(context.bsi, destX, y + 2, z); + boolean BMid = MovementHelper.canWalkThrough(context.bsi, destX, y + 1, z); + boolean BLow = MovementHelper.canWalkThrough(context.bsi, destX, y, z, pb2); + if ((!(ATop && AMid && ALow) && !(BTop && BMid && BLow)) // no option + || MovementHelper.avoidWalkingInto(pb0.getBlock()) // bad + || MovementHelper.avoidWalkingInto(pb2.getBlock()) // bad + || (ATop && AMid && MovementHelper.canWalkOn(context.bsi, x, y, destZ, pb0)) // we could just ascend + || (BTop && BMid && MovementHelper.canWalkOn(context.bsi, destX, y, z, pb2)) // we could just ascend + || (!ATop && AMid && ALow) // head bonk A + || (!BTop && BMid && BLow)) { // head bonk B + return; + } + res.cost = multiplier * SQRT_2 + JUMP_ONE_BLOCK_COST; + res.x = destX; + res.z = destZ; + res.y = y + 1; + return; + } double optionA = MovementHelper.getMiningDurationTicks(context, x, y, destZ, pb0, false); double optionB = MovementHelper.getMiningDurationTicks(context, destX, y, z, pb2, false); if (optionA != 0 && optionB != 0) { @@ -140,15 +187,6 @@ public class MovementDiagonal extends Movement { // and now that option B is fully calculated, see if we can edge around that way return; } - boolean water = false; - Block startIn = context.getBlock(x, y, z); - if (MovementHelper.isWater(startIn) || MovementHelper.isWater(destInto.getBlock())) { - // Ignore previous multiplier - // Whatever we were walking on (possibly soul sand) doesn't matter as we're actually floating on water - // Not even touching the blocks below - multiplier = context.waterWalkSpeed; - water = true; - } if (optionA != 0 || optionB != 0) { multiplier *= SQRT_2 - 0.001; // TODO tune if (startIn == Blocks.LADDER || startIn == Blocks.VINE) { @@ -187,6 +225,9 @@ public class MovementDiagonal extends Movement { } else if (!playerInValidPosition() && !(MovementHelper.isLiquid(ctx, src) && getValidPositions().contains(ctx.playerFeet().up()))) { return state.setStatus(MovementStatus.UNREACHABLE); } + if (dest.y > src.y && ctx.player().posY < src.y + 0.1 && ctx.player().collidedHorizontally) { + state.setInput(Input.JUMP, true); + } if (sprint()) { state.setInput(Input.SPRINT, true); } From cccd61e050cee1b16da01e54c2740a184c581529 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 15 Sep 2019 11:37:09 -0700 Subject: [PATCH 631/682] add ability to build from opposite corner --- src/api/java/baritone/api/Settings.java | 15 +++++++++++++++ .../java/baritone/process/BuilderProcess.java | 14 +++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 614f2340..55420e38 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -742,6 +742,21 @@ public final class Settings { */ public final Setting breakCorrectBlockPenaltyMultiplier = new Setting<>(10d); + /** + * When this setting is true, build a schematic with the highest X coordinate being the origin, instead of the lowest + */ + public final Setting schematicOrientationX = new Setting<>(false); + + /** + * When this setting is true, build a schematic with the highest Y coordinate being the origin, instead of the lowest + */ + public final Setting schematicOrientationY = new Setting<>(false); + + /** + * When this setting is true, build a schematic with the highest Z coordinate being the origin, instead of the lowest + */ + public final Setting schematicOrientationZ = new Setting<>(false); + /** * While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)? */ diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 84ea8da3..b924347c 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -78,7 +78,19 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil this.name = name; this.schematic = schematic; this.realSchematic = null; - this.origin = origin; + int x = origin.getX(); + int y = origin.getY(); + int z = origin.getZ(); + if (Baritone.settings().schematicOrientationX.value) { + x += schematic.widthX(); + } + if (Baritone.settings().schematicOrientationY.value) { + y += schematic.heightY(); + } + if (Baritone.settings().schematicOrientationZ.value) { + z += schematic.lengthZ(); + } + this.origin = new Vec3i(x, y, z); this.paused = false; this.layer = 0; this.observedCompleted = new LongOpenHashSet(); From 5f674b86f8a3f8b26d2f0ea59bef80e5a7898381 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 16 Sep 2019 23:17:20 -0700 Subject: [PATCH 632/682] add a setting to scan a larger radius every tick --- src/api/java/baritone/api/Settings.java | 6 ++++++ src/main/java/baritone/process/BuilderProcess.java | 7 ++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 55420e38..d0181366 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -757,6 +757,12 @@ public final class Settings { */ public final Setting schematicOrientationZ = new Setting<>(false); + /** + * Distance to scan every tick for updates. Expanding this beyond player reach distance (i.e. setting it to 6 or above) + * is only necessary in very large schematics where rescanning the whole thing is costly. + */ + public final Setting builderTickScanRadius = new Setting<>(5); + /** * While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)? */ diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index b924347c..310a7a8a 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -486,9 +486,10 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil private void recalcNearby(BuilderCalculationContext bcc) { BetterBlockPos center = ctx.playerFeet(); - for (int dx = -5; dx <= 5; dx++) { - for (int dy = -5; dy <= 5; dy++) { - for (int dz = -5; dz <= 5; dz++) { + int radius = Baritone.settings().builderTickScanRadius.value; + for (int dx = -radius; dx <= radius; dx++) { + for (int dy = -radius; dy <= radius; dy++) { + for (int dz = -radius; dz <= radius; dz++) { int x = center.x + dx; int y = center.y + dy; int z = center.z + dz; From 7f58847f883f5864cbdb5a73b14f609da3a137c0 Mon Sep 17 00:00:00 2001 From: BlueBlazeTech <35273524+BlueBlazeTech@users.noreply.github.com> Date: Wed, 18 Sep 2019 09:37:40 -0600 Subject: [PATCH 633/682] Updated Standards section of CODE_OF_CONDUCT.md added additional details to standards -line 20 -line 17 -line 32 --- CODE_OF_CONDUCT.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 37c1b703..474ecf7e 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -14,10 +14,10 @@ appearance, race, religion, or sexual identity and orientation. Examples of behavior that contributes to creating a positive environment include: -* No Anime +* No Anime (including uwu's or owo's) * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism +* Giving and gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members @@ -29,7 +29,7 @@ Examples of unacceptable behavior by participants include: * ~~Trolling, insulting/derogatory comments, and personal or political attacks~~ * Public or private harassment * Publishing others' private information, such as a physical or electronic - address, without explicit permission + address, without explicit permission or consent * Other conduct which could reasonably be considered inappropriate in a professional setting From fa905b8844691e935db4cb06d0e29f10cba4f70c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 12:28:56 -0700 Subject: [PATCH 634/682] fix breaking blocks --- src/api/java/baritone/api/Settings.java | 5 +++ .../mixins/MixinPlayerControllerMP.java | 40 +++++++++++++++++++ src/launch/resources/mixins.baritone.json | 1 + .../java/baritone/behavior/LookBehavior.java | 2 + .../java/baritone/utils/BlockBreakHelper.java | 15 ++++++- .../utils/accessor/IPlayerControllerMP.java | 28 +++++++++++++ 6 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 src/launch/java/baritone/launch/mixins/MixinPlayerControllerMP.java create mode 100644 src/main/java/baritone/utils/accessor/IPlayerControllerMP.java diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index d0181366..a95d30d2 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -248,6 +248,11 @@ public final class Settings { */ public final Setting rightClickSpeed = new Setting<>(4); + /** + * How many degrees to randomize the pitch and yaw every tick. Set to 0 to disable + */ + public final Setting randomLooking = new Setting<>(0.01d); + /** * This is the big A* setting. * As long as your cost heuristic is an *underestimate*, it's guaranteed to find you the best path. diff --git a/src/launch/java/baritone/launch/mixins/MixinPlayerControllerMP.java b/src/launch/java/baritone/launch/mixins/MixinPlayerControllerMP.java new file mode 100644 index 00000000..c0294355 --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinPlayerControllerMP.java @@ -0,0 +1,40 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import baritone.utils.accessor.IPlayerControllerMP; +import net.minecraft.client.multiplayer.PlayerControllerMP; +import net.minecraft.util.math.BlockPos; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(PlayerControllerMP.class) +public abstract class MixinPlayerControllerMP implements IPlayerControllerMP { + @Accessor + @Override + public abstract void setIsHittingBlock(boolean isHittingBlock); + + @Accessor + @Override + public abstract BlockPos getCurrentBlock(); + + @Invoker + @Override + public abstract void callSyncCurrentPlayItem(); +} diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index 2a38a317..669b64cb 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -19,6 +19,7 @@ "MixinMinecraft", "MixinNetHandlerPlayClient", "MixinNetworkManager", + "MixinPlayerControllerMP", "MixinRenderChunk", "MixinRenderList", "MixinVboRenderList", diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index de131d12..32e5c22f 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -72,6 +72,8 @@ public final class LookBehavior extends Behavior implements ILookBehavior { 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(); } diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index 95d021c2..7f8ada84 100644 --- a/src/main/java/baritone/utils/BlockBreakHelper.java +++ b/src/main/java/baritone/utils/BlockBreakHelper.java @@ -19,6 +19,8 @@ package baritone.utils; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; +import baritone.utils.accessor.IPlayerControllerMP; +import net.minecraft.client.Minecraft; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; @@ -46,8 +48,13 @@ public final class BlockBreakHelper implements Helper { public void stopBreakingBlock() { // The player controller will never be null, but the player can be - if (playerContext.player() != null) { + if (playerContext.player() != null && didBreakLastTick) { + if (((IPlayerControllerMP) mc.playerController).getCurrentBlock().getY() != -1) { + // insane bypass to check breaking succeeded + ((IPlayerControllerMP) mc.playerController).setIsHittingBlock(true); + } playerContext.playerController().resetBlockRemoving(); + didBreakLastTick = false; } } @@ -57,11 +64,17 @@ public final class BlockBreakHelper implements Helper { boolean isBlockTrace = trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK; if (isLeftClick && isBlockTrace) { + if (!didBreakLastTick) { + ((IPlayerControllerMP) Minecraft.getMinecraft().playerController).callSyncCurrentPlayItem(); + Minecraft.getMinecraft().playerController.clickBlock(trace.getBlockPos(), trace.sideHit); + playerContext.player().swingArm(EnumHand.MAIN_HAND); + } tryBreakBlock(trace.getBlockPos(), trace.sideHit); didBreakLastTick = true; } else if (didBreakLastTick) { stopBreakingBlock(); didBreakLastTick = false; } + ((IPlayerControllerMP) Minecraft.getMinecraft().playerController).setIsHittingBlock(false); } } diff --git a/src/main/java/baritone/utils/accessor/IPlayerControllerMP.java b/src/main/java/baritone/utils/accessor/IPlayerControllerMP.java new file mode 100644 index 00000000..58959d6d --- /dev/null +++ b/src/main/java/baritone/utils/accessor/IPlayerControllerMP.java @@ -0,0 +1,28 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils.accessor; + +import net.minecraft.util.math.BlockPos; + +public interface IPlayerControllerMP { + void setIsHittingBlock(boolean isHittingBlock); + + BlockPos getCurrentBlock(); + + void callSyncCurrentPlayItem(); +} From 396a96d604159381f46b1872cf3efb604fdda04f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 12:53:15 -0700 Subject: [PATCH 635/682] reformat --- .../java/baritone/api/cache/IWaypoint.java | 6 +- src/api/java/baritone/api/cache/Waypoint.java | 9 +- .../api/event/events/type/Overrideable.java | 6 +- .../listener/AbstractGameEventListener.java | 4 +- .../baritone/api/pathing/goals/GoalBlock.java | 8 +- .../api/pathing/goals/GoalGetToBlock.java | 8 +- .../api/pathing/goals/GoalInverted.java | 2 +- .../baritone/api/pathing/goals/GoalNear.java | 10 +- .../api/pathing/goals/GoalRunAway.java | 6 +- .../pathing/goals/GoalStrictDirection.java | 12 +- .../api/pathing/goals/GoalTwoBlocks.java | 8 +- .../baritone/api/pathing/goals/GoalXZ.java | 6 +- .../api/pathing/goals/GoalYLevel.java | 4 +- .../baritone/api/process/IMineProcess.java | 6 +- .../api/schematic/CompositeSchematic.java | 2 +- .../baritone/api/selection/ISelection.java | 2 +- .../api/selection/ISelectionManager.java | 2 +- .../baritone/api/utils/BetterBlockPos.java | 8 +- .../api/utils/BlockOptionalMetaLookup.java | 16 +- .../java/baritone/api/utils/SettingsUtil.java | 4 +- .../helpers/arguments/ArgConsumer.java | 36 ++-- .../tabcomplete/TabCompleteHelper.java | 14 +- .../launch/mixins/MixinChatTabCompleter.java | 10 +- .../baritone/launch/mixins/MixinGuiChat.java | 6 +- .../launch/mixins/MixinItemStack.java | 8 +- .../mixins/MixinStateImplementation.java | 10 +- .../launch/mixins/MixinTabCompleter.java | 7 +- src/main/java/baritone/Baritone.java | 3 - .../baritone/behavior/InventoryBehavior.java | 1 - .../baritone/behavior/PathingBehavior.java | 10 +- src/main/java/baritone/cache/ChunkPacker.java | 3 +- .../baritone/cache/WaypointCollection.java | 1 - .../java/baritone/cache/WorldScanner.java | 10 +- .../java/baritone/process/FollowProcess.java | 11 +- .../baritone/process/GetToBlockProcess.java | 5 +- .../java/baritone/selection/Selection.java | 20 +- src/main/java/baritone/utils/IRenderer.java | 2 +- .../java/baritone/utils/PathRenderer.java | 2 +- src/main/java/baritone/utils/ToolSet.java | 2 +- .../utils/command/defaults/AxisCommand.java | 8 +- .../command/defaults/BlacklistCommand.java | 8 +- .../utils/command/defaults/BuildCommand.java | 10 +- .../utils/command/defaults/CancelCommand.java | 8 +- .../utils/command/defaults/ChestsCommand.java | 10 +- .../command/defaults/ClearareaCommand.java | 10 +- .../utils/command/defaults/ClickCommand.java | 8 +- .../utils/command/defaults/ComeCommand.java | 12 +- .../command/defaults/DefaultCommands.java | 78 ++++---- .../utils/command/defaults/EmptyCommand.java | 8 +- .../command/defaults/ExploreCommand.java | 14 +- .../defaults/ExploreFilterCommand.java | 16 +- .../utils/command/defaults/FarmCommand.java | 8 +- .../utils/command/defaults/FindCommand.java | 32 +-- .../utils/command/defaults/FollowCommand.java | 40 ++-- .../command/defaults/ForceCancelCommand.java | 8 +- .../utils/command/defaults/GcCommand.java | 8 +- .../utils/command/defaults/GoalCommand.java | 20 +- .../utils/command/defaults/HelpCommand.java | 70 +++---- .../utils/command/defaults/InvertCommand.java | 8 +- .../utils/command/defaults/MineCommand.java | 20 +- .../utils/command/defaults/PathCommand.java | 20 +- .../command/defaults/PauseResumeCommands.java | 76 ++++---- .../utils/command/defaults/ProcCommand.java | 38 ++-- .../command/defaults/ReloadAllCommand.java | 8 +- .../utils/command/defaults/RenderCommand.java | 20 +- .../utils/command/defaults/RepackCommand.java | 8 +- .../command/defaults/SaveAllCommand.java | 8 +- .../command/defaults/SchematicaCommand.java | 8 +- .../utils/command/defaults/SelCommand.java | 84 ++++---- .../utils/command/defaults/SetCommand.java | 154 +++++++-------- .../command/defaults/ThisWayCommand.java | 14 +- .../utils/command/defaults/TunnelCommand.java | 12 +- .../command/defaults/VersionCommand.java | 8 +- .../command/defaults/WaypointsCommand.java | 184 +++++++++--------- .../schematica/SchematicAdapter.java | 1 - .../schematica/SchematicaHelper.java | 2 +- .../client/world/SchematicWorld.java | 2 +- 77 files changed, 658 insertions(+), 683 deletions(-) diff --git a/src/api/java/baritone/api/cache/IWaypoint.java b/src/api/java/baritone/api/cache/IWaypoint.java index 238b4d88..4c086ba2 100644 --- a/src/api/java/baritone/api/cache/IWaypoint.java +++ b/src/api/java/baritone/api/cache/IWaypoint.java @@ -19,11 +19,7 @@ package baritone.api.cache; import baritone.api.utils.BetterBlockPos; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import static java.util.Arrays.asList; diff --git a/src/api/java/baritone/api/cache/Waypoint.java b/src/api/java/baritone/api/cache/Waypoint.java index f126de38..9c4fbfbf 100644 --- a/src/api/java/baritone/api/cache/Waypoint.java +++ b/src/api/java/baritone/api/cache/Waypoint.java @@ -18,7 +18,6 @@ package baritone.api.cache; import baritone.api.utils.BetterBlockPos; -import net.minecraft.util.math.BlockPos; import java.util.Date; @@ -82,10 +81,10 @@ public class Waypoint implements IWaypoint { @Override public String toString() { return String.format( - "%s %s %s", - name, - BetterBlockPos.from(location).toString(), - new Date(creationTimestamp).toString() + "%s %s %s", + name, + BetterBlockPos.from(location).toString(), + new Date(creationTimestamp).toString() ); } diff --git a/src/api/java/baritone/api/event/events/type/Overrideable.java b/src/api/java/baritone/api/event/events/type/Overrideable.java index 7690ee8f..1ce7934e 100644 --- a/src/api/java/baritone/api/event/events/type/Overrideable.java +++ b/src/api/java/baritone/api/event/events/type/Overrideable.java @@ -44,9 +44,9 @@ public class Overrideable { @Override public String toString() { return String.format( - "Overrideable{modified=%b,value=%s}", - modified, - value.toString() + "Overrideable{modified=%b,value=%s}", + modified, + value.toString() ); } } diff --git a/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java b/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java index 9e5b6dbb..e7d4dc29 100644 --- a/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java +++ b/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java @@ -40,10 +40,10 @@ public interface AbstractGameEventListener extends IGameEventListener { default void onSendChatMessage(ChatEvent event) {} @Override - default void onPreTabComplete(TabCompleteEvent.Pre event) {}; + default void onPreTabComplete(TabCompleteEvent.Pre event) {} @Override - default void onPostTabComplete(TabCompleteEvent.Post event) {}; + default void onPostTabComplete(TabCompleteEvent.Post event) {} @Override default void onChunkEvent(ChunkEvent event) {} diff --git a/src/api/java/baritone/api/pathing/goals/GoalBlock.java b/src/api/java/baritone/api/pathing/goals/GoalBlock.java index 836b47df..c85e5cad 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalBlock.java @@ -69,10 +69,10 @@ public class GoalBlock implements Goal, IGoalRenderPos { @Override public String toString() { return String.format( - "GoalBlock{x=%s,y=%s,z=%s}", - SettingsUtil.maybeCensor(x), - SettingsUtil.maybeCensor(y), - SettingsUtil.maybeCensor(z) + "GoalBlock{x=%s,y=%s,z=%s}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) ); } diff --git a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java index 7fe64a4f..8d6fdcb3 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java @@ -63,10 +63,10 @@ public class GoalGetToBlock implements Goal, IGoalRenderPos { @Override public String toString() { return String.format( - "GoalGetToBlock{x=%s,y=%s,z=%s}", - SettingsUtil.maybeCensor(x), - SettingsUtil.maybeCensor(y), - SettingsUtil.maybeCensor(z) + "GoalGetToBlock{x=%s,y=%s,z=%s}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalInverted.java b/src/api/java/baritone/api/pathing/goals/GoalInverted.java index 7f072c4d..9f793a41 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalInverted.java +++ b/src/api/java/baritone/api/pathing/goals/GoalInverted.java @@ -19,7 +19,7 @@ package baritone.api.pathing.goals; /** * Invert any goal. - * + *

* In the old chat control system, #invert just tried to pick a {@link GoalRunAway} that effectively inverted the * current goal. This goal just reverses the heuristic to act as a TRUE invert. Inverting a Y level? Baritone tries to * get away from that Y level. Inverting a GoalBlock? Baritone will try to make distance whether it's in the X, Y or Z diff --git a/src/api/java/baritone/api/pathing/goals/GoalNear.java b/src/api/java/baritone/api/pathing/goals/GoalNear.java index 1482b904..78f3b5f6 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalNear.java +++ b/src/api/java/baritone/api/pathing/goals/GoalNear.java @@ -58,11 +58,11 @@ public class GoalNear implements Goal, IGoalRenderPos { @Override public String toString() { return String.format( - "GoalNear{x=%s, y=%s, z=%s, rangeSq=%d}", - SettingsUtil.maybeCensor(x), - SettingsUtil.maybeCensor(y), - SettingsUtil.maybeCensor(z), - rangeSq + "GoalNear{x=%s, y=%s, z=%s, rangeSq=%d}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z), + rangeSq ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index fa9c29fc..a1a15378 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -84,9 +84,9 @@ public class GoalRunAway implements Goal { public String toString() { if (maintainY != null) { return String.format( - "GoalRunAwayFromMaintainY y=%s, %s", - SettingsUtil.maybeCensor(maintainY), - Arrays.asList(from) + "GoalRunAwayFromMaintainY y=%s, %s", + SettingsUtil.maybeCensor(maintainY), + Arrays.asList(from) ); } else { return "GoalRunAwayFrom" + Arrays.asList(from); diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java index 3f14bf24..1f2efd05 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java +++ b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java @@ -66,12 +66,12 @@ public class GoalStrictDirection implements Goal { @Override public String toString() { return String.format( - "GoalStrictDirection{x=%s, y=%s, z=%s, dx=%s, dz=%s}", - SettingsUtil.maybeCensor(x), - SettingsUtil.maybeCensor(y), - SettingsUtil.maybeCensor(z), - SettingsUtil.maybeCensor(dx), - SettingsUtil.maybeCensor(dz) + "GoalStrictDirection{x=%s, y=%s, z=%s, dx=%s, dz=%s}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z), + SettingsUtil.maybeCensor(dx), + SettingsUtil.maybeCensor(dz) ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java index 52286dd0..27be981e 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java +++ b/src/api/java/baritone/api/pathing/goals/GoalTwoBlocks.java @@ -75,10 +75,10 @@ public class GoalTwoBlocks implements Goal, IGoalRenderPos { @Override public String toString() { return String.format( - "GoalTwoBlocks{x=%s,y=%s,z=%s}", - SettingsUtil.maybeCensor(x), - SettingsUtil.maybeCensor(y), - SettingsUtil.maybeCensor(z) + "GoalTwoBlocks{x=%s,y=%s,z=%s}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) ); } } diff --git a/src/api/java/baritone/api/pathing/goals/GoalXZ.java b/src/api/java/baritone/api/pathing/goals/GoalXZ.java index 53ef3ccf..63d39cd7 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalXZ.java +++ b/src/api/java/baritone/api/pathing/goals/GoalXZ.java @@ -67,9 +67,9 @@ public class GoalXZ implements Goal { @Override public String toString() { return String.format( - "GoalXZ{x=%s,z=%s}", - SettingsUtil.maybeCensor(x), - SettingsUtil.maybeCensor(z) + "GoalXZ{x=%s,z=%s}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(z) ); } diff --git a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java index 84b4cefe..603ef9bd 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalYLevel.java +++ b/src/api/java/baritone/api/pathing/goals/GoalYLevel.java @@ -61,8 +61,8 @@ public class GoalYLevel implements Goal, ActionCosts { @Override public String toString() { return String.format( - "GoalYLevel{y=%s}", - SettingsUtil.maybeCensor(level) + "GoalYLevel{y=%s}", + SettingsUtil.maybeCensor(level) ); } } diff --git a/src/api/java/baritone/api/process/IMineProcess.java b/src/api/java/baritone/api/process/IMineProcess.java index aa01aa5a..455e93ca 100644 --- a/src/api/java/baritone/api/process/IMineProcess.java +++ b/src/api/java/baritone/api/process/IMineProcess.java @@ -92,9 +92,9 @@ public interface IMineProcess extends IBaritoneProcess { */ default void mine(int quantity, Block... blocks) { mine(quantity, new BlockOptionalMetaLookup( - Arrays.stream(blocks) - .map(BlockOptionalMeta::new) - .toArray(BlockOptionalMeta[]::new) + Arrays.stream(blocks) + .map(BlockOptionalMeta::new) + .toArray(BlockOptionalMeta[]::new) )); } diff --git a/src/api/java/baritone/api/schematic/CompositeSchematic.java b/src/api/java/baritone/api/schematic/CompositeSchematic.java index ecb0dd70..9d65d9d3 100644 --- a/src/api/java/baritone/api/schematic/CompositeSchematic.java +++ b/src/api/java/baritone/api/schematic/CompositeSchematic.java @@ -51,7 +51,7 @@ public class CompositeSchematic extends AbstractSchematic { private CompositeSchematicEntry getSchematic(int x, int y, int z, IBlockState currentState) { for (CompositeSchematicEntry entry : schematicArr) { if (x >= entry.x && y >= entry.y && z >= entry.z && - entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState)) { + entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState)) { return entry; } } diff --git a/src/api/java/baritone/api/selection/ISelection.java b/src/api/java/baritone/api/selection/ISelection.java index 4771c2e9..5a5690d9 100644 --- a/src/api/java/baritone/api/selection/ISelection.java +++ b/src/api/java/baritone/api/selection/ISelection.java @@ -68,7 +68,7 @@ public interface ISelection { /** * Returns a new {@link ISelection} contracted in the specified direction by the specified number of blocks. - * + *

* Note that, for example, if the direction specified is UP, the bottom of the selection will be shifted up. If it * is DOWN, the top of the selection will be shifted down. * diff --git a/src/api/java/baritone/api/selection/ISelectionManager.java b/src/api/java/baritone/api/selection/ISelectionManager.java index e69549f9..a078e6d1 100644 --- a/src/api/java/baritone/api/selection/ISelectionManager.java +++ b/src/api/java/baritone/api/selection/ISelectionManager.java @@ -91,7 +91,7 @@ public interface ISelectionManager { /** * Replaces the specified {@link ISelection} with one contracted in the specified direction by the specified number * of blocks. - * + *

* Note that, for example, if the direction specified is UP, the bottom of the selection will be shifted up. If it * is DOWN, the top of the selection will be shifted down. * diff --git a/src/api/java/baritone/api/utils/BetterBlockPos.java b/src/api/java/baritone/api/utils/BetterBlockPos.java index 6a462d0c..40122a86 100644 --- a/src/api/java/baritone/api/utils/BetterBlockPos.java +++ b/src/api/java/baritone/api/utils/BetterBlockPos.java @@ -203,10 +203,10 @@ public final class BetterBlockPos extends BlockPos { @Nonnull public String toString() { return String.format( - "BetterBlockPos{x=%s,y=%s,z=%s}", - SettingsUtil.maybeCensor(x), - SettingsUtil.maybeCensor(y), - SettingsUtil.maybeCensor(z) + "BetterBlockPos{x=%s,y=%s,z=%s}", + SettingsUtil.maybeCensor(x), + SettingsUtil.maybeCensor(y), + SettingsUtil.maybeCensor(z) ); } } diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index 963d147c..fe1c5e6a 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -35,20 +35,20 @@ public class BlockOptionalMetaLookup { public BlockOptionalMetaLookup(Block... blocks) { this.boms = Arrays.stream(blocks) - .map(BlockOptionalMeta::new) - .toArray(BlockOptionalMeta[]::new); + .map(BlockOptionalMeta::new) + .toArray(BlockOptionalMeta[]::new); } public BlockOptionalMetaLookup(List blocks) { this.boms = blocks.stream() - .map(BlockOptionalMeta::new) - .toArray(BlockOptionalMeta[]::new); + .map(BlockOptionalMeta::new) + .toArray(BlockOptionalMeta[]::new); } public BlockOptionalMetaLookup(String... blocks) { this.boms = Arrays.stream(blocks) - .map(BlockOptionalMeta::new) - .toArray(BlockOptionalMeta[]::new); + .map(BlockOptionalMeta::new) + .toArray(BlockOptionalMeta[]::new); } public boolean has(Block block) { @@ -88,8 +88,8 @@ public class BlockOptionalMetaLookup { @Override public String toString() { return String.format( - "BlockOptionalMetaLookup{%s}", - Arrays.toString(boms) + "BlockOptionalMetaLookup{%s}", + Arrays.toString(boms) ); } } diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 5c8ab83f..0035f2ea 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -123,7 +123,7 @@ public class SettingsUtil { /** * Gets the type of a setting and returns it as a string, with package names stripped. - * + *

* For example, if the setting type is {@code java.util.List}, this function returns * {@code List}. * @@ -132,7 +132,7 @@ public class SettingsUtil { */ public static String settingTypeToString(Settings.Setting setting) { return setting.getType().getTypeName() - .replaceAll("(?:\\w+\\.)+(\\w+)", "$1"); + .replaceAll("(?:\\w+\\.)+(\\w+)", "$1"); } public static String settingValueToString(Settings.Setting setting, T value) throws IllegalArgumentException { diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index a0c1f793..201076c7 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -39,19 +39,19 @@ import java.util.stream.Stream; * The {@link ArgConsumer} is how {@link Command}s read the arguments passed to them. This class has many benefits: * *

    - *
  • Mutability. The whole concept of the {@link ArgConsumer} is to let you gradually consume arguments in any way - * you'd like. You can change your consumption based on earlier arguments, for subcommands for example.
  • - *
  • You don't need to keep track of your consumption. The {@link ArgConsumer} keeps track of the arguments you - * consume so that it can throw detailed exceptions whenever something is out of the ordinary. Additionally, if you - * need to retrieve an argument after you've already consumed it - look no further than {@link #consumed()}!
  • - *
  • Easy retrieval of many different types. If you need to retrieve an instance of an int or float for example, - * look no further than {@link #getAs(Class)}. If you need a more powerful way of retrieving data, try out the many - * {@link #getDatatype(Class)} methods.
  • - *
  • It's very easy to throw detailed exceptions. The {@link ArgConsumer} has many different methods that can - * enforce the number of arguments, the type of arguments, and more, throwing different types of - * {@link CommandException}s if something seems off. You're recommended to do all validation and store all needed - * data in variables BEFORE logging any data to chat via {@link Helper#logDirect(String)}, so that the error - * handlers can do their job and log the error to chat.
  • + *
  • Mutability. The whole concept of the {@link ArgConsumer} is to let you gradually consume arguments in any way + * you'd like. You can change your consumption based on earlier arguments, for subcommands for example.
  • + *
  • You don't need to keep track of your consumption. The {@link ArgConsumer} keeps track of the arguments you + * consume so that it can throw detailed exceptions whenever something is out of the ordinary. Additionally, if you + * need to retrieve an argument after you've already consumed it - look no further than {@link #consumed()}!
  • + *
  • Easy retrieval of many different types. If you need to retrieve an instance of an int or float for example, + * look no further than {@link #getAs(Class)}. If you need a more powerful way of retrieving data, try out the many + * {@link #getDatatype(Class)} methods.
  • + *
  • It's very easy to throw detailed exceptions. The {@link ArgConsumer} has many different methods that can + * enforce the number of arguments, the type of arguments, and more, throwing different types of + * {@link CommandException}s if something seems off. You're recommended to do all validation and store all needed + * data in variables BEFORE logging any data to chat via {@link Helper#logDirect(String)}, so that the error + * handlers can do their job and log the error to chat.
  • *
*/ public class ArgConsumer implements Cloneable { @@ -913,11 +913,11 @@ public class ArgConsumer implements Cloneable { * into three {@link CommandArgument}s {@code "arg1"}, {@code "arg2"}, and {@code "arg3"}: * *
    - *
  • {@code rawRest()} would return arg1 arg2  arg3
  • - *
  • After calling {@link #get()}, {@code rawRest()} would return arg2  arg3 (note the - * double space - it is preserved!)
  • - *
  • After calling {@link #get()} again, {@code rawRest()} would return {@code "arg3"}
  • - *
  • After calling {@link #get()} one last time, {@code rawRest()} would return {@code ""}
  • + *
  • {@code rawRest()} would return arg1 arg2  arg3
  • + *
  • After calling {@link #get()}, {@code rawRest()} would return arg2  arg3 (note the + * double space - it is preserved!)
  • + *
  • After calling {@link #get()} again, {@code rawRest()} would return {@code "arg3"}
  • + *
  • After calling {@link #get()} one last time, {@code rawRest()} would return {@code ""}
  • *
* * @return The "raw rest" of the string. diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index 2878b8df..1c60c085 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -40,13 +40,13 @@ import java.util.stream.Stream; *

* The recommended way to use this class is: *

    - *
  • Create a new instance with the empty constructor
  • - *
  • Use {@code append}, {@code prepend} or {@code add} methods to add completions
  • - *
  • Sort using {@link #sort(Comparator)} or {@link #sortAlphabetically()} and then filter by prefix using - * {@link #filterPrefix(String)}
  • - *
  • Get the stream using {@link #stream()}
  • - *
  • Pass it up to whatever's calling your tab complete function (i.e. - * {@link CommandManager#tabComplete(CommandExecution)} or {@link ArgConsumer#tabCompleteDatatype(Class)})
  • + *
  • Create a new instance with the empty constructor
  • + *
  • Use {@code append}, {@code prepend} or {@code add} methods to add completions
  • + *
  • Sort using {@link #sort(Comparator)} or {@link #sortAlphabetically()} and then filter by prefix using + * {@link #filterPrefix(String)}
  • + *
  • Get the stream using {@link #stream()}
  • + *
  • Pass it up to whatever's calling your tab complete function (i.e. + * {@link CommandManager#tabComplete(CommandExecution)} or {@link ArgConsumer#tabCompleteDatatype(Class)})
  • *
*

* For advanced users: if you're intercepting {@link TabCompleteEvent}s directly, use {@link #build()} instead for an diff --git a/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java index 1cbf32e7..3d56446c 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java +++ b/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java @@ -26,17 +26,17 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(GuiChat.ChatTabCompleter.class) public abstract class MixinChatTabCompleter extends MixinTabCompleter { @Inject( - method = "*", - at = @At("RETURN") + method = "*", + at = @At("RETURN") ) private void onConstruction(CallbackInfo ci) { isChatCompleter = true; } @Inject( - method = "complete", - at = @At("HEAD"), - cancellable = true + method = "complete", + at = @At("HEAD"), + cancellable = true ) private void onComplete(CallbackInfo ci) { if (dontComplete) { diff --git a/src/launch/java/baritone/launch/mixins/MixinGuiChat.java b/src/launch/java/baritone/launch/mixins/MixinGuiChat.java index 86f2b1b0..8c0a7d63 100644 --- a/src/launch/java/baritone/launch/mixins/MixinGuiChat.java +++ b/src/launch/java/baritone/launch/mixins/MixinGuiChat.java @@ -32,9 +32,9 @@ public abstract class MixinGuiChat implements net.minecraft.util.ITabCompleter { private TabCompleter tabCompleter; @Inject( - method = "setCompletions", - at = @At("HEAD"), - cancellable = true + method = "setCompletions", + at = @At("HEAD"), + cancellable = true ) private void onSetCompletions(String[] newCompl, CallbackInfo ci) { if (((ITabCompleter) tabCompleter).onGuiChatSetCompletions(newCompl)) { diff --git a/src/launch/java/baritone/launch/mixins/MixinItemStack.java b/src/launch/java/baritone/launch/mixins/MixinItemStack.java index 03f5e25f..2a690632 100644 --- a/src/launch/java/baritone/launch/mixins/MixinItemStack.java +++ b/src/launch/java/baritone/launch/mixins/MixinItemStack.java @@ -45,16 +45,16 @@ public abstract class MixinItemStack implements IItemStack { } @Inject( - method = "*", - at = @At("RETURN") + method = "*", + at = @At("RETURN") ) private void onInit(CallbackInfo ci) { recalculateHash(); } @Inject( - method = "setItemDamage", - at = @At("TAIL") + method = "setItemDamage", + at = @At("TAIL") ) private void onItemDamageSet(CallbackInfo ci) { recalculateHash(); diff --git a/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java b/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java index de74a4db..ea437084 100644 --- a/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java +++ b/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java @@ -19,11 +19,7 @@ package baritone.launch.mixins; import com.google.common.collect.ImmutableMap; import net.minecraft.block.properties.IProperty; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -41,8 +37,8 @@ public abstract class MixinStateImplementation { private int hashCode; @Inject( - method = "*", - at = @At("RETURN") + method = "*", + at = @At("RETURN") ) private void onInit(CallbackInfo ci) { hashCode = properties.hashCode(); diff --git a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java index b07dd9d0..4432505b 100644 --- a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java +++ b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java @@ -21,7 +21,6 @@ import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.event.events.TabCompleteEvent; import baritone.utils.accessor.ITabCompleter; -import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiTextField; import net.minecraft.util.TabCompleter; import org.spongepowered.asm.mixin.Final; @@ -64,9 +63,9 @@ public abstract class MixinTabCompleter implements ITabCompleter { } @Inject( - method = "requestCompletions", - at = @At("HEAD"), - cancellable = true + method = "requestCompletions", + at = @At("HEAD"), + cancellable = true ) private void onRequestCompletions(String prefix, CallbackInfo ci) { if (!isChatCompleter) { diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 7f70bbea..aa787e10 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -21,17 +21,14 @@ import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.event.listener.IEventBus; -import baritone.api.utils.command.BaritoneChatControl; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; -import baritone.api.utils.command.manager.CommandManager; import baritone.behavior.*; import baritone.cache.WorldProvider; import baritone.event.GameEventHandler; import baritone.process.*; import baritone.selection.SelectionManager; import baritone.utils.*; -import baritone.utils.command.defaults.DefaultCommands; import baritone.utils.player.PrimaryPlayerContext; import net.minecraft.client.Minecraft; diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index c278738a..484efa19 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -28,7 +28,6 @@ import net.minecraft.inventory.ClickType; import net.minecraft.item.*; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; -import net.minecraft.util.math.BlockPos; import java.util.ArrayList; import java.util.OptionalInt; diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index c3aa2ad9..86fd9505 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -19,11 +19,7 @@ package baritone.behavior; import baritone.Baritone; import baritone.api.behavior.IPathingBehavior; -import baritone.api.event.events.PathEvent; -import baritone.api.event.events.PlayerUpdateEvent; -import baritone.api.event.events.RenderEvent; -import baritone.api.event.events.SprintStateEvent; -import baritone.api.event.events.TickEvent; +import baritone.api.event.events.*; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; @@ -137,8 +133,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, BetterBlockPos calcFrom = inProgress.getStart(); Optional currentBest = inProgress.bestPathSoFar(); if ((current == null || !current.getPath().getDest().equals(calcFrom)) // if current ends in inProgress's start, then we're ok - && !calcFrom.equals(ctx.playerFeet()) && !calcFrom.equals(expectedSegmentStart) // if current starts in our playerFeet or pathStart, then we're ok - && (!currentBest.isPresent() || (!currentBest.get().positions().contains(ctx.playerFeet()) && !currentBest.get().positions().contains(expectedSegmentStart))) // if + && !calcFrom.equals(ctx.playerFeet()) && !calcFrom.equals(expectedSegmentStart) // if current starts in our playerFeet or pathStart, then we're ok + && (!currentBest.isPresent() || (!currentBest.get().positions().contains(ctx.playerFeet()) && !currentBest.get().positions().contains(expectedSegmentStart))) // if ) { // when it was *just* started, currentBest will be empty so we need to also check calcFrom since that's always present inProgress.cancel(); // cancellation doesn't dispatch any events diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index 864f23d6..9b754869 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -88,7 +88,8 @@ public final class ChunkPacker { IBlockState[] blocks = new IBlockState[256]; for (int z = 0; z < 16; z++) { - https://www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html + https: +//www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html for (int x = 0; x < 16; x++) { for (int y = 255; y >= 0; y--) { int index = CachedChunk.getPositionIndex(x, y, z); diff --git a/src/main/java/baritone/cache/WaypointCollection.java b/src/main/java/baritone/cache/WaypointCollection.java index 448dddd3..222adfdf 100644 --- a/src/main/java/baritone/cache/WaypointCollection.java +++ b/src/main/java/baritone/cache/WaypointCollection.java @@ -21,7 +21,6 @@ import baritone.api.cache.IWaypoint; import baritone.api.cache.IWaypointCollection; import baritone.api.cache.Waypoint; import baritone.api.utils.BetterBlockPos; -import net.minecraft.util.math.BlockPos; import java.io.*; import java.nio.file.Files; diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index 458e7afe..de9e6fe9 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -31,11 +31,7 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; +import java.util.*; import java.util.stream.IntStream; import static java.util.Objects.nonNull; @@ -89,8 +85,8 @@ public enum WorldScanner implements IWorldScanner { } } if ((allUnloaded && foundChunks) - || (res.size() >= max - && (searchRadiusSq > maxSearchRadiusSq || (searchRadiusSq > 1 && foundWithinY))) + || (res.size() >= max + && (searchRadiusSq > maxSearchRadiusSq || (searchRadiusSq > 1 && foundWithinY))) ) { return res; } diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 3c0ef0a2..af30b25d 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -29,7 +29,6 @@ import baritone.utils.BaritoneProcessHelper; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; -import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -83,11 +82,11 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo private void scanWorld() { cache = Stream.of(ctx.world().loadedEntityList, ctx.world().playerEntities) - .flatMap(List::stream) - .filter(this::followable) - .filter(this.filter) - .distinct() - .collect(Collectors.toList()); + .flatMap(List::stream) + .filter(this::followable) + .filter(this.filter) + .distinct() + .collect(Collectors.toList()); } @Override diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index c891f109..5c1d7783 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -33,7 +33,10 @@ import net.minecraft.init.Blocks; import net.minecraft.inventory.ContainerPlayer; import net.minecraft.util.math.BlockPos; -import java.util.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; public final class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess { diff --git a/src/main/java/baritone/selection/Selection.java b/src/main/java/baritone/selection/Selection.java index 3b385503..594c037f 100644 --- a/src/main/java/baritone/selection/Selection.java +++ b/src/main/java/baritone/selection/Selection.java @@ -19,21 +19,21 @@ public class Selection implements ISelection { this.pos2 = pos2; this.min = new BetterBlockPos( - Math.min(pos1.x, pos2.x), - Math.min(pos1.y, pos2.y), - Math.min(pos1.z, pos2.z) + Math.min(pos1.x, pos2.x), + Math.min(pos1.y, pos2.y), + Math.min(pos1.z, pos2.z) ); this.max = new BetterBlockPos( - Math.max(pos1.x, pos2.x), - Math.max(pos1.y, pos2.y), - Math.max(pos1.z, pos2.z) + Math.max(pos1.x, pos2.x), + Math.max(pos1.y, pos2.y), + Math.max(pos1.z, pos2.z) ); this.size = new Vec3i( - max.x - min.x + 1, - max.y - min.y + 1, - max.z - min.z + 1 + max.x - min.x + 1, + max.y - min.y + 1, + max.z - min.z + 1 ); this.aabb = new AxisAlignedBB(this.min, this.max.add(1, 1, 1)); @@ -81,7 +81,7 @@ public class Selection implements ISelection { /** * Since it might not be immediately obvious what this does, let me explain. - * + *

* Let's say you specify EnumFacing.UP, this functions returns if pos2 is the highest BlockPos. * If you specify EnumFacing.DOWN, it returns if pos2 is the lowest BlockPos. * diff --git a/src/main/java/baritone/utils/IRenderer.java b/src/main/java/baritone/utils/IRenderer.java index 2de47ed7..f08d0c39 100644 --- a/src/main/java/baritone/utils/IRenderer.java +++ b/src/main/java/baritone/utils/IRenderer.java @@ -28,7 +28,7 @@ import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.math.AxisAlignedBB; -import java.awt.Color; +import java.awt.*; import static org.lwjgl.opengl.GL11.*; diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 58917436..6e262213 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -36,7 +36,7 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; -import java.awt.Color; +import java.awt.*; import java.util.Collection; import java.util.Collections; import java.util.List; diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 860f0577..2df2261a 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -118,7 +118,7 @@ public class ToolSet { } else if (speed == highestSpeed) { int cost = getMaterialCost(itemStack); if ((cost < lowestCost && (silkTouch || !bestSilkTouch)) || - (preferSilkTouch && !bestSilkTouch && silkTouch)) { + (preferSilkTouch && !bestSilkTouch && silkTouch)) { highestSpeed = speed; best = i; lowestCost = cost; diff --git a/src/main/java/baritone/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java index 794af0c5..32c36d15 100644 --- a/src/main/java/baritone/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -54,10 +54,10 @@ public class AxisCommand extends Command { @Override public List getLongDesc() { return asList( - "The axis command sets a goal that tells Baritone to head towards the nearest axis. That is, X=0 or Z=0.", - "", - "Usage:", - "> axis" + "The axis command sets a goal that tells Baritone to head towards the nearest axis. That is, X=0 or Z=0.", + "", + "Usage:", + "> axis" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index 1152ee08..926847f9 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -62,10 +62,10 @@ public class BlacklistCommand extends Command { @Override public List getLongDesc() { return asList( - "While, for example, mining, this command blacklists the closest block so that Baritone won't attempt to get to it.", - "", - "Usage:", - "> blacklist" + "While, for example, mining, this command blacklists the closest block so that Baritone won't attempt to get to it.", + "", + "Usage:", + "> blacklist" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index dd789ccb..ac99b341 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -89,11 +89,11 @@ public class BuildCommand extends Command { @Override public List getLongDesc() { return asList( - "Build a schematic from a file.", - "", - "Usage:", - "> build - Loads and builds '.schematic'", - "> build - Custom position" + "Build a schematic from a file.", + "", + "Usage:", + "> build - Loads and builds '.schematic'", + "> build - Custom position" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index 49fdc537..3b45b5ab 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -51,10 +51,10 @@ public class CancelCommand extends Command { @Override public List getLongDesc() { return asList( - "The cancel command tells Baritons to stop whatever it's currently doing.", - "", - "Usage:", - "> cancel" + "The cancel command tells Baritons to stop whatever it's currently doing.", + "", + "Usage:", + "> cancel" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index 72e07da1..6d436cc7 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -43,7 +43,7 @@ public class ChestsCommand extends Command { protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); Set> entries = - ctx.worldData().getContainerMemory().getRememberedInventories().entrySet(); + ctx.worldData().getContainerMemory().getRememberedInventories().entrySet(); if (entries.isEmpty()) { throw new CommandInvalidStateException("No remembered inventories"); @@ -77,10 +77,10 @@ public class ChestsCommand extends Command { @Override public List getLongDesc() { return asList( - "The chests command lists remembered inventories, I guess?", - "", - "Usage:", - "> chests" + "The chests command lists remembered inventories, I guess?", + "", + "Usage:", + "> chests" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index 68fc547e..0f210234 100644 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -73,11 +73,11 @@ public class ClearareaCommand extends Command { @Override public List getLongDesc() { return asList( - "Clear an area of all blocks.", - "", - "Usage:", - "> cleararea - Clears the area marked by your current position and the current GoalBlock", - "> cleararea - Custom second corner rather than your goal" + "Clear an area of all blocks.", + "", + "Usage:", + "> cleararea - Clears the area marked by your current position and the current GoalBlock", + "> cleararea - Custom second corner rather than your goal" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java index 494ae8f7..8f2a3c8f 100644 --- a/src/main/java/baritone/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -51,10 +51,10 @@ public class ClickCommand extends Command { @Override public List getLongDesc() { return asList( - "Opens click dude", - "", - "Usage:", - "> click" + "Opens click dude", + "", + "Usage:", + "> click" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index cfbf1f46..ad823300 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -62,12 +62,12 @@ public class ComeCommand extends Command { @Override public List getLongDesc() { return asList( - "The come command tells Baritone to head towards your camera.", - "", - "This can be useful in hacked clients where freecam doesn't move your player position.", - "", - "Usage:", - "> come" + "The come command tells Baritone to head towards your camera.", + "", + "This can be useful in hacked clients where freecam doesn't move your player position.", + "", + "Usage:", + "> come" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java index 213bd393..9e65e10c 100644 --- a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java +++ b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java @@ -26,44 +26,44 @@ import static java.util.Arrays.asList; public class DefaultCommands { public static final List COMMANDS = Collections.unmodifiableList(asList( - new HelpCommand(), - new SetCommand(), - new CommandAlias(asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), - new CommandAlias("reset", "Reset all settings or just one", "set reset"), - new GoalCommand(), - new PathCommand(), - new ProcCommand(), - new VersionCommand(), - new RepackCommand(), - new BuildCommand(), - new SchematicaCommand(), - new ComeCommand(), - new AxisCommand(), - new CancelCommand(), - new ForceCancelCommand(), - new GcCommand(), - new InvertCommand(), - new ClearareaCommand(), - PauseResumeCommands.pauseCommand, - PauseResumeCommands.resumeCommand, - PauseResumeCommands.pausedCommand, - new TunnelCommand(), - new RenderCommand(), - new FarmCommand(), - new ChestsCommand(), - new FollowCommand(), - new ExploreFilterCommand(), - new ReloadAllCommand(), - new SaveAllCommand(), - new ExploreCommand(), - new BlacklistCommand(), - new FindCommand(), - new MineCommand(), - new ClickCommand(), - new ThisWayCommand(), - new WaypointsCommand(), - new CommandAlias("sethome", "Sets your home waypoint", "waypoints save home"), - new CommandAlias("home", "Set goal to your home waypoint", "waypoints goal home"), - new SelCommand() + new HelpCommand(), + new SetCommand(), + new CommandAlias(asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), + new CommandAlias("reset", "Reset all settings or just one", "set reset"), + new GoalCommand(), + new PathCommand(), + new ProcCommand(), + new VersionCommand(), + new RepackCommand(), + new BuildCommand(), + new SchematicaCommand(), + new ComeCommand(), + new AxisCommand(), + new CancelCommand(), + new ForceCancelCommand(), + new GcCommand(), + new InvertCommand(), + new ClearareaCommand(), + PauseResumeCommands.pauseCommand, + PauseResumeCommands.resumeCommand, + PauseResumeCommands.pausedCommand, + new TunnelCommand(), + new RenderCommand(), + new FarmCommand(), + new ChestsCommand(), + new FollowCommand(), + new ExploreFilterCommand(), + new ReloadAllCommand(), + new SaveAllCommand(), + new ExploreCommand(), + new BlacklistCommand(), + new FindCommand(), + new MineCommand(), + new ClickCommand(), + new ThisWayCommand(), + new WaypointsCommand(), + new CommandAlias("sethome", "Sets your home waypoint", "waypoints save home"), + new CommandAlias("home", "Set goal to your home waypoint", "waypoints goal home"), + new SelCommand() )); } diff --git a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java index 9298f32a..3a6f46e4 100644 --- a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java +++ b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java @@ -49,10 +49,10 @@ public class EmptyCommand extends Command { @Override public List getLongDesc() { return asList( - "", - "", - "Usage:", - "> " + "", + "", + "Usage:", + "> " ); } } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index c0925342..2cc328d7 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -42,8 +42,8 @@ public class ExploreCommand extends Command { } GoalXZ goal = args.has() - ? args.getDatatypePost(RelativeGoalXZ.class, ctx.playerFeet()) - : new GoalXZ(ctx.playerFeet()); + ? args.getDatatypePost(RelativeGoalXZ.class, ctx.playerFeet()) + : new GoalXZ(ctx.playerFeet()); baritone.getExploreProcess().explore(goal.getX(), goal.getZ()); logDirect(String.format("Exploring from %s", goal.toString())); @@ -66,11 +66,11 @@ public class ExploreCommand extends Command { @Override public List getLongDesc() { return asList( - "Tell Baritone to explore randomly. If you used explorefilter before this, it will be applied.", - "", - "Usage:", - "> explore - Explore from your current position.", - "> explore - Explore from the specified X and Z position." + "Tell Baritone to explore randomly. If you used explorefilter before this, it will be applied.", + "", + "Usage:", + "> explore - Explore from your current position.", + "> explore - Explore from the specified X and Z position." ); } } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index 9f637257..ab0e1307 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -81,14 +81,14 @@ public class ExploreFilterCommand extends Command { @Override public List getLongDesc() { return asList( - "Apply an explore filter before using explore, which tells the explore process which chunks have been explored/not explored.", - "", - "The JSON file will follow this format: [{\"x\":0,\"z\":0},...]", - "", - "If 'invert' is specified, the chunks listed will be considered NOT explored, rather than explored.", - "", - "Usage:", - "> explorefilter [invert] - Load the JSON file referenced by the specified path. If invert is specified, it must be the literal word 'invert'." + "Apply an explore filter before using explore, which tells the explore process which chunks have been explored/not explored.", + "", + "The JSON file will follow this format: [{\"x\":0,\"z\":0},...]", + "", + "If 'invert' is specified, the chunks listed will be considered NOT explored, rather than explored.", + "", + "Usage:", + "> explorefilter [invert] - Load the JSON file referenced by the specified path. If invert is specified, it must be the literal word 'invert'." ); } } diff --git a/src/main/java/baritone/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java index 4390585c..f125bfae 100644 --- a/src/main/java/baritone/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -51,10 +51,10 @@ public class FarmCommand extends Command { @Override public List getLongDesc() { return asList( - "The farm command starts farming nearby plants. It harvests mature crops and plants new ones.", - "", - "Usage:", - "> farm" + "The farm command starts farming nearby plants. It harvests mature crops and plants new ones.", + "", + "Usage:", + "> farm" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index 4f71366a..499a45c9 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -46,18 +46,18 @@ public class FindCommand extends Command { BetterBlockPos origin = ctx.playerFeet(); toFind.stream() - .flatMap(block -> - ctx.worldData().getCachedWorld().getLocationsOf( - Block.REGISTRY.getNameForObject(block).getPath(), - Integer.MAX_VALUE, - origin.x, - origin.y, - 4 - ).stream() - ) - .map(BetterBlockPos::new) - .map(BetterBlockPos::toString) - .forEach(this::logDirect); + .flatMap(block -> + ctx.worldData().getCachedWorld().getLocationsOf( + Block.REGISTRY.getNameForObject(block).getPath(), + Integer.MAX_VALUE, + origin.x, + origin.y, + 4 + ).stream() + ) + .map(BetterBlockPos::new) + .map(BetterBlockPos::toString) + .forEach(this::logDirect); } @Override @@ -73,10 +73,10 @@ public class FindCommand extends Command { @Override public List getLongDesc() { return asList( - "", - "", - "Usage:", - "> " + "", + "", + "Usage:", + "> " ); } } diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index 7588edd2..7b5362cc 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -77,9 +77,9 @@ public class FollowCommand extends Command { } baritone.getFollowProcess().follow( - classes.isEmpty() - ? entities::contains - : e -> classes.stream().anyMatch(c -> c.isInstance(e)) + classes.isEmpty() + ? entities::contains + : e -> classes.stream().anyMatch(c -> c.isInstance(e)) ); } @@ -90,14 +90,14 @@ public class FollowCommand extends Command { if (classes.isEmpty()) { entities.stream() - .map(Entity::toString) - .forEach(this::logDirect); + .map(Entity::toString) + .forEach(this::logDirect); } else { classes.stream() - .map(EntityList::getKey) - .map(Objects::requireNonNull) - .map(ResourceLocation::toString) - .forEach(this::logDirect); + .map(EntityList::getKey) + .map(Objects::requireNonNull) + .map(ResourceLocation::toString) + .forEach(this::logDirect); } } } @@ -106,10 +106,10 @@ public class FollowCommand extends Command { protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { if (args.hasExactlyOne()) { return new TabCompleteHelper() - .append(FollowGroup.class) - .append(FollowList.class) - .filterPrefix(args.getString()) - .stream(); + .append(FollowGroup.class) + .append(FollowList.class) + .filterPrefix(args.getString()) + .stream(); } else { Class followType; @@ -139,13 +139,13 @@ public class FollowCommand extends Command { @Override public List getLongDesc() { return asList( - "The follow command tells Baritone to follow certain kinds of entities.", - "", - "Usage:", - "> follow entities - Follows all entities.", - "> follow entity <...> - Follow certain entities (for example 'skeleton', 'horse' etc.)", - "> follow players - Follow players", - "> follow player <...> - Follow certain players" + "The follow command tells Baritone to follow certain kinds of entities.", + "", + "Usage:", + "> follow entities - Follows all entities.", + "> follow entity <...> - Follow certain entities (for example 'skeleton', 'horse' etc.)", + "> follow players - Follow players", + "> follow player <...> - Follow certain players" ); } diff --git a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index 5bd7d58a..4facba0a 100644 --- a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -54,10 +54,10 @@ public class ForceCancelCommand extends Command { @Override public List getLongDesc() { return asList( - "Like cancel, but more forceful.", - "", - "Usage:", - "> forcecancel" + "Like cancel, but more forceful.", + "", + "Usage:", + "> forcecancel" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index 7e838c6f..edf7c236 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -53,10 +53,10 @@ public class GcCommand extends Command { @Override public List getLongDesc() { return asList( - "Calls System.gc().", - "", - "Usage:", - "> gc" + "Calls System.gc().", + "", + "Usage:", + "> gc" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index 55f09928..3af86a4c 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -94,16 +94,16 @@ public class GoalCommand extends Command { @Override public List getLongDesc() { return asList( - "The goal command allows you to set or clear Baritone's goal.", - "", - "Wherever a coordinate is expected, you can use ~ just like in regular Minecraft commands. Or, you can just use regular numbers.", - "", - "Usage:", - "> goal - Set the goal to your current position", - "> goal - Erase the goal", - "> goal - Set the goal to a Y level", - "> goal - Set the goal to an X,Z position", - "> goal - Set the goal to an X,Y,Z position" + "The goal command allows you to set or clear Baritone's goal.", + "", + "Wherever a coordinate is expected, you can use ~ just like in regular Minecraft commands. Or, you can just use regular numbers.", + "", + "Usage:", + "> goal - Set the goal to your current position", + "> goal - Erase the goal", + "> goal - Set the goal to a Y level", + "> goal - Set the goal to an X,Z position", + "> goal - Set the goal to an X,Y,Z position" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index ccd7d640..5a7a022d 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -50,38 +50,38 @@ public class HelpCommand extends Command { if (!args.has() || args.is(Integer.class)) { Paginator.paginate( - args, new Paginator<>( - CommandManager.REGISTRY.descendingStream() - .filter(command -> !command.hiddenFromHelp()) - .collect(Collectors.toList()) - ), - () -> logDirect("All Baritone commands (clickable):"), - command -> { - String names = String.join("/", command.names); - String name = command.names.get(0); + args, new Paginator<>( + CommandManager.REGISTRY.descendingStream() + .filter(command -> !command.hiddenFromHelp()) + .collect(Collectors.toList()) + ), + () -> logDirect("All Baritone commands (clickable):"), + command -> { + String names = String.join("/", command.names); + String name = command.names.get(0); - ITextComponent shortDescComponent = new TextComponentString(" - " + command.getShortDesc()); - shortDescComponent.getStyle().setColor(TextFormatting.DARK_GRAY); + ITextComponent shortDescComponent = new TextComponentString(" - " + command.getShortDesc()); + shortDescComponent.getStyle().setColor(TextFormatting.DARK_GRAY); - ITextComponent namesComponent = new TextComponentString(names); - namesComponent.getStyle().setColor(TextFormatting.WHITE); + ITextComponent namesComponent = new TextComponentString(names); + namesComponent.getStyle().setColor(TextFormatting.WHITE); - ITextComponent hoverComponent = new TextComponentString(""); - hoverComponent.getStyle().setColor(TextFormatting.GRAY); - hoverComponent.appendSibling(namesComponent); - hoverComponent.appendText("\n" + command.getShortDesc()); - hoverComponent.appendText("\n\nClick to view full help"); - String clickCommand = FORCE_COMMAND_PREFIX + String.format("%s %s", label, command.names.get(0)); + ITextComponent hoverComponent = new TextComponentString(""); + hoverComponent.getStyle().setColor(TextFormatting.GRAY); + hoverComponent.appendSibling(namesComponent); + hoverComponent.appendText("\n" + command.getShortDesc()); + hoverComponent.appendText("\n\nClick to view full help"); + String clickCommand = FORCE_COMMAND_PREFIX + String.format("%s %s", label, command.names.get(0)); - ITextComponent component = new TextComponentString(name); - component.getStyle().setColor(TextFormatting.GRAY); - component.appendSibling(shortDescComponent); - component.getStyle() - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent)) - .setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, clickCommand)); - return component; - }, - FORCE_COMMAND_PREFIX + label + ITextComponent component = new TextComponentString(name); + component.getStyle().setColor(TextFormatting.GRAY); + component.appendSibling(shortDescComponent); + component.getStyle() + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent)) + .setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, clickCommand)); + return component; + }, + FORCE_COMMAND_PREFIX + label ); } else { String commandName = args.getString().toLowerCase(); @@ -98,8 +98,8 @@ public class HelpCommand extends Command { ITextComponent returnComponent = new TextComponentString("Click to return to the help menu"); returnComponent.getStyle().setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - FORCE_COMMAND_PREFIX + label + ClickEvent.Action.RUN_COMMAND, + FORCE_COMMAND_PREFIX + label )); logDirect(returnComponent); @@ -123,11 +123,11 @@ public class HelpCommand extends Command { @Override public List getLongDesc() { return asList( - "Using this command, you can view detailed help information on how to use certain commands of Baritone.", - "", - "Usage:", - "> help - Lists all commands and their short descriptions.", - "> help - Displays help information on a specific command." + "Using this command, you can view detailed help information on how to use certain commands of Baritone.", + "", + "Usage:", + "> help - Lists all commands and their short descriptions.", + "> help - Displays help information on a specific command." ); } } diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index 1a46bdc7..8000d584 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -70,10 +70,10 @@ public class InvertCommand extends Command { @Override public List getLongDesc() { return asList( - "The invert command tells Baritone to head away from the current goal rather than towards it.", - "", - "Usage:", - "> invert - Invert the current goal." + "The invert command tells Baritone to head away from the current goal rather than towards it.", + "", + "Usage:", + "> invert - Invert the current goal." ); } } diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index 0f155e74..5cc12ff8 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -64,16 +64,16 @@ public class MineCommand extends Command { @Override public List getLongDesc() { return asList( - "The mine command allows you to tell Baritone to search for and mine individual blocks.", - "", - "The specified blocks can be ores (which are commonly cached), or any other block.", - "", - "Also see the legitMine settings (see #set l legitMine).", - "", - "Usage:", - "> mine diamond_ore - Mines all diamonds it can find.", - "> mine redstone_ore lit_redstone_ore - Mines redstone ore.", - "> mine log:0 - Mines only oak logs." + "The mine command allows you to tell Baritone to search for and mine individual blocks.", + "", + "The specified blocks can be ores (which are commonly cached), or any other block.", + "", + "Also see the legitMine settings (see #set l legitMine).", + "", + "Usage:", + "> mine diamond_ore - Mines all diamonds it can find.", + "> mine redstone_ore lit_redstone_ore - Mines redstone ore.", + "> mine log:0 - Mines only oak logs." ); } } diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index b2c7e69f..3dcc79bd 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -69,9 +69,9 @@ public class PathCommand extends Command { if (!args.has(2)) { return new TabCompleteHelper() - .append("~") - .filterPrefix(args.getString()) - .stream(); + .append("~") + .filterPrefix(args.getString()) + .stream(); } } } @@ -87,13 +87,13 @@ public class PathCommand extends Command { @Override public List getLongDesc() { return asList( - "The path command tells Baritone to head towards the current goal.", - "", - "Usage:", - "> path - Start the pathing.", - "> path ", - "> path ", - "> path - Define the goal here" + "The path command tells Baritone to head towards the current goal.", + "", + "Usage:", + "> path - Start the pathing.", + "> path ", + "> path ", + "> path - Define the goal here" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index b8b3f91f..1242d153 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -33,7 +33,7 @@ import static java.util.Arrays.asList; /** * Contains the pause, resume, and paused commands. - * + *

* This thing is scoped to hell, private so far you can't even access it using reflection, because you AREN'T SUPPOSED * TO USE THIS to pause and resume Baritone. Make your own process that returns {@link PathingCommandType#REQUEST_PAUSE * REQUEST_PAUSE} as needed. @@ -48,35 +48,35 @@ public class PauseResumeCommands { final boolean[] paused = {false}; BaritoneAPI.getProvider().getPrimaryBaritone().getPathingControlManager().registerProcess( - new IBaritoneProcess() { - @Override - public boolean isActive() { - return paused[0]; - } + new IBaritoneProcess() { + @Override + public boolean isActive() { + return paused[0]; + } - @Override - public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { - return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); - } + @Override + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } - @Override - public boolean isTemporary() { - return true; - } + @Override + public boolean isTemporary() { + return true; + } - @Override - public void onLostControl() {} + @Override + public void onLostControl() {} - @Override - public double priority() { - return DEFAULT_PRIORITY + 1; - } + @Override + public double priority() { + return DEFAULT_PRIORITY + 1; + } - @Override - public String displayName0() { - return "Pause/Resume Commands"; + @Override + public String displayName0() { + return "Pause/Resume Commands"; + } } - } ); pauseCommand = new Command("pause") { @@ -105,12 +105,12 @@ public class PauseResumeCommands { @Override public List getLongDesc() { return asList( - "The pause command tells Baritone to temporarily stop whatever it's doing.", - "", - "This can be used to pause pathing, building, following, whatever. A single use of the resume command will start it right back up again!", - "", - "Usage:", - "> pause" + "The pause command tells Baritone to temporarily stop whatever it's doing.", + "", + "This can be used to pause pathing, building, following, whatever. A single use of the resume command will start it right back up again!", + "", + "Usage:", + "> pause" ); } }; @@ -141,10 +141,10 @@ public class PauseResumeCommands { @Override public List getLongDesc() { return asList( - "The resume command tells Baritone to resume whatever it was doing when you last used pause.", - "", - "Usage:", - "> resume" + "The resume command tells Baritone to resume whatever it was doing when you last used pause.", + "", + "Usage:", + "> resume" ); } }; @@ -170,10 +170,10 @@ public class PauseResumeCommands { @Override public List getLongDesc() { return asList( - "The paused command tells you if Baritone is currently paused by use of the pause command.", - "", - "Usage:", - "> paused" + "The paused command tells you if Baritone is currently paused by use of the pause command.", + "", + "Usage:", + "> paused" ); } }; diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index a0ada87f..816c1770 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -48,19 +48,19 @@ public class ProcCommand extends Command { } logDirect(String.format( - "Class: %s\n" + - "Priority: %f\n" + - "Temporary: %b\n" + - "Display name: %s\n" + - "Last command: %s", - process.getClass().getTypeName(), - process.priority(), - process.isTemporary(), - process.displayName(), - pathingControlManager - .mostRecentCommand() - .map(PathingCommand::toString) - .orElse("None") + "Class: %s\n" + + "Priority: %f\n" + + "Temporary: %b\n" + + "Display name: %s\n" + + "Last command: %s", + process.getClass().getTypeName(), + process.priority(), + process.isTemporary(), + process.displayName(), + pathingControlManager + .mostRecentCommand() + .map(PathingCommand::toString) + .orElse("None") )); } @@ -77,12 +77,12 @@ public class ProcCommand extends Command { @Override public List getLongDesc() { return asList( - "The proc command provides miscellaneous information about the process currently controlling Baritone.", - "", - "You are not expected to understand this if you aren't familiar with how Baritone works.", - "", - "Usage:", - "> proc - View process information, if present" + "The proc command provides miscellaneous information about the process currently controlling Baritone.", + "", + "You are not expected to understand this if you aren't familiar with how Baritone works.", + "", + "Usage:", + "> proc - View process information, if present" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index a7904bda..1ac5c6d7 100644 --- a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -51,10 +51,10 @@ public class ReloadAllCommand extends Command { @Override public List getLongDesc() { return asList( - "The reloadall command reloads Baritone's world cache.", - "", - "Usage:", - "> reloadall" + "The reloadall command reloads Baritone's world cache.", + "", + "Usage:", + "> reloadall" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index 90a260a5..e59664f9 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -39,12 +39,12 @@ public class RenderCommand extends Command { BetterBlockPos origin = ctx.playerFeet(); int renderDistance = (MC.gameSettings.renderDistanceChunks + 1) * 16; MC.renderGlobal.markBlockRangeForRenderUpdate( - origin.x - renderDistance, - 0, - origin.z - renderDistance, - origin.x + renderDistance, - 255, - origin.z + renderDistance + origin.x - renderDistance, + 0, + origin.z - renderDistance, + origin.x + renderDistance, + 255, + origin.z + renderDistance ); logDirect("Done"); @@ -63,10 +63,10 @@ public class RenderCommand extends Command { @Override public List getLongDesc() { return asList( - "The render command fixes glitched chunk rendering without having to reload all of them.", - "", - "Usage:", - "> render" + "The render command fixes glitched chunk rendering without having to reload all of them.", + "", + "Usage:", + "> render" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java index 357197ee..b64d4b8e 100644 --- a/src/main/java/baritone/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -51,10 +51,10 @@ public class RepackCommand extends Command { @Override public List getLongDesc() { return asList( - "Repack chunks around you. This basically re-caches them.", - "", - "Usage:", - "> repack - Repack chunks." + "Repack chunks around you. This basically re-caches them.", + "", + "Usage:", + "> repack - Repack chunks." ); } } diff --git a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index 953e7527..ae8d603d 100644 --- a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -51,10 +51,10 @@ public class SaveAllCommand extends Command { @Override public List getLongDesc() { return asList( - "The saveall command saves Baritone's world cache.", - "", - "Usage:", - "> saveall" + "The saveall command saves Baritone's world cache.", + "", + "Usage:", + "> saveall" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index be455bc2..1b83ded8 100644 --- a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -50,10 +50,10 @@ public class SchematicaCommand extends Command { @Override public List getLongDesc() { return asList( - "Builds the schematica currently open in Schematica.", - "", - "Usage:", - "> schematica" + "Builds the schematica currently open in Schematica.", + "", + "Usage:", + "> schematica" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index fcaae5ed..9952b8a1 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -19,11 +19,7 @@ package baritone.utils.command.defaults; import baritone.api.Settings; import baritone.api.event.events.RenderEvent; -import baritone.api.schematic.CompositeSchematic; -import baritone.api.schematic.FillSchematic; -import baritone.api.schematic.ReplaceSchematic; -import baritone.api.schematic.ShellSchematic; -import baritone.api.schematic.WallsSchematic; +import baritone.api.schematic.*; import baritone.api.selection.ISelection; import baritone.api.selection.ISelectionManager; import baritone.api.utils.BetterBlockPos; @@ -44,7 +40,7 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.Vec3i; -import java.awt.Color; +import java.awt.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -109,8 +105,8 @@ public class SelCommand extends Command { } } else if (action == Action.SET || action == Action.WALLS || action == Action.SHELL || action == Action.CLEARAREA || action == Action.REPLACE) { BlockOptionalMeta type = action == Action.CLEARAREA - ? new BlockOptionalMeta(Blocks.AIR) - : args.getDatatypeFor(ForBlockOptionalMeta.class); + ? new BlockOptionalMeta(Blocks.AIR) + : args.getDatatypeFor(ForBlockOptionalMeta.class); BlockOptionalMetaLookup replaces = null; if (action == Action.REPLACE) { @@ -142,9 +138,9 @@ public class SelCommand extends Command { for (ISelection selection : selections) { BetterBlockPos min = selection.min(); origin = new BetterBlockPos( - Math.min(origin.x, min.x), - Math.min(origin.y, min.y), - Math.min(origin.z, min.z) + Math.min(origin.x, min.x), + Math.min(origin.y, min.y), + Math.min(origin.z, min.z) ); } @@ -204,10 +200,10 @@ public class SelCommand extends Command { protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { if (args.hasExactlyOne()) { return new TabCompleteHelper() - .append(Action.getAllNames()) - .filterPrefix(args.getString()) - .sortAlphabetically() - .stream(); + .append(Action.getAllNames()) + .filterPrefix(args.getString()) + .sortAlphabetically() + .stream(); } else { Action action = Action.getByName(args.getString()); @@ -227,10 +223,10 @@ public class SelCommand extends Command { } else if (action == Action.EXPAND || action == Action.CONTRACT || action == Action.SHIFT) { if (args.hasExactlyOne()) { return new TabCompleteHelper() - .append(TransformTarget.getAllNames()) - .filterPrefix(args.getString()) - .sortAlphabetically() - .stream(); + .append(TransformTarget.getAllNames()) + .filterPrefix(args.getString()) + .sortAlphabetically() + .stream(); } else { TransformTarget target = TransformTarget.getByName(args.getString()); @@ -253,29 +249,29 @@ public class SelCommand extends Command { @Override public List getLongDesc() { return asList( - "The sel command allows you to manipulate Baritone's selections, similarly to WorldEdit.", - "", - "Using these selections, you can clear areas, fill them with blocks, or something else.", - "", - "The expand/contract/shift commands use a kind of selector to choose which selections to target. Supported ones are a/all, n/newest, and o/oldest.", - "", - "Usage:", - "> sel pos1/p1/1 - Set position 1 to your current position.", - "> sel pos1/p1/1 - Set position 1 to a relative position.", - "> sel pos2/p2/2 - Set position 2 to your current position.", - "> sel pos2/p2/2 - Set position 2 to a relative position.", - "", - "> sel clear/c - Clear the selection.", - "> sel undo/u - Undo the last action (setting positions, creating selections, etc.)", - "> 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 cleararea/ca - Basically 'set air'.", - "> sel replace/r - Replaces blocks with another block.", - "", - "> sel expand - Expand the targets.", - "> sel contract - Contract the targets.", - "> sel shift - Shift the targets (does not resize)." + "The sel command allows you to manipulate Baritone's selections, similarly to WorldEdit.", + "", + "Using these selections, you can clear areas, fill them with blocks, or something else.", + "", + "The expand/contract/shift commands use a kind of selector to choose which selections to target. Supported ones are a/all, n/newest, and o/oldest.", + "", + "Usage:", + "> sel pos1/p1/1 - Set position 1 to your current position.", + "> sel pos1/p1/1 - Set position 1 to a relative position.", + "> sel pos2/p2/2 - Set position 2 to your current position.", + "> sel pos2/p2/2 - Set position 2 to a relative position.", + "", + "> sel clear/c - Clear the selection.", + "> sel undo/u - Undo the last action (setting positions, creating selections, etc.)", + "> 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 cleararea/ca - Basically 'set air'.", + "> sel replace/r - Replaces blocks with another block.", + "", + "> sel expand - Expand the targets.", + "> sel contract - Contract the targets.", + "> sel shift - Shift the targets (does not resize)." ); } @@ -327,8 +323,8 @@ public class SelCommand extends Command { enum TransformTarget { ALL(sels -> sels, "all", "a"), - NEWEST(sels -> new ISelection[] {sels[sels.length - 1]}, "newest", "n"), - OLDEST(sels -> new ISelection[] {sels[0]}, "oldest", "o"); + NEWEST(sels -> new ISelection[]{sels[sels.length - 1]}, "newest", "n"), + OLDEST(sels -> new ISelection[]{sels[0]}, "oldest", "o"); private final Function transform; private final String[] names; diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index 4588c450..7fa33d26 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -66,44 +66,44 @@ public class SetCommand extends Command { args.requireMax(1); List toPaginate = - (viewModified ? SettingsUtil.modifiedSettings(settings) : settings.allSettings).stream() - .filter(s -> !s.getName().equals("logger")) - .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()); + (viewModified ? SettingsUtil.modifiedSettings(settings) : settings.allSettings).stream() + .filter(s -> !s.getName().equals("logger")) + .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()); Paginator.paginate( - args, - new Paginator<>(toPaginate), - () -> logDirect( - !search.isEmpty() - ? String.format("All %ssettings containing the string '%s':", viewModified ? "modified " : "", search) - : String.format("All %ssettings:", viewModified ? "modified " : "") - ), - setting -> { - ITextComponent typeComponent = new TextComponentString(String.format( - " (%s)", - settingTypeToString(setting) - )); - typeComponent.getStyle().setColor(TextFormatting.DARK_GRAY); + args, + new Paginator<>(toPaginate), + () -> logDirect( + !search.isEmpty() + ? String.format("All %ssettings containing the string '%s':", viewModified ? "modified " : "", search) + : String.format("All %ssettings:", viewModified ? "modified " : "") + ), + setting -> { + ITextComponent typeComponent = new TextComponentString(String.format( + " (%s)", + settingTypeToString(setting) + )); + typeComponent.getStyle().setColor(TextFormatting.DARK_GRAY); - ITextComponent hoverComponent = new TextComponentString(""); - hoverComponent.getStyle().setColor(TextFormatting.GRAY); - hoverComponent.appendText(setting.getName()); - hoverComponent.appendText(String.format("\nType: %s", settingTypeToString(setting))); - hoverComponent.appendText(String.format("\n\nValue:\n%s", settingValueToString(setting))); - String commandSuggestion = settings.prefix.value + String.format("set %s ", setting.getName()); + ITextComponent hoverComponent = new TextComponentString(""); + hoverComponent.getStyle().setColor(TextFormatting.GRAY); + hoverComponent.appendText(setting.getName()); + hoverComponent.appendText(String.format("\nType: %s", settingTypeToString(setting))); + hoverComponent.appendText(String.format("\n\nValue:\n%s", settingValueToString(setting))); + String commandSuggestion = settings.prefix.value + String.format("set %s ", setting.getName()); - ITextComponent component = new TextComponentString(setting.getName()); - component.getStyle().setColor(TextFormatting.GRAY); - component.appendSibling(typeComponent); - component.getStyle() - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent)) - .setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, commandSuggestion)); + ITextComponent component = new TextComponentString(setting.getName()); + component.getStyle().setColor(TextFormatting.GRAY); + component.appendSibling(typeComponent); + component.getStyle() + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent)) + .setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, commandSuggestion)); - return component; - }, - FORCE_COMMAND_PREFIX + "set " + arg + " " + search + return component; + }, + FORCE_COMMAND_PREFIX + "set " + arg + " " + search ); return; @@ -135,9 +135,9 @@ public class SetCommand extends Command { String settingName = doingSomething ? args.getString() : arg; Settings.Setting setting = settings.allSettings.stream() - .filter(s -> s.getName().equalsIgnoreCase(settingName)) - .findFirst() - .orElse(null); + .filter(s -> s.getName().equalsIgnoreCase(settingName)) + .findFirst() + .orElse(null); if (isNull(setting)) { throw new CommandInvalidTypeException(args.consumed(), "a valid setting"); @@ -160,9 +160,9 @@ public class SetCommand extends Command { ((Settings.Setting) setting).value ^= true; logDirect(String.format( - "Toggled setting %s to %s", - setting.getName(), - Boolean.toString((Boolean) setting.value) + "Toggled setting %s to %s", + setting.getName(), + Boolean.toString((Boolean) setting.value) )); } else { String newValue = args.getString(); @@ -177,29 +177,29 @@ public class SetCommand extends Command { if (!toggling) { logDirect(String.format( - "Successfully %s %s to %s", - resetting ? "reset" : "set", - setting.getName(), - settingValueToString(setting) + "Successfully %s %s to %s", + resetting ? "reset" : "set", + setting.getName(), + settingValueToString(setting) )); } ITextComponent oldValueComponent = new TextComponentString(String.format("Old value: %s", oldValue)); oldValueComponent.getStyle() - .setColor(TextFormatting.GRAY) - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("Click to set the setting back to this value") - )) - .setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue) - )); + .setColor(TextFormatting.GRAY) + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to set the setting back to this value") + )) + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue) + )); logDirect(oldValueComponent); if ((setting.getName().equals("chatControl") && !(Boolean) setting.value && !settings.chatControlAnyway.value) || - setting.getName().equals("chatControlAnyway") && !(Boolean) setting.value && !settings.chatControl.value) { + setting.getName().equals("chatControlAnyway") && !(Boolean) setting.value && !settings.chatControl.value) { logDirect("Warning: Chat commands will no longer work. If you want to revert this change, use prefix control (if enabled) or click the old value listed above.", TextFormatting.RED); } else if (setting.getName().equals("prefixControl") && !(Boolean) setting.value) { logDirect("Warning: Prefixed commands will no longer work. If you want to revert this change, use chat control (if enabled) or click the old value listed above.", TextFormatting.RED); @@ -217,15 +217,15 @@ public class SetCommand extends Command { if (args.hasExactlyOne() && !asList("s", "save").contains(args.peekString().toLowerCase(Locale.US))) { if (arg.equalsIgnoreCase("reset")) { return new TabCompleteHelper() - .addModifiedSettings() - .prepend("all") - .filterPrefix(args.getString()) - .stream(); + .addModifiedSettings() + .prepend("all") + .filterPrefix(args.getString()) + .stream(); } else if (arg.equalsIgnoreCase("toggle")) { return new TabCompleteHelper() - .addToggleableSettings() - .filterPrefix(args.getString()) - .stream(); + .addToggleableSettings() + .filterPrefix(args.getString()) + .stream(); } Settings.Setting setting = settings.byLowerName.get(arg.toLowerCase(Locale.US)); @@ -247,11 +247,11 @@ public class SetCommand extends Command { } } else if (!args.has()) { return new TabCompleteHelper() - .addSettings() - .sortAlphabetically() - .prepend("list", "modified", "reset", "toggle", "save") - .filterPrefix(arg) - .stream(); + .addSettings() + .sortAlphabetically() + .prepend("list", "modified", "reset", "toggle", "save") + .filterPrefix(arg) + .stream(); } } @@ -266,18 +266,18 @@ public class SetCommand extends Command { @Override public List getLongDesc() { return asList( - "Using the set command, you can manage all of Baritone's settings. Almost every aspect is controlled by these settings - go wild!", - "", - "Usage:", - "> set - Same as `set list`", - "> set list [page] - View all settings", - "> set modified [page] - View modified settings", - "> set - View the current value of a setting", - "> set - Set the value of a setting", - "> 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)" + "Using the set command, you can manage all of Baritone's settings. Almost every aspect is controlled by these settings - go wild!", + "", + "Usage:", + "> set - Same as `set list`", + "> set list [page] - View all settings", + "> set modified [page] - View modified settings", + "> set - View the current value of a setting", + "> set - Set the value of a setting", + "> 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)" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index 2f83cb0c..e51f96a8 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -37,9 +37,9 @@ public class ThisWayCommand extends Command { args.requireExactly(1); GoalXZ goal = GoalXZ.fromDirection( - ctx.playerFeetAsVec(), - ctx.player().rotationYawHead, - args.getAs(Double.class) + ctx.playerFeetAsVec(), + ctx.player().rotationYawHead, + args.getAs(Double.class) ); baritone.getCustomGoalProcess().setGoal(goal); @@ -59,10 +59,10 @@ public class ThisWayCommand extends Command { @Override public List getLongDesc() { return asList( - "Creates a GoalXZ some amount of blocks in the direction you're currently looking", - "", - "Usage:", - "> thisway - makes a GoalXZ distance blocks in front of you" + "Creates a GoalXZ some amount of blocks in the direction you're currently looking", + "", + "Usage:", + "> thisway - makes a GoalXZ distance blocks in front of you" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index 8d59fba6..a355e2e2 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -38,8 +38,8 @@ public class TunnelCommand extends Command { args.requireMax(0); Goal goal = new GoalStrictDirection( - ctx.playerFeet(), - ctx.player().getHorizontalFacing() + ctx.playerFeet(), + ctx.player().getHorizontalFacing() ); baritone.getCustomGoalProcess().setGoal(goal); @@ -59,10 +59,10 @@ public class TunnelCommand extends Command { @Override public List getLongDesc() { return asList( - "The tunnel command sets a goal that tells Baritone to mine completely straight in the direction that you're facing.", - "", - "Usage:", - "> tunnel" + "The tunnel command sets a goal that tells Baritone to mine completely straight in the direction that you're facing.", + "", + "Usage:", + "> tunnel" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index 71b30c19..f6e25be4 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -59,10 +59,10 @@ public class VersionCommand extends Command { @Override public List getLongDesc() { return asList( - "The version command prints the version of Baritone you're currently running.", - "", - "Usage:", - "> version - View version information, if present" + "The version command prints the version of Baritone you're currently running.", + "", + "Usage:", + "> version - View version information, if present" ); } } diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 7069e02f..cf02f67b 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -76,27 +76,27 @@ public class WaypointsCommand extends Command { component.appendSibling(nameComponent); component.appendSibling(timestamp); component.getStyle() - .setHoverEvent(new HoverEvent( - HoverEvent.Action.SHOW_TEXT, - new TextComponentString("Click to select") - )) - .setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - String.format( - "%s%s %s %s @ %d", - FORCE_COMMAND_PREFIX, - label, - _action.names[0], - waypoint.getTag().getName(), - waypoint.getCreationTimestamp() + .setHoverEvent(new HoverEvent( + HoverEvent.Action.SHOW_TEXT, + new TextComponentString("Click to select") )) - ); + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + String.format( + "%s%s %s %s @ %d", + FORCE_COMMAND_PREFIX, + label, + _action.names[0], + waypoint.getTag().getName(), + waypoint.getCreationTimestamp() + )) + ); return component; }; Function transform = waypoint -> - toComponent.apply(waypoint, action == Action.LIST ? Action.INFO : action); + toComponent.apply(waypoint, action == Action.LIST ? Action.INFO : action); if (action == Action.LIST) { IWaypoint.Tag tag = args.has() ? IWaypoint.Tag.getByName(args.peekString()) : null; @@ -106,34 +106,34 @@ public class WaypointsCommand extends Command { } IWaypoint[] waypoints = tag != null - ? ForWaypoints.getWaypointsByTag(tag) - : ForWaypoints.getWaypoints(); + ? ForWaypoints.getWaypointsByTag(tag) + : ForWaypoints.getWaypoints(); if (waypoints.length > 0) { args.requireMax(1); Paginator.paginate( - args, - waypoints, - () -> logDirect( - tag != null - ? String.format("All waypoints by tag %s:", tag.name()) - : "All waypoints:" - ), - transform, - String.format( - "%s%s %s%s", - FORCE_COMMAND_PREFIX, - label, - action.names[0], - tag != null ? " " + tag.getName() : "" - ) + args, + waypoints, + () -> logDirect( + tag != null + ? String.format("All waypoints by tag %s:", tag.name()) + : "All waypoints:" + ), + transform, + String.format( + "%s%s %s%s", + FORCE_COMMAND_PREFIX, + label, + action.names[0], + tag != null ? " " + tag.getName() : "" + ) ); } else { args.requireMax(0); throw new CommandInvalidStateException( - tag != null - ? "No waypoints found by that tag" - : "No waypoints found" + tag != null + ? "No waypoints found by that tag" + : "No waypoints found" ); } } else if (action == Action.SAVE) { @@ -145,8 +145,8 @@ public class WaypointsCommand extends Command { String name = args.has() ? args.getString() : ""; BetterBlockPos pos = args.has() - ? args.getDatatypePost(RelativeBlockPos.class, ctx.playerFeet()) - : ctx.playerFeet(); + ? args.getDatatypePost(RelativeBlockPos.class, ctx.playerFeet()) + : ctx.playerFeet(); args.requireMax(0); @@ -198,17 +198,17 @@ public class WaypointsCommand extends Command { if (waypoint == null) { args.requireMax(1); Paginator.paginate( - args, - waypoints, - () -> logDirect("Multiple waypoints were found:"), - transform, - String.format( - "%s%s %s %s", - FORCE_COMMAND_PREFIX, - label, - action.names[0], - args.consumedString() - ) + args, + waypoints, + () -> logDirect("Multiple waypoints were found:"), + transform, + String.format( + "%s%s %s %s", + FORCE_COMMAND_PREFIX, + label, + action.names[0], + args.consumedString() + ) ); } else { if (action == Action.INFO) { @@ -216,34 +216,34 @@ public class WaypointsCommand extends Command { logDirect(String.format("Position: %s", waypoint.getLocation())); ITextComponent deleteComponent = new TextComponentString("Click to delete this waypoint"); deleteComponent.getStyle().setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - String.format( - "%s%s delete %s @ %d", - FORCE_COMMAND_PREFIX, - label, - waypoint.getTag().getName(), - waypoint.getCreationTimestamp() - ) + ClickEvent.Action.RUN_COMMAND, + String.format( + "%s%s delete %s @ %d", + FORCE_COMMAND_PREFIX, + label, + waypoint.getTag().getName(), + waypoint.getCreationTimestamp() + ) )); ITextComponent goalComponent = new TextComponentString("Click to set goal to this waypoint"); goalComponent.getStyle().setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - String.format( - "%s%s goal %s @ %d", - FORCE_COMMAND_PREFIX, - label, - waypoint.getTag().getName(), - waypoint.getCreationTimestamp() - ) + ClickEvent.Action.RUN_COMMAND, + String.format( + "%s%s goal %s @ %d", + FORCE_COMMAND_PREFIX, + label, + waypoint.getTag().getName(), + waypoint.getCreationTimestamp() + ) )); ITextComponent backComponent = new TextComponentString("Click to return to the waypoints list"); backComponent.getStyle().setClickEvent(new ClickEvent( - ClickEvent.Action.RUN_COMMAND, - String.format( - "%s%s list", - FORCE_COMMAND_PREFIX, - label - ) + ClickEvent.Action.RUN_COMMAND, + String.format( + "%s%s list", + FORCE_COMMAND_PREFIX, + label + ) )); logDirect(deleteComponent); logDirect(goalComponent); @@ -265,20 +265,20 @@ public class WaypointsCommand extends Command { if (args.has()) { if (args.hasExactlyOne()) { return new TabCompleteHelper() - .append(Action.getAllNames()) - .sortAlphabetically() - .filterPrefix(args.getString()) - .stream(); + .append(Action.getAllNames()) + .sortAlphabetically() + .filterPrefix(args.getString()) + .stream(); } else { Action action = Action.getByName(args.getString()); if (args.hasExactlyOne()) { if (action == Action.LIST || action == Action.SAVE || action == Action.CLEAR) { return new TabCompleteHelper() - .append(IWaypoint.Tag.getAllNames()) - .sortAlphabetically() - .filterPrefix(args.getString()) - .stream(); + .append(IWaypoint.Tag.getAllNames()) + .sortAlphabetically() + .filterPrefix(args.getString()) + .stream(); } else { return args.tabCompleteDatatype(ForWaypoints.class); } @@ -301,20 +301,20 @@ public class WaypointsCommand extends Command { @Override public List getLongDesc() { return asList( - "The waypoint command allows you to manage Baritone's waypoints.", - "", - "Waypoints can be used to mark positions for later. Waypoints are each given a tag and an optional name.", - "", - "Note that the info, delete, and goal commands let you specify a waypoint by tag. If there is more than one waypoint with a certain tag, then they will let you select which waypoint you mean.", - "", - "Usage:", - "> wp [l/list] - List all waypoints.", - "> wp - Save your current position as an unnamed waypoint with the specified tag.", - "> wp - Save the waypoint with the specified name.", - "> wp - Save the waypoint with the specified name and position.", - "> wp - Show info on a waypoint by tag.", - "> wp - Delete a waypoint by tag.", - "> wp - Set a goal to a waypoint by tag." + "The waypoint command allows you to manage Baritone's waypoints.", + "", + "Waypoints can be used to mark positions for later. Waypoints are each given a tag and an optional name.", + "", + "Note that the info, delete, and goal commands let you specify a waypoint by tag. If there is more than one waypoint with a certain tag, then they will let you select which waypoint you mean.", + "", + "Usage:", + "> wp [l/list] - List all waypoints.", + "> wp - Save your current position as an unnamed waypoint with the specified tag.", + "> wp - Save the waypoint with the specified name.", + "> wp - Save the waypoint with the specified name and position.", + "> wp - Show info on a waypoint by tag.", + "> wp - Delete a waypoint by tag.", + "> wp - Set a goal to a waypoint by tag." ); } diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java index 548e3e37..4743b79b 100644 --- a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java @@ -18,7 +18,6 @@ package baritone.utils.schematic.schematica; import baritone.api.utils.ISchematic; - import com.github.lunatrius.schematica.client.world.SchematicWorld; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java index 63b85670..bacf1e9d 100644 --- a/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicaHelper.java @@ -39,7 +39,7 @@ public enum SchematicaHelper { public static Optional> getOpenSchematic() { return Optional.ofNullable(ClientProxy.schematic) - .map(world -> new Tuple<>(new SchematicAdapter(world), world.position)); + .map(world -> new Tuple<>(new SchematicAdapter(world), world.position)); } } diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java b/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java index 80c1b2a2..d24074c4 100644 --- a/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java +++ b/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java @@ -21,7 +21,7 @@ import com.github.lunatrius.core.util.math.MBlockPos; import com.github.lunatrius.schematica.api.ISchematic; public class SchematicWorld { - public final MBlockPos position = (MBlockPos)(Object)"cringe"; + public final MBlockPos position = (MBlockPos) (Object) "cringe"; public ISchematic getSchematic() { throw new LinkageError("LOL"); From 23a592ec01aad7f957c690a91ec21f98aadfd6b5 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 13:30:40 -0700 Subject: [PATCH 636/682] it launches --- src/api/java/baritone/api/BaritoneAPI.java | 6 +- src/api/java/baritone/api/IBaritone.java | 9 -- .../java/baritone/api/utils/ISchematic.java | 2 +- .../java/baritone/api/utils/MyChunkPos.java | 2 +- .../baritone/api/utils/command/Command.java | 18 ++-- .../launch/mixins/MixinMinecraft.java | 3 +- src/main/java/baritone/Baritone.java | 18 +--- src/main/java/baritone/BaritoneProvider.java | 8 +- .../baritone/selection/SelectionManager.java | 5 +- .../baritone/selection/SelectionRenderer.java | 3 +- src/main/java/baritone/utils/IRenderer.java | 2 - .../baritone/utils/InputOverrideHandler.java | 2 +- .../utils/command/defaults/AxisCommand.java | 5 +- .../command/defaults/BlacklistCommand.java | 5 +- .../utils/command/defaults/BuildCommand.java | 5 +- .../utils/command/defaults/CancelCommand.java | 5 +- .../utils/command/defaults/ChestsCommand.java | 5 +- .../command/defaults/ClearareaCommand.java | 5 +- .../utils/command/defaults/ClickCommand.java | 5 +- .../utils/command/defaults/ComeCommand.java | 5 +- .../utils/command/defaults/CommandAlias.java | 9 +- .../command/defaults/DefaultCommands.java | 93 ++++++++++--------- .../utils/command/defaults/EmptyCommand.java | 5 +- .../command/defaults/ExploreCommand.java | 5 +- .../defaults/ExploreFilterCommand.java | 5 +- .../utils/command/defaults/FarmCommand.java | 5 +- .../utils/command/defaults/FindCommand.java | 5 +- .../utils/command/defaults/FollowCommand.java | 5 +- .../command/defaults/ForceCancelCommand.java | 5 +- .../utils/command/defaults/GcCommand.java | 5 +- .../utils/command/defaults/GoalCommand.java | 5 +- .../utils/command/defaults/HelpCommand.java | 5 +- .../utils/command/defaults/InvertCommand.java | 5 +- .../utils/command/defaults/MineCommand.java | 5 +- .../utils/command/defaults/PathCommand.java | 5 +- .../command/defaults/PauseResumeCommands.java | 20 ++-- .../utils/command/defaults/ProcCommand.java | 5 +- .../command/defaults/ReloadAllCommand.java | 5 +- .../utils/command/defaults/RenderCommand.java | 5 +- .../utils/command/defaults/RepackCommand.java | 5 +- .../command/defaults/SaveAllCommand.java | 5 +- .../command/defaults/SchematicaCommand.java | 5 +- .../utils/command/defaults/SelCommand.java | 40 ++++---- .../utils/command/defaults/SetCommand.java | 5 +- .../command/defaults/ThisWayCommand.java | 5 +- .../utils/command/defaults/TunnelCommand.java | 5 +- .../command/defaults/VersionCommand.java | 5 +- .../command/defaults/WaypointsCommand.java | 5 +- 48 files changed, 211 insertions(+), 189 deletions(-) diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index 4ea6ef3e..53937bd8 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -34,12 +34,12 @@ public final class BaritoneAPI { private static final Settings settings; static { + settings = new Settings(); + SettingsUtil.readAndApply(settings); + ServiceLoader baritoneLoader = ServiceLoader.load(IBaritoneProvider.class); Iterator instances = baritoneLoader.iterator(); provider = instances.next(); - - settings = new Settings(); - SettingsUtil.readAndApply(settings); } public static IBaritoneProvider getProvider() { diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index 4ca48c24..fa8c5465 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -33,15 +33,6 @@ import baritone.api.utils.IPlayerContext; */ public interface IBaritone { - /** - * Call as soon as Minecraft is ready, initializes all of the processes, behaviors, etc. This will - * only effectively be ran once, any additional calls are redundant because the initialization state - * is saved. - *

- * Or whenever your overeager utility client wants. - */ - void init(); - /** * @return The {@link IPathingBehavior} instance * @see IPathingBehavior diff --git a/src/api/java/baritone/api/utils/ISchematic.java b/src/api/java/baritone/api/utils/ISchematic.java index b2dfc308..a60ca846 100644 --- a/src/api/java/baritone/api/utils/ISchematic.java +++ b/src/api/java/baritone/api/utils/ISchematic.java @@ -87,4 +87,4 @@ public interface ISchematic { * @return The length (Z axis length) of this schematic */ int lengthZ(); -} \ No newline at end of file +} diff --git a/src/api/java/baritone/api/utils/MyChunkPos.java b/src/api/java/baritone/api/utils/MyChunkPos.java index 8b61012f..7cda5aa3 100644 --- a/src/api/java/baritone/api/utils/MyChunkPos.java +++ b/src/api/java/baritone/api/utils/MyChunkPos.java @@ -34,4 +34,4 @@ public class MyChunkPos { public String toString() { return x + ", " + z; } -} \ No newline at end of file +} diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index bb00c8a7..c42d7ef8 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -17,10 +17,8 @@ package baritone.api.utils.command; -import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; -import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.api.utils.command.execution.CommandExecution; @@ -33,10 +31,9 @@ import java.util.Locale; import java.util.stream.Collectors; import java.util.stream.Stream; -public abstract class Command implements Helper, AbstractGameEventListener { - protected IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone(); - protected Settings settings = BaritoneAPI.getSettings(); - protected IPlayerContext ctx = baritone.getPlayerContext(); +public abstract class Command implements Helper { + protected IBaritone baritone; + protected IPlayerContext ctx; protected Minecraft MC = mc; /** @@ -49,15 +46,16 @@ public abstract class Command implements Helper, AbstractGameEventListener { * * @param names The names of this command. This is what you put after the command prefix. */ - protected Command(List names) { + protected Command(IBaritone baritone, List names) { this.names = names.stream() .map(s -> s.toLowerCase(Locale.US)) .collect(Collectors.toList()); - baritone.getGameEventHandler().registerEventListener(this); + this.baritone = baritone; + this.ctx = baritone.getPlayerContext(); } - protected Command(String name) { - this(Collections.singletonList(name)); + protected Command(IBaritone baritone, String name) { + this(baritone, Collections.singletonList(name)); } /** diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 6ee1a79b..9dc835cd 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -17,7 +17,6 @@ package baritone.launch.mixins; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.event.events.BlockInteractEvent; @@ -59,7 +58,7 @@ public class MixinMinecraft { at = @At("RETURN") ) private void postInit(CallbackInfo ci) { - ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).init(); + BaritoneAPI.getProvider().getPrimaryBaritone(); } @Inject( diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index aa787e10..e9c3990f 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -60,11 +60,6 @@ public class Baritone implements IBaritone { } } - /** - * Whether or not {@link Baritone#init()} has been called yet - */ - private boolean initialized; - private GameEventHandler gameEventHandler; private PathingBehavior pathingBehavior; @@ -92,13 +87,6 @@ public class Baritone implements IBaritone { Baritone() { this.gameEventHandler = new GameEventHandler(this); - } - - @Override - public synchronized void init() { - if (initialized) { - return; - } // Define this before behaviors try and get it, or else it will be null and the builds will fail! this.playerContext = PrimaryPlayerContext.INSTANCE; @@ -125,13 +113,11 @@ public class Baritone implements IBaritone { } this.worldProvider = new WorldProvider(); - this.selectionManager = new SelectionManager(); + this.selectionManager = new SelectionManager(this); if (BaritoneAutoTest.ENABLE_AUTO_TEST) { this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE); } - - this.initialized = true; } @Override @@ -240,4 +226,4 @@ public class Baritone implements IBaritone { public static Executor getExecutor() { return threadPool; } -} \ No newline at end of file +} diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index 9fdd0489..6293ca51 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -34,11 +34,13 @@ import java.util.List; */ public final class BaritoneProvider implements IBaritoneProvider { - private final Baritone primary = new Baritone(); - private final List all = Collections.singletonList(primary); + private final Baritone primary; + private final List all; { - DefaultCommands.COMMANDS.forEach(CommandManager.REGISTRY::register); + primary = new Baritone(); + all = Collections.singletonList(primary); + DefaultCommands.commands(primary).forEach(CommandManager.REGISTRY::register); new BaritoneChatControl(primary); } diff --git a/src/main/java/baritone/selection/SelectionManager.java b/src/main/java/baritone/selection/SelectionManager.java index 5fea4cba..6932b34f 100644 --- a/src/main/java/baritone/selection/SelectionManager.java +++ b/src/main/java/baritone/selection/SelectionManager.java @@ -1,5 +1,6 @@ package baritone.selection; +import baritone.Baritone; import baritone.api.selection.ISelection; import baritone.api.selection.ISelectionManager; import baritone.api.utils.BetterBlockPos; @@ -12,8 +13,8 @@ public class SelectionManager implements ISelectionManager { private final LinkedList selections = new LinkedList<>(); private ISelection[] selectionsArr = new ISelection[0]; - public SelectionManager() { - new SelectionRenderer(this); + public SelectionManager(Baritone baritone) { + new SelectionRenderer(baritone, this); } private void resetSelectionsArr() { diff --git a/src/main/java/baritone/selection/SelectionRenderer.java b/src/main/java/baritone/selection/SelectionRenderer.java index 435f7dc7..e8b75cab 100644 --- a/src/main/java/baritone/selection/SelectionRenderer.java +++ b/src/main/java/baritone/selection/SelectionRenderer.java @@ -1,5 +1,6 @@ package baritone.selection; +import baritone.Baritone; import baritone.api.event.events.RenderEvent; import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.selection.ISelection; @@ -11,7 +12,7 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener { private final SelectionManager manager; - SelectionRenderer(SelectionManager manager) { + SelectionRenderer(Baritone baritone, SelectionManager manager) { this.manager = manager; baritone.getGameEventHandler().registerEventListener(this); } diff --git a/src/main/java/baritone/utils/IRenderer.java b/src/main/java/baritone/utils/IRenderer.java index f08d0c39..049e6e0c 100644 --- a/src/main/java/baritone/utils/IRenderer.java +++ b/src/main/java/baritone/utils/IRenderer.java @@ -18,7 +18,6 @@ package baritone.utils; import baritone.api.BaritoneAPI; -import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.Helper; import net.minecraft.client.renderer.BufferBuilder; @@ -36,7 +35,6 @@ public interface IRenderer { Tessellator tessellator = Tessellator.getInstance(); BufferBuilder buffer = tessellator.getBuffer(); RenderManager renderManager = Helper.mc.getRenderManager(); - IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone(); Settings settings = BaritoneAPI.getSettings(); static void glColor(Color color, float alpha) { diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 3a32a18c..47a06854 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -115,4 +115,4 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri public BlockBreakHelper getBlockBreakHelper() { return blockBreakHelper; } -} \ No newline at end of file +} diff --git a/src/main/java/baritone/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java index 32c36d15..0b657d35 100644 --- a/src/main/java/baritone/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalAxis; @@ -29,8 +30,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class AxisCommand extends Command { - public AxisCommand() { - super(asList("axis", "highway")); + public AxisCommand(IBaritone baritone) { + super(baritone, asList("axis", "highway")); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index 926847f9..92796c17 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.process.IGetToBlockProcess; import baritone.api.utils.command.Command; @@ -29,8 +30,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class BlacklistCommand extends Command { - public BlacklistCommand() { - super("blacklist"); + public BlacklistCommand(IBaritone baritone) { + super(baritone, "blacklist"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index ac99b341..c6e42335 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; @@ -36,8 +37,8 @@ import static java.util.Arrays.asList; public class BuildCommand extends Command { private static final File schematicsDir = new File(Minecraft.getMinecraft().gameDir, "schematics"); - public BuildCommand() { - super("build"); + public BuildCommand(IBaritone baritone) { + super(baritone, "build"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index 3b45b5ab..1691f4eb 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -27,8 +28,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class CancelCommand extends Command { - public CancelCommand() { - super(asList("cancel", "stop")); + public CancelCommand(IBaritone baritone) { + super(baritone, asList("cancel", "stop")); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index 6d436cc7..bea68b59 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.cache.IRememberedInventory; import baritone.api.utils.BetterBlockPos; @@ -35,8 +36,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ChestsCommand extends Command { - public ChestsCommand() { - super("chests"); + public ChestsCommand(IBaritone baritone) { + super(baritone, "chests"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index 0f210234..eaa06898 100644 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; @@ -32,8 +33,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ClearareaCommand extends Command { - public ClearareaCommand() { - super("cleararea"); + public ClearareaCommand(IBaritone baritone) { + super(baritone, "cleararea"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java index 8f2a3c8f..eed1446d 100644 --- a/src/main/java/baritone/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -27,8 +28,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ClickCommand extends Command { - public ClickCommand() { - super("click"); + public ClickCommand(IBaritone baritone) { + super(baritone, "click"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index ad823300..43faf7c4 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.command.Command; @@ -32,8 +33,8 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class ComeCommand extends Command { - public ComeCommand() { - super("come"); + public ComeCommand(IBaritone baritone) { + super(baritone, "come"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/CommandAlias.java b/src/main/java/baritone/utils/command/defaults/CommandAlias.java index c407ca69..29c1539f 100644 --- a/src/main/java/baritone/utils/command/defaults/CommandAlias.java +++ b/src/main/java/baritone/utils/command/defaults/CommandAlias.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -30,14 +31,14 @@ public class CommandAlias extends Command { private final String shortDesc; public final String target; - public CommandAlias(List names, String shortDesc, String target) { - super(names); + public CommandAlias(IBaritone baritone, List names, String shortDesc, String target) { + super(baritone, names); this.shortDesc = shortDesc; this.target = target; } - public CommandAlias(String name, String shortDesc, String target) { - super(name); + public CommandAlias(IBaritone baritone, String name, String shortDesc, String target) { + super(baritone, name); this.shortDesc = shortDesc; this.target = target; } diff --git a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java index 9e65e10c..cccb2ee3 100644 --- a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java +++ b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java @@ -17,53 +17,60 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.utils.command.Command; -import java.util.Collections; -import java.util.List; +import java.util.*; import static java.util.Arrays.asList; public class DefaultCommands { - public static final List COMMANDS = Collections.unmodifiableList(asList( - new HelpCommand(), - new SetCommand(), - new CommandAlias(asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), - new CommandAlias("reset", "Reset all settings or just one", "set reset"), - new GoalCommand(), - new PathCommand(), - new ProcCommand(), - new VersionCommand(), - new RepackCommand(), - new BuildCommand(), - new SchematicaCommand(), - new ComeCommand(), - new AxisCommand(), - new CancelCommand(), - new ForceCancelCommand(), - new GcCommand(), - new InvertCommand(), - new ClearareaCommand(), - PauseResumeCommands.pauseCommand, - PauseResumeCommands.resumeCommand, - PauseResumeCommands.pausedCommand, - new TunnelCommand(), - new RenderCommand(), - new FarmCommand(), - new ChestsCommand(), - new FollowCommand(), - new ExploreFilterCommand(), - new ReloadAllCommand(), - new SaveAllCommand(), - new ExploreCommand(), - new BlacklistCommand(), - new FindCommand(), - new MineCommand(), - new ClickCommand(), - new ThisWayCommand(), - new WaypointsCommand(), - new CommandAlias("sethome", "Sets your home waypoint", "waypoints save home"), - new CommandAlias("home", "Set goal to your home waypoint", "waypoints goal home"), - new SelCommand() - )); + public static List commands(IBaritone baritone) { + Objects.requireNonNull(baritone); + List commands = new ArrayList<>(); + commands.addAll(Arrays.asList( + new HelpCommand(baritone), + new SetCommand(baritone), + new CommandAlias(baritone, asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), + new CommandAlias(baritone, "reset", "Reset all settings or just one", "set reset"), + new GoalCommand(baritone), + new PathCommand(baritone), + new ProcCommand(baritone), + new VersionCommand(baritone), + new RepackCommand(baritone), + new BuildCommand(baritone), + new SchematicaCommand(baritone), + new ComeCommand(baritone), + new AxisCommand(baritone), + new CancelCommand(baritone), + new ForceCancelCommand(baritone), + new GcCommand(baritone), + new InvertCommand(baritone), + new ClearareaCommand(baritone), + + new TunnelCommand(baritone), + new RenderCommand(baritone), + new FarmCommand(baritone), + new ChestsCommand(baritone), + new FollowCommand(baritone), + new ExploreFilterCommand(baritone), + new ReloadAllCommand(baritone), + new SaveAllCommand(baritone), + new ExploreCommand(baritone), + new BlacklistCommand(baritone), + new FindCommand(baritone), + new MineCommand(baritone), + new ClickCommand(baritone), + new ThisWayCommand(baritone), + new WaypointsCommand(baritone), + new CommandAlias(baritone, "sethome", "Sets your home waypoint", "waypoints save home"), + new CommandAlias(baritone, "home", "Set goal to your home waypoint", "waypoints goal home"), + new SelCommand(baritone) + )); + PauseResumeCommands prc = new PauseResumeCommands(baritone); + commands.add(prc.pauseCommand); + commands.add(prc.resumeCommand); + commands.add(prc.pausedCommand); + return Collections.unmodifiableList(commands); + } } diff --git a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java index 3a6f46e4..a09a856c 100644 --- a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java +++ b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -27,8 +28,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class EmptyCommand extends Command { - public EmptyCommand() { - super(asList("name1", "name2")); + public EmptyCommand(IBaritone baritone) { + super(baritone, asList("name1", "name2")); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index 2cc328d7..9c5870f1 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.command.Command; @@ -29,8 +30,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ExploreCommand extends Command { - public ExploreCommand() { - super("explore"); + public ExploreCommand(IBaritone baritone) { + super(baritone, "explore"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index ab0e1307..fa459adc 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeFile; @@ -33,8 +34,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ExploreFilterCommand extends Command { - public ExploreFilterCommand() { - super("explorefilter"); + public ExploreFilterCommand(IBaritone baritone) { + super(baritone, "explorefilter"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java index f125bfae..fb5d537f 100644 --- a/src/main/java/baritone/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -27,8 +28,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class FarmCommand extends Command { - public FarmCommand() { - super("farm"); + public FarmCommand(IBaritone baritone) { + super(baritone, "farm"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index 499a45c9..6324430d 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; @@ -31,8 +32,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class FindCommand extends Command { - public FindCommand() { - super("find"); + public FindCommand(IBaritone baritone) { + super(baritone, "find"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index 7b5362cc..26542207 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.EntityClassById; @@ -43,8 +44,8 @@ import static java.util.Objects.isNull; import static java.util.Objects.nonNull; public class FollowCommand extends Command { - public FollowCommand() { - super("follow"); + public FollowCommand(IBaritone baritone) { + super(baritone, "follow"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index 4facba0a..649fcc7d 100644 --- a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.behavior.IPathingBehavior; import baritone.api.utils.command.Command; @@ -28,8 +29,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ForceCancelCommand extends Command { - public ForceCancelCommand() { - super("forcecancel"); + public ForceCancelCommand(IBaritone baritone) { + super(baritone, "forcecancel"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index edf7c236..9dabcd43 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -27,8 +28,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class GcCommand extends Command { - public GcCommand() { - super("gc"); + public GcCommand(IBaritone baritone) { + super(baritone, "gc"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index 3af86a4c..e864d5c5 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.process.ICustomGoalProcess; @@ -35,8 +36,8 @@ import static java.util.Objects.isNull; import static java.util.Objects.nonNull; public class GoalCommand extends Command { - public GoalCommand() { - super("goal"); + public GoalCommand(IBaritone baritone) { + super(baritone, "goal"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index 5a7a022d..378b8fa3 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandNotFoundException; @@ -40,8 +41,8 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class HelpCommand extends Command { - public HelpCommand() { - super(asList("help", "?")); + public HelpCommand(IBaritone baritone) { + super(baritone, asList("help", "?")); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index 8000d584..d8d5f0b2 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalInverted; @@ -32,8 +33,8 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class InvertCommand extends Command { - public InvertCommand() { - super("invert"); + public InvertCommand(IBaritone baritone) { + super(baritone, "invert"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index 5cc12ff8..a846a310 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.command.Command; @@ -32,8 +33,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class MineCommand extends Command { - public MineCommand() { - super("mine"); + public MineCommand(IBaritone baritone) { + super(baritone, "mine"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index 3dcc79bd..ce9d8878 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.process.ICustomGoalProcess; @@ -35,8 +36,8 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class PathCommand extends Command { - public PathCommand() { - super(asList("path", "goto")); + public PathCommand(IBaritone baritone) { + super(baritone, asList("path", "goto")); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index 1242d153..199086a4 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -17,7 +17,7 @@ package baritone.utils.command.defaults; -import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.process.IBaritoneProcess; import baritone.api.process.PathingCommand; @@ -39,15 +39,17 @@ import static java.util.Arrays.asList; * REQUEST_PAUSE} as needed. */ public class PauseResumeCommands { - public static Command pauseCommand; - public static Command resumeCommand; - public static Command pausedCommand; + private final IBaritone baritone; + Command pauseCommand; + Command resumeCommand; + Command pausedCommand; - static { + public PauseResumeCommands(IBaritone baritone) { + this.baritone = baritone; // array for mutability, non-field so reflection can't touch it final boolean[] paused = {false}; - BaritoneAPI.getProvider().getPrimaryBaritone().getPathingControlManager().registerProcess( + baritone.getPathingControlManager().registerProcess( new IBaritoneProcess() { @Override public boolean isActive() { @@ -79,7 +81,7 @@ public class PauseResumeCommands { } ); - pauseCommand = new Command("pause") { + pauseCommand = new Command(baritone, "pause") { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); @@ -115,7 +117,7 @@ public class PauseResumeCommands { } }; - resumeCommand = new Command("resume") { + resumeCommand = new Command(baritone, "resume") { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); @@ -149,7 +151,7 @@ public class PauseResumeCommands { } }; - pausedCommand = new Command("paused") { + pausedCommand = new Command(baritone, "paused") { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index 816c1770..8d27d7d2 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.calc.IPathingControlManager; import baritone.api.process.IBaritoneProcess; @@ -32,8 +33,8 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class ProcCommand extends Command { - public ProcCommand() { - super("proc"); + public ProcCommand(IBaritone baritone) { + super(baritone, "proc"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index 1ac5c6d7..0cc025ff 100644 --- a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -27,8 +28,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ReloadAllCommand extends Command { - public ReloadAllCommand() { - super("reloadall"); + public ReloadAllCommand(IBaritone baritone) { + super(baritone, "reloadall"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index e59664f9..536e2847 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; @@ -28,8 +29,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class RenderCommand extends Command { - public RenderCommand() { - super("render"); + public RenderCommand(IBaritone baritone) { + super(baritone, "render"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java index b64d4b8e..6241541e 100644 --- a/src/main/java/baritone/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -28,8 +29,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class RepackCommand extends Command { - public RepackCommand() { - super(asList("repack", "rescan")); + public RepackCommand(IBaritone baritone) { + super(baritone, asList("repack", "rescan")); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index ae8d603d..80b2f321 100644 --- a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -27,8 +28,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class SaveAllCommand extends Command { - public SaveAllCommand() { - super("saveall"); + public SaveAllCommand(IBaritone baritone) { + super(baritone, "saveall"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index 1b83ded8..d684f1fd 100644 --- a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -27,8 +28,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class SchematicaCommand extends Command { - public SchematicaCommand() { - super("schematica"); + public SchematicaCommand(IBaritone baritone) { + super(baritone, "schematica"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index 9952b8a1..03293513 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -17,8 +17,11 @@ package baritone.utils.command.defaults; +import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.event.events.RenderEvent; +import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.schematic.*; import baritone.api.selection.ISelection; import baritone.api.selection.ISelectionManager; @@ -54,8 +57,25 @@ public class SelCommand extends Command { private ISelectionManager manager = baritone.getSelectionManager(); private BetterBlockPos pos1 = null; - public SelCommand() { - super(asList("sel", "selection", "s")); + public SelCommand(IBaritone baritone) { + super(baritone, asList("sel", "selection", "s")); + baritone.getGameEventHandler().registerEventListener(new AbstractGameEventListener() { + @Override + public void onRenderPass(RenderEvent event) { + if (!Baritone.settings().renderSelectionCorners.value || pos1 == null) { + return; + } + + Color color = Baritone.settings().colorSelectionPos1.value; + float opacity = Baritone.settings().selectionOpacity.value; + 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.endLines(ignoreDepth); + } + }); } @Override @@ -360,20 +380,4 @@ public class SelCommand extends Command { return names.toArray(new String[0]); } } - - @Override - public void onRenderPass(RenderEvent event) { - if (!settings.renderSelectionCorners.value || pos1 == null) { - return; - } - - Color color = settings.colorSelectionPos1.value; - float opacity = settings.selectionOpacity.value; - float lineWidth = settings.selectionLineWidth.value; - boolean ignoreDepth = settings.renderSelectionIgnoreDepth.value; - - IRenderer.startLines(color, opacity, lineWidth, ignoreDepth); - IRenderer.drawAABB(new AxisAlignedBB(pos1, pos1.add(1, 1, 1))); - IRenderer.endLines(ignoreDepth); - } } diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index 7fa33d26..a682fde4 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.SettingsUtil; import baritone.api.utils.command.Command; @@ -44,8 +45,8 @@ import static java.util.Objects.nonNull; import static java.util.stream.Stream.of; public class SetCommand extends Command { - public SetCommand() { - super(asList("set", "setting", "settings")); + public SetCommand(IBaritone baritone) { + super(baritone, asList("set", "setting", "settings")); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index e51f96a8..a3b431ea 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.command.Command; @@ -28,8 +29,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ThisWayCommand extends Command { - public ThisWayCommand() { - super(asList("thisway", "forward")); + public ThisWayCommand(IBaritone baritone) { + super(baritone, asList("thisway", "forward")); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index a355e2e2..95f25350 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalStrictDirection; @@ -29,8 +30,8 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class TunnelCommand extends Command { - public TunnelCommand() { - super("tunnel"); + public TunnelCommand(IBaritone baritone) { + super(baritone, "tunnel"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index f6e25be4..3711f06c 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandInvalidStateException; @@ -29,8 +30,8 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class VersionCommand extends Command { - public VersionCommand() { - super("version"); + public VersionCommand(IBaritone baritone) { + super(baritone, "version"); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index cf02f67b..f26c0f8e 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.cache.IWaypoint; import baritone.api.cache.Waypoint; @@ -49,8 +50,8 @@ import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFI import static java.util.Arrays.asList; public class WaypointsCommand extends Command { - public WaypointsCommand() { - super(asList("waypoints", "waypoint", "wp")); + public WaypointsCommand(IBaritone baritone) { + super(baritone, asList("waypoints", "waypoint", "wp")); } @Override From 0a38e6f6909c5baf007b31eae3a66c7eabbed327 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 13:40:46 -0700 Subject: [PATCH 637/682] standardize on this --- src/api/java/baritone/api/Settings.java | 1 + src/api/java/baritone/api/accessor/IGuiScreen.java | 1 + src/api/java/baritone/api/accessor/IItemStack.java | 1 + .../java/baritone/api/event/events/TabCompleteEvent.java | 3 +++ src/api/java/baritone/api/pathing/goals/GoalInverted.java | 1 + src/api/java/baritone/api/pathing/goals/GoalNear.java | 1 + .../baritone/api/pathing/goals/GoalStrictDirection.java | 1 + src/api/java/baritone/api/process/IExploreProcess.java | 1 + src/api/java/baritone/api/process/IFarmProcess.java | 1 + src/api/java/baritone/api/process/IMineProcess.java | 1 + src/api/java/baritone/api/schematic/AbstractSchematic.java | 1 + src/api/java/baritone/api/schematic/CompositeSchematic.java | 1 + .../baritone/api/schematic/CompositeSchematicEntry.java | 1 + src/api/java/baritone/api/schematic/FillSchematic.java | 1 + src/api/java/baritone/api/schematic/MaskSchematic.java | 1 + src/api/java/baritone/api/schematic/ReplaceSchematic.java | 1 + src/api/java/baritone/api/schematic/ShellSchematic.java | 1 + src/api/java/baritone/api/schematic/WallsSchematic.java | 1 + src/api/java/baritone/api/selection/ISelection.java | 1 + src/api/java/baritone/api/selection/ISelectionManager.java | 1 + src/api/java/baritone/api/utils/BetterBlockPos.java | 1 + src/api/java/baritone/api/utils/BlockOptionalMeta.java | 1 + .../java/baritone/api/utils/BlockOptionalMetaLookup.java | 1 + src/api/java/baritone/api/utils/BlockUtils.java | 1 + .../baritone/api/utils/command/BaritoneChatControl.java | 1 + src/api/java/baritone/api/utils/command/Command.java | 1 + .../java/baritone/api/utils/interfaces/IGoalRenderPos.java | 1 + src/launch/java/baritone/launch/mixins/MixinBitArray.java | 1 + .../baritone/launch/mixins/MixinBlockStateContainer.java | 1 + .../java/baritone/launch/mixins/MixinChatTabCompleter.java | 1 + src/launch/java/baritone/launch/mixins/MixinGuiChat.java | 1 + src/launch/java/baritone/launch/mixins/MixinGuiScreen.java | 1 + src/launch/java/baritone/launch/mixins/MixinItemStack.java | 1 + .../baritone/launch/mixins/MixinPlayerControllerMP.java | 1 + .../baritone/launch/mixins/MixinStateImplementation.java | 1 + .../java/baritone/launch/mixins/MixinTabCompleter.java | 1 + src/main/java/baritone/behavior/InventoryBehavior.java | 1 + src/main/java/baritone/behavior/MemoryBehavior.java | 1 + src/main/java/baritone/cache/CachedWorld.java | 1 + src/main/java/baritone/pathing/path/SplicedPath.java | 1 + src/main/java/baritone/process/BuilderProcess.java | 6 ++++++ src/main/java/baritone/process/ExploreProcess.java | 3 +++ src/main/java/baritone/process/MineProcess.java | 1 + src/main/java/baritone/selection/Selection.java | 1 + src/main/java/baritone/selection/SelectionManager.java | 1 + src/main/java/baritone/selection/SelectionRenderer.java | 1 + src/main/java/baritone/utils/BlockPlaceHelper.java | 1 + src/main/java/baritone/utils/IRenderer.java | 1 + src/main/java/baritone/utils/PathRenderer.java | 1 + src/main/java/baritone/utils/PathingCommandContext.java | 1 + src/main/java/baritone/utils/PathingControlManager.java | 1 + src/main/java/baritone/utils/PlayerMovementInput.java | 1 + src/main/java/baritone/utils/ToolSet.java | 1 + src/main/java/baritone/utils/accessor/IBitArray.java | 1 + .../java/baritone/utils/accessor/IBlockStateContainer.java | 1 + .../java/baritone/utils/accessor/IChunkProviderClient.java | 1 + .../java/baritone/utils/accessor/IPlayerControllerMP.java | 1 + src/main/java/baritone/utils/accessor/ITabCompleter.java | 1 + .../java/baritone/utils/command/defaults/AxisCommand.java | 1 + .../baritone/utils/command/defaults/BlacklistCommand.java | 1 + .../java/baritone/utils/command/defaults/BuildCommand.java | 1 + .../java/baritone/utils/command/defaults/CancelCommand.java | 1 + .../java/baritone/utils/command/defaults/ChestsCommand.java | 1 + .../baritone/utils/command/defaults/ClearareaCommand.java | 1 + .../java/baritone/utils/command/defaults/ClickCommand.java | 1 + .../java/baritone/utils/command/defaults/ComeCommand.java | 1 + .../java/baritone/utils/command/defaults/CommandAlias.java | 1 + .../baritone/utils/command/defaults/DefaultCommands.java | 1 + .../java/baritone/utils/command/defaults/EmptyCommand.java | 1 + .../baritone/utils/command/defaults/ExploreCommand.java | 1 + .../java/baritone/utils/command/defaults/FarmCommand.java | 1 + .../java/baritone/utils/command/defaults/FindCommand.java | 1 + .../java/baritone/utils/command/defaults/FollowCommand.java | 1 + .../baritone/utils/command/defaults/ForceCancelCommand.java | 1 + .../java/baritone/utils/command/defaults/GcCommand.java | 1 + .../java/baritone/utils/command/defaults/GoalCommand.java | 1 + .../java/baritone/utils/command/defaults/HelpCommand.java | 1 + .../java/baritone/utils/command/defaults/InvertCommand.java | 1 + .../java/baritone/utils/command/defaults/MineCommand.java | 1 + .../java/baritone/utils/command/defaults/PathCommand.java | 1 + .../utils/command/defaults/PauseResumeCommands.java | 1 + .../java/baritone/utils/command/defaults/ProcCommand.java | 1 + .../baritone/utils/command/defaults/ReloadAllCommand.java | 1 + .../java/baritone/utils/command/defaults/RenderCommand.java | 1 + .../java/baritone/utils/command/defaults/RepackCommand.java | 1 + .../baritone/utils/command/defaults/SaveAllCommand.java | 1 + .../baritone/utils/command/defaults/SchematicaCommand.java | 1 + .../java/baritone/utils/command/defaults/SelCommand.java | 1 + .../java/baritone/utils/command/defaults/SetCommand.java | 1 + .../baritone/utils/command/defaults/ThisWayCommand.java | 1 + .../java/baritone/utils/command/defaults/TunnelCommand.java | 1 + .../baritone/utils/command/defaults/VersionCommand.java | 1 + .../baritone/utils/command/defaults/WaypointsCommand.java | 1 + src/main/java/baritone/utils/pathing/Avoidance.java | 1 + src/main/java/baritone/utils/pathing/Favoring.java | 1 + src/main/java/baritone/utils/pathing/MutableMoveResult.java | 1 + src/main/java/baritone/utils/pathing/PathBase.java | 1 + src/main/java/baritone/utils/schematic/FillSchematic.java | 1 + src/main/java/baritone/utils/schematic/Schematic.java | 1 + .../java/baritone/pathing/movement/ActionCostsTest.java | 1 + .../java/baritone/utils/pathing/PathingBlockTypeTest.java | 1 + 101 files changed, 110 insertions(+) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 48b5a785..22d597da 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -1022,6 +1022,7 @@ public final class Settings { public final Map, Type> settingTypes; public final class Setting { + public T value; public final T defaultValue; private String name; diff --git a/src/api/java/baritone/api/accessor/IGuiScreen.java b/src/api/java/baritone/api/accessor/IGuiScreen.java index 3eed255f..ba01e275 100644 --- a/src/api/java/baritone/api/accessor/IGuiScreen.java +++ b/src/api/java/baritone/api/accessor/IGuiScreen.java @@ -20,5 +20,6 @@ package baritone.api.accessor; import java.net.URI; public interface IGuiScreen { + void openLink(URI url); } diff --git a/src/api/java/baritone/api/accessor/IItemStack.java b/src/api/java/baritone/api/accessor/IItemStack.java index ac0f760f..480c713f 100644 --- a/src/api/java/baritone/api/accessor/IItemStack.java +++ b/src/api/java/baritone/api/accessor/IItemStack.java @@ -18,5 +18,6 @@ package baritone.api.accessor; public interface IItemStack { + int getBaritoneHash(); } diff --git a/src/api/java/baritone/api/event/events/TabCompleteEvent.java b/src/api/java/baritone/api/event/events/TabCompleteEvent.java index d5bed1ff..fea1da29 100644 --- a/src/api/java/baritone/api/event/events/TabCompleteEvent.java +++ b/src/api/java/baritone/api/event/events/TabCompleteEvent.java @@ -24,6 +24,7 @@ import baritone.api.event.events.type.Overrideable; * @author LoganDark */ public abstract class TabCompleteEvent extends Cancellable { + public final Overrideable prefix; public final Overrideable completions; @@ -37,12 +38,14 @@ public abstract class TabCompleteEvent extends Cancellable { } public static final class Pre extends TabCompleteEvent { + public Pre(String prefix) { super(prefix, null); } } public static final class Post extends TabCompleteEvent { + public Post(String prefix, String[] completions) { super(prefix, completions); } diff --git a/src/api/java/baritone/api/pathing/goals/GoalInverted.java b/src/api/java/baritone/api/pathing/goals/GoalInverted.java index 9f793a41..19736924 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalInverted.java +++ b/src/api/java/baritone/api/pathing/goals/GoalInverted.java @@ -28,6 +28,7 @@ package baritone.api.pathing.goals; * @author LoganDark */ public class GoalInverted implements Goal { + public final Goal origin; public GoalInverted(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 78f3b5f6..73d64ed9 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalNear.java +++ b/src/api/java/baritone/api/pathing/goals/GoalNear.java @@ -22,6 +22,7 @@ import baritone.api.utils.interfaces.IGoalRenderPos; import net.minecraft.util.math.BlockPos; public class GoalNear implements Goal, IGoalRenderPos { + private final int x; private final int y; private final int z; diff --git a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java index 1f2efd05..b48a029a 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java +++ b/src/api/java/baritone/api/pathing/goals/GoalStrictDirection.java @@ -25,6 +25,7 @@ import net.minecraft.util.math.BlockPos; * Dig a tunnel in a certain direction, but if you have to deviate from the path, go back to where you started */ public class GoalStrictDirection implements Goal { + public final int x; public final int y; public final int z; diff --git a/src/api/java/baritone/api/process/IExploreProcess.java b/src/api/java/baritone/api/process/IExploreProcess.java index 811a509f..4950d31d 100644 --- a/src/api/java/baritone/api/process/IExploreProcess.java +++ b/src/api/java/baritone/api/process/IExploreProcess.java @@ -20,6 +20,7 @@ package baritone.api.process; import java.nio.file.Path; public interface IExploreProcess extends IBaritoneProcess { + void explore(int centerX, int centerZ); void applyJsonFilter(Path path, boolean invert) throws Exception; diff --git a/src/api/java/baritone/api/process/IFarmProcess.java b/src/api/java/baritone/api/process/IFarmProcess.java index c9234a24..6ced16fb 100644 --- a/src/api/java/baritone/api/process/IFarmProcess.java +++ b/src/api/java/baritone/api/process/IFarmProcess.java @@ -18,5 +18,6 @@ package baritone.api.process; public interface IFarmProcess extends IBaritoneProcess { + void farm(); } diff --git a/src/api/java/baritone/api/process/IMineProcess.java b/src/api/java/baritone/api/process/IMineProcess.java index 455e93ca..27c9d8d2 100644 --- a/src/api/java/baritone/api/process/IMineProcess.java +++ b/src/api/java/baritone/api/process/IMineProcess.java @@ -28,6 +28,7 @@ import java.util.Arrays; * @since 9/23/2018 */ public interface IMineProcess extends IBaritoneProcess { + /** * Begin to search for and mine the specified blocks until * the number of specified items to get from the blocks that diff --git a/src/api/java/baritone/api/schematic/AbstractSchematic.java b/src/api/java/baritone/api/schematic/AbstractSchematic.java index c1cb6bde..7a24e803 100644 --- a/src/api/java/baritone/api/schematic/AbstractSchematic.java +++ b/src/api/java/baritone/api/schematic/AbstractSchematic.java @@ -20,6 +20,7 @@ package baritone.api.schematic; import baritone.api.utils.ISchematic; public abstract class AbstractSchematic implements ISchematic { + protected int x; protected int y; protected int z; diff --git a/src/api/java/baritone/api/schematic/CompositeSchematic.java b/src/api/java/baritone/api/schematic/CompositeSchematic.java index 9d65d9d3..6913a8ac 100644 --- a/src/api/java/baritone/api/schematic/CompositeSchematic.java +++ b/src/api/java/baritone/api/schematic/CompositeSchematic.java @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.List; public class CompositeSchematic extends AbstractSchematic { + private final List schematics; private CompositeSchematicEntry[] schematicArr; diff --git a/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java b/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java index 6e97e41f..a26f356b 100644 --- a/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java +++ b/src/api/java/baritone/api/schematic/CompositeSchematicEntry.java @@ -20,6 +20,7 @@ package baritone.api.schematic; import baritone.api.utils.ISchematic; public class CompositeSchematicEntry { + public final ISchematic schematic; public final int x; public final int y; diff --git a/src/api/java/baritone/api/schematic/FillSchematic.java b/src/api/java/baritone/api/schematic/FillSchematic.java index 20b1c250..509f7a7b 100644 --- a/src/api/java/baritone/api/schematic/FillSchematic.java +++ b/src/api/java/baritone/api/schematic/FillSchematic.java @@ -24,6 +24,7 @@ import net.minecraft.init.Blocks; import java.util.List; public class FillSchematic extends AbstractSchematic { + private final BlockOptionalMeta bom; public FillSchematic(int x, int y, int z, BlockOptionalMeta bom) { diff --git a/src/api/java/baritone/api/schematic/MaskSchematic.java b/src/api/java/baritone/api/schematic/MaskSchematic.java index a0589cee..f74ccc8f 100644 --- a/src/api/java/baritone/api/schematic/MaskSchematic.java +++ b/src/api/java/baritone/api/schematic/MaskSchematic.java @@ -23,6 +23,7 @@ import net.minecraft.block.state.IBlockState; import java.util.List; public abstract class MaskSchematic extends AbstractSchematic { + private final ISchematic schematic; public MaskSchematic(ISchematic schematic) { diff --git a/src/api/java/baritone/api/schematic/ReplaceSchematic.java b/src/api/java/baritone/api/schematic/ReplaceSchematic.java index ca2577c8..1418fe0e 100644 --- a/src/api/java/baritone/api/schematic/ReplaceSchematic.java +++ b/src/api/java/baritone/api/schematic/ReplaceSchematic.java @@ -22,6 +22,7 @@ import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; public class ReplaceSchematic extends MaskSchematic { + private final BlockOptionalMetaLookup filter; private final Boolean[][][] cache; diff --git a/src/api/java/baritone/api/schematic/ShellSchematic.java b/src/api/java/baritone/api/schematic/ShellSchematic.java index d6a734be..4ead61b6 100644 --- a/src/api/java/baritone/api/schematic/ShellSchematic.java +++ b/src/api/java/baritone/api/schematic/ShellSchematic.java @@ -21,6 +21,7 @@ import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; public class ShellSchematic extends MaskSchematic { + public ShellSchematic(ISchematic schematic) { super(schematic); } diff --git a/src/api/java/baritone/api/schematic/WallsSchematic.java b/src/api/java/baritone/api/schematic/WallsSchematic.java index 388fdb4d..e05de1e7 100644 --- a/src/api/java/baritone/api/schematic/WallsSchematic.java +++ b/src/api/java/baritone/api/schematic/WallsSchematic.java @@ -21,6 +21,7 @@ import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; public class WallsSchematic extends MaskSchematic { + public WallsSchematic(ISchematic schematic) { super(schematic); } diff --git a/src/api/java/baritone/api/selection/ISelection.java b/src/api/java/baritone/api/selection/ISelection.java index 5a5690d9..59651feb 100644 --- a/src/api/java/baritone/api/selection/ISelection.java +++ b/src/api/java/baritone/api/selection/ISelection.java @@ -27,6 +27,7 @@ import net.minecraft.util.math.Vec3i; * types of build commands, however it can be used for anything. */ public interface ISelection { + /** * @return The first corner of this selection. This is meant to preserve the user's original first corner. */ diff --git a/src/api/java/baritone/api/selection/ISelectionManager.java b/src/api/java/baritone/api/selection/ISelectionManager.java index a078e6d1..de5ee288 100644 --- a/src/api/java/baritone/api/selection/ISelectionManager.java +++ b/src/api/java/baritone/api/selection/ISelectionManager.java @@ -25,6 +25,7 @@ import net.minecraft.util.EnumFacing; * the current selection. */ public interface ISelectionManager { + /** * Adds a new selection. The added selection is returned. * diff --git a/src/api/java/baritone/api/utils/BetterBlockPos.java b/src/api/java/baritone/api/utils/BetterBlockPos.java index 40122a86..dd986dee 100644 --- a/src/api/java/baritone/api/utils/BetterBlockPos.java +++ b/src/api/java/baritone/api/utils/BetterBlockPos.java @@ -34,6 +34,7 @@ import javax.annotation.Nonnull; * @author leijurv */ public final class BetterBlockPos extends BlockPos { + public final int x; public final int y; public final int z; diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index 22ba74ea..7effe4bd 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -38,6 +38,7 @@ import java.util.stream.Collectors; import static java.util.Objects.isNull; public final class BlockOptionalMeta { + private final Block block; private final int meta; private final boolean noMeta; diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index fe1c5e6a..a5f7d626 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -27,6 +27,7 @@ import java.util.List; import static java.util.Arrays.asList; public class BlockOptionalMetaLookup { + private final BlockOptionalMeta[] boms; public BlockOptionalMetaLookup(BlockOptionalMeta... boms) { diff --git a/src/api/java/baritone/api/utils/BlockUtils.java b/src/api/java/baritone/api/utils/BlockUtils.java index 633e3acb..8fad35f8 100644 --- a/src/api/java/baritone/api/utils/BlockUtils.java +++ b/src/api/java/baritone/api/utils/BlockUtils.java @@ -24,6 +24,7 @@ import java.util.HashMap; import java.util.Map; public class BlockUtils { + private static transient Map resourceCache = new HashMap<>(); public static String blockToString(Block block) { diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index 23bbd4a7..0684aa89 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -51,6 +51,7 @@ import static java.util.Objects.isNull; import static java.util.Objects.nonNull; public class BaritoneChatControl implements Helper, AbstractGameEventListener { + public final IBaritone baritone; public final IPlayerContext ctx; public final Settings settings = BaritoneAPI.getSettings(); diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index c42d7ef8..123adc01 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -32,6 +32,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; public abstract class Command implements Helper { + protected IBaritone baritone; protected IPlayerContext ctx; protected Minecraft MC = mc; diff --git a/src/api/java/baritone/api/utils/interfaces/IGoalRenderPos.java b/src/api/java/baritone/api/utils/interfaces/IGoalRenderPos.java index 5bbbc007..13e7e686 100644 --- a/src/api/java/baritone/api/utils/interfaces/IGoalRenderPos.java +++ b/src/api/java/baritone/api/utils/interfaces/IGoalRenderPos.java @@ -20,5 +20,6 @@ package baritone.api.utils.interfaces; import net.minecraft.util.math.BlockPos; public interface IGoalRenderPos { + BlockPos getGoalPos(); } diff --git a/src/launch/java/baritone/launch/mixins/MixinBitArray.java b/src/launch/java/baritone/launch/mixins/MixinBitArray.java index 2719cfa7..9383c9aa 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBitArray.java +++ b/src/launch/java/baritone/launch/mixins/MixinBitArray.java @@ -26,6 +26,7 @@ import org.spongepowered.asm.mixin.Unique; @Mixin(BitArray.class) public abstract class MixinBitArray implements IBitArray { + @Shadow @Final private long[] longArray; diff --git a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java index d3de16f0..8c08b03f 100644 --- a/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java +++ b/src/launch/java/baritone/launch/mixins/MixinBlockStateContainer.java @@ -30,6 +30,7 @@ import org.spongepowered.asm.mixin.gen.Accessor; @Mixin(BlockStateContainer.class) public abstract class MixinBlockStateContainer implements IBlockStateContainer { + @Shadow protected BitArray storage; diff --git a/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java index 3d56446c..797b6210 100644 --- a/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java +++ b/src/launch/java/baritone/launch/mixins/MixinChatTabCompleter.java @@ -25,6 +25,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(GuiChat.ChatTabCompleter.class) public abstract class MixinChatTabCompleter extends MixinTabCompleter { + @Inject( method = "*", at = @At("RETURN") diff --git a/src/launch/java/baritone/launch/mixins/MixinGuiChat.java b/src/launch/java/baritone/launch/mixins/MixinGuiChat.java index 8c0a7d63..9883c176 100644 --- a/src/launch/java/baritone/launch/mixins/MixinGuiChat.java +++ b/src/launch/java/baritone/launch/mixins/MixinGuiChat.java @@ -28,6 +28,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(GuiChat.class) public abstract class MixinGuiChat implements net.minecraft.util.ITabCompleter { + @Shadow private TabCompleter tabCompleter; diff --git a/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java b/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java index 78da7b21..9f91beaa 100644 --- a/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java +++ b/src/launch/java/baritone/launch/mixins/MixinGuiScreen.java @@ -26,6 +26,7 @@ import java.net.URI; @Mixin(GuiScreen.class) public abstract class MixinGuiScreen implements IGuiScreen { + @Override @Invoker("openWebLink") public abstract void openLink(URI url); diff --git a/src/launch/java/baritone/launch/mixins/MixinItemStack.java b/src/launch/java/baritone/launch/mixins/MixinItemStack.java index 2a690632..2ad4c187 100644 --- a/src/launch/java/baritone/launch/mixins/MixinItemStack.java +++ b/src/launch/java/baritone/launch/mixins/MixinItemStack.java @@ -30,6 +30,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ItemStack.class) public abstract class MixinItemStack implements IItemStack { + @Shadow @Final private Item item; diff --git a/src/launch/java/baritone/launch/mixins/MixinPlayerControllerMP.java b/src/launch/java/baritone/launch/mixins/MixinPlayerControllerMP.java index c0294355..88c4abec 100644 --- a/src/launch/java/baritone/launch/mixins/MixinPlayerControllerMP.java +++ b/src/launch/java/baritone/launch/mixins/MixinPlayerControllerMP.java @@ -26,6 +26,7 @@ import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(PlayerControllerMP.class) public abstract class MixinPlayerControllerMP implements IPlayerControllerMP { + @Accessor @Override public abstract void setIsHittingBlock(boolean isHittingBlock); diff --git a/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java b/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java index ea437084..fef47bbe 100644 --- a/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java +++ b/src/launch/java/baritone/launch/mixins/MixinStateImplementation.java @@ -26,6 +26,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(targets = "net.minecraft.block.state.BlockStateContainer$StateImplementation") public abstract class MixinStateImplementation { + @Shadow @Final private ImmutableMap, Comparable> properties; diff --git a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java index 4432505b..7de73ead 100644 --- a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java +++ b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java @@ -35,6 +35,7 @@ import static java.util.Objects.isNull; @Mixin(TabCompleter.class) public abstract class MixinTabCompleter implements ITabCompleter { + @Shadow @Final protected GuiTextField textField; diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 484efa19..63e6c91e 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -35,6 +35,7 @@ import java.util.Random; import java.util.function.Predicate; public final class InventoryBehavior extends Behavior { + public InventoryBehavior(Baritone baritone) { super(baritone); } diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index aac6b554..66ab10f3 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -255,6 +255,7 @@ public final class MemoryBehavior extends Behavior { } public static class EnderChestMemory { + private static final Map memory = new HashMap<>(); private final Path enderChest; private List contents; diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 237c460b..e7405390 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -288,6 +288,7 @@ public final class CachedWorld implements ICachedWorld, Helper { } private class PackerThread implements Runnable { + public void run() { while (true) { // TODO: Add CachedWorld unloading to remove the redundancy of having this diff --git a/src/main/java/baritone/pathing/path/SplicedPath.java b/src/main/java/baritone/pathing/path/SplicedPath.java index 686a15f0..1ba497d8 100644 --- a/src/main/java/baritone/pathing/path/SplicedPath.java +++ b/src/main/java/baritone/pathing/path/SplicedPath.java @@ -26,6 +26,7 @@ import baritone.utils.pathing.PathBase; import java.util.*; public class SplicedPath extends PathBase { + private final List path; private final List movements; diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 4d2bf89c..ab1400f8 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -58,6 +58,7 @@ import java.util.*; import static baritone.api.pathing.movement.ActionCosts.COST_INF; public final class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { + private HashSet incorrectPositions; private LongOpenHashSet observedCompleted; // positions that are completed even if they're out of render distance and we can't make sure right now private String name; @@ -207,6 +208,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } public static class Placement { + private final int hotbarSelection; private final BlockPos placeAgainst; private final EnumFacing side; @@ -603,6 +605,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } public static class JankyGoalComposite implements Goal { + private final Goal primary; private final Goal fallback; @@ -676,6 +679,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } public static class GoalAdjacent extends GoalGetToBlock { + private boolean allowSameLevel; private BlockPos no; @@ -708,6 +712,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } public static class GoalPlace extends GoalBlock { + public GoalPlace(BlockPos placeAt) { super(placeAt.up()); } @@ -758,6 +763,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil } public class BuilderCalculationContext extends CalculationContext { + private final List placeable; private final ISchematic schematic; private final int originX; diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 3fa3d413..220ae3b1 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -173,6 +173,7 @@ public final class ExploreProcess extends BaritoneProcessHelper implements IExpl } private interface IChunkFilter { + Status isAlreadyExplored(int chunkX, int chunkZ); int countRemain(); @@ -205,6 +206,7 @@ public final class ExploreProcess extends BaritoneProcessHelper implements IExpl } private class JsonChunkFilter implements IChunkFilter { + private final boolean invert; // if true, the list is interpreted as a list of chunks that are NOT explored, if false, the list is interpreted as a list of chunks that ARE explored private final LongOpenHashSet inFilter; private final MyChunkPos[] positions; @@ -257,6 +259,7 @@ public final class ExploreProcess extends BaritoneProcessHelper implements IExpl } private class EitherChunk implements IChunkFilter { + private final IChunkFilter a; private final IChunkFilter b; diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 01c24884..a2e1f120 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -52,6 +52,7 @@ import static baritone.api.pathing.movement.ActionCosts.COST_INF; * @author leijurv */ public final class MineProcess extends BaritoneProcessHelper implements IMineProcess { + private static final int ORE_LOCATIONS_COUNT = 64; private BlockOptionalMetaLookup filter; diff --git a/src/main/java/baritone/selection/Selection.java b/src/main/java/baritone/selection/Selection.java index 594c037f..58e069de 100644 --- a/src/main/java/baritone/selection/Selection.java +++ b/src/main/java/baritone/selection/Selection.java @@ -7,6 +7,7 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.Vec3i; public class Selection implements ISelection { + private final BetterBlockPos pos1; private final BetterBlockPos pos2; private final BetterBlockPos min; diff --git a/src/main/java/baritone/selection/SelectionManager.java b/src/main/java/baritone/selection/SelectionManager.java index 6932b34f..c7f21300 100644 --- a/src/main/java/baritone/selection/SelectionManager.java +++ b/src/main/java/baritone/selection/SelectionManager.java @@ -10,6 +10,7 @@ import java.util.LinkedList; import java.util.ListIterator; public class SelectionManager implements ISelectionManager { + private final LinkedList selections = new LinkedList<>(); private ISelection[] selectionsArr = new ISelection[0]; diff --git a/src/main/java/baritone/selection/SelectionRenderer.java b/src/main/java/baritone/selection/SelectionRenderer.java index e8b75cab..89104d03 100644 --- a/src/main/java/baritone/selection/SelectionRenderer.java +++ b/src/main/java/baritone/selection/SelectionRenderer.java @@ -8,6 +8,7 @@ import baritone.utils.IRenderer; import net.minecraft.util.math.AxisAlignedBB; public class SelectionRenderer implements IRenderer, AbstractGameEventListener { + public static final double SELECTION_BOX_EXPANSION = .005D; private final SelectionManager manager; diff --git a/src/main/java/baritone/utils/BlockPlaceHelper.java b/src/main/java/baritone/utils/BlockPlaceHelper.java index ee8f2b73..ed39fb0b 100644 --- a/src/main/java/baritone/utils/BlockPlaceHelper.java +++ b/src/main/java/baritone/utils/BlockPlaceHelper.java @@ -25,6 +25,7 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.RayTraceResult; public class BlockPlaceHelper implements Helper { + private final IPlayerContext ctx; private int rightClickTimer; diff --git a/src/main/java/baritone/utils/IRenderer.java b/src/main/java/baritone/utils/IRenderer.java index 049e6e0c..0078f227 100644 --- a/src/main/java/baritone/utils/IRenderer.java +++ b/src/main/java/baritone/utils/IRenderer.java @@ -32,6 +32,7 @@ import java.awt.*; import static org.lwjgl.opengl.GL11.*; public interface IRenderer { + Tessellator tessellator = Tessellator.getInstance(); BufferBuilder buffer = tessellator.getBuffer(); RenderManager renderManager = Helper.mc.getRenderManager(); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 6e262213..cc11f4e6 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -48,6 +48,7 @@ import static org.lwjgl.opengl.GL11.*; * @since 8/9/2018 */ public final class PathRenderer implements IRenderer { + private PathRenderer() {} public static void render(RenderEvent event, PathingBehavior behavior) { diff --git a/src/main/java/baritone/utils/PathingCommandContext.java b/src/main/java/baritone/utils/PathingCommandContext.java index 1e8bfe6a..c43166e9 100644 --- a/src/main/java/baritone/utils/PathingCommandContext.java +++ b/src/main/java/baritone/utils/PathingCommandContext.java @@ -23,6 +23,7 @@ import baritone.api.process.PathingCommandType; import baritone.pathing.movement.CalculationContext; public class PathingCommandContext extends PathingCommand { + public final CalculationContext desiredCalcContext; public PathingCommandContext(Goal goal, PathingCommandType commandType, CalculationContext context) { diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 14d921d0..a83e53a1 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -32,6 +32,7 @@ import net.minecraft.util.math.BlockPos; import java.util.*; public class PathingControlManager implements IPathingControlManager { + private final Baritone baritone; private final HashSet processes; // unGh private final List active; diff --git a/src/main/java/baritone/utils/PlayerMovementInput.java b/src/main/java/baritone/utils/PlayerMovementInput.java index f41e0f62..22e2063a 100644 --- a/src/main/java/baritone/utils/PlayerMovementInput.java +++ b/src/main/java/baritone/utils/PlayerMovementInput.java @@ -21,6 +21,7 @@ import baritone.api.utils.input.Input; import net.minecraft.util.MovementInput; public class PlayerMovementInput extends MovementInput { + private final InputOverrideHandler handler; PlayerMovementInput(InputOverrideHandler handler) { diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 2df2261a..90f06bb0 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -38,6 +38,7 @@ import java.util.function.Function; * @author Avery, Brady, leijurv */ public class ToolSet { + /** * A cache mapping a {@link Block} to how long it will take to break * with this toolset, given the optimum tool is used. diff --git a/src/main/java/baritone/utils/accessor/IBitArray.java b/src/main/java/baritone/utils/accessor/IBitArray.java index 1fd912a2..81501036 100644 --- a/src/main/java/baritone/utils/accessor/IBitArray.java +++ b/src/main/java/baritone/utils/accessor/IBitArray.java @@ -1,6 +1,7 @@ package baritone.utils.accessor; public interface IBitArray { + int getAtFast(int index); int[] toArray(); diff --git a/src/main/java/baritone/utils/accessor/IBlockStateContainer.java b/src/main/java/baritone/utils/accessor/IBlockStateContainer.java index aa2eaab4..7c47a9b8 100644 --- a/src/main/java/baritone/utils/accessor/IBlockStateContainer.java +++ b/src/main/java/baritone/utils/accessor/IBlockStateContainer.java @@ -5,6 +5,7 @@ import net.minecraft.util.BitArray; import net.minecraft.world.chunk.IBlockStatePalette; public interface IBlockStateContainer { + IBlockStatePalette getPalette(); BitArray getStorage(); diff --git a/src/main/java/baritone/utils/accessor/IChunkProviderClient.java b/src/main/java/baritone/utils/accessor/IChunkProviderClient.java index 19f14685..e5fde40b 100644 --- a/src/main/java/baritone/utils/accessor/IChunkProviderClient.java +++ b/src/main/java/baritone/utils/accessor/IChunkProviderClient.java @@ -21,5 +21,6 @@ import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import net.minecraft.world.chunk.Chunk; public interface IChunkProviderClient { + Long2ObjectMap loadedChunks(); } diff --git a/src/main/java/baritone/utils/accessor/IPlayerControllerMP.java b/src/main/java/baritone/utils/accessor/IPlayerControllerMP.java index 58959d6d..354b9eef 100644 --- a/src/main/java/baritone/utils/accessor/IPlayerControllerMP.java +++ b/src/main/java/baritone/utils/accessor/IPlayerControllerMP.java @@ -20,6 +20,7 @@ package baritone.utils.accessor; import net.minecraft.util.math.BlockPos; public interface IPlayerControllerMP { + void setIsHittingBlock(boolean isHittingBlock); BlockPos getCurrentBlock(); diff --git a/src/main/java/baritone/utils/accessor/ITabCompleter.java b/src/main/java/baritone/utils/accessor/ITabCompleter.java index 72733f27..e187c3e6 100644 --- a/src/main/java/baritone/utils/accessor/ITabCompleter.java +++ b/src/main/java/baritone/utils/accessor/ITabCompleter.java @@ -1,6 +1,7 @@ package baritone.utils.accessor; public interface ITabCompleter { + String getPrefix(); void setPrefix(String prefix); diff --git a/src/main/java/baritone/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java index 0b657d35..dd9d5a83 100644 --- a/src/main/java/baritone/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -30,6 +30,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class AxisCommand extends Command { + public AxisCommand(IBaritone baritone) { super(baritone, asList("axis", "highway")); } diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index 92796c17..d63a0315 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -30,6 +30,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class BlacklistCommand extends Command { + public BlacklistCommand(IBaritone baritone) { super(baritone, "blacklist"); } diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index c6e42335..e11f7ad2 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -35,6 +35,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class BuildCommand extends Command { + private static final File schematicsDir = new File(Minecraft.getMinecraft().gameDir, "schematics"); public BuildCommand(IBaritone baritone) { diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index 1691f4eb..742e2aaf 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class CancelCommand extends Command { + public CancelCommand(IBaritone baritone) { super(baritone, asList("cancel", "stop")); } diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index bea68b59..33a88075 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -36,6 +36,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ChestsCommand extends Command { + public ChestsCommand(IBaritone baritone) { super(baritone, "chests"); } diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index eaa06898..bfe3856d 100644 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -33,6 +33,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ClearareaCommand extends Command { + public ClearareaCommand(IBaritone baritone) { super(baritone, "cleararea"); } diff --git a/src/main/java/baritone/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java index eed1446d..126f64f6 100644 --- a/src/main/java/baritone/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ClickCommand extends Command { + public ClickCommand(IBaritone baritone) { super(baritone, "click"); } diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index 43faf7c4..0d8440c5 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -33,6 +33,7 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class ComeCommand extends Command { + public ComeCommand(IBaritone baritone) { super(baritone, "come"); } diff --git a/src/main/java/baritone/utils/command/defaults/CommandAlias.java b/src/main/java/baritone/utils/command/defaults/CommandAlias.java index 29c1539f..aba934b2 100644 --- a/src/main/java/baritone/utils/command/defaults/CommandAlias.java +++ b/src/main/java/baritone/utils/command/defaults/CommandAlias.java @@ -28,6 +28,7 @@ import java.util.List; import java.util.stream.Stream; public class CommandAlias extends Command { + private final String shortDesc; public final String target; diff --git a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java index cccb2ee3..e8af7891 100644 --- a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java +++ b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java @@ -25,6 +25,7 @@ import java.util.*; import static java.util.Arrays.asList; public class DefaultCommands { + public static List commands(IBaritone baritone) { Objects.requireNonNull(baritone); List commands = new ArrayList<>(); diff --git a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java index a09a856c..cc45e800 100644 --- a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java +++ b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class EmptyCommand extends Command { + public EmptyCommand(IBaritone baritone) { super(baritone, asList("name1", "name2")); } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index 9c5870f1..374f3260 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -30,6 +30,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ExploreCommand extends Command { + public ExploreCommand(IBaritone baritone) { super(baritone, "explore"); } diff --git a/src/main/java/baritone/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java index fb5d537f..ee699490 100644 --- a/src/main/java/baritone/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class FarmCommand extends Command { + public FarmCommand(IBaritone baritone) { super(baritone, "farm"); } diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index 6324430d..64dd9728 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -32,6 +32,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class FindCommand extends Command { + public FindCommand(IBaritone baritone) { super(baritone, "find"); } diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index 26542207..c82461f6 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -44,6 +44,7 @@ import static java.util.Objects.isNull; import static java.util.Objects.nonNull; public class FollowCommand extends Command { + public FollowCommand(IBaritone baritone) { super(baritone, "follow"); } diff --git a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index 649fcc7d..09d2065f 100644 --- a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -29,6 +29,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ForceCancelCommand extends Command { + public ForceCancelCommand(IBaritone baritone) { super(baritone, "forcecancel"); } diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index 9dabcd43..7a0b124a 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class GcCommand extends Command { + public GcCommand(IBaritone baritone) { super(baritone, "gc"); } diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index e864d5c5..20892037 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -36,6 +36,7 @@ import static java.util.Objects.isNull; import static java.util.Objects.nonNull; public class GoalCommand extends Command { + public GoalCommand(IBaritone baritone) { super(baritone, "goal"); } diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index 378b8fa3..fa6e760c 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -41,6 +41,7 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class HelpCommand extends Command { + public HelpCommand(IBaritone baritone) { super(baritone, asList("help", "?")); } diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index d8d5f0b2..133f428f 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -33,6 +33,7 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class InvertCommand extends Command { + public InvertCommand(IBaritone baritone) { super(baritone, "invert"); } diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index a846a310..61cb1c4d 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -33,6 +33,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class MineCommand extends Command { + public MineCommand(IBaritone baritone) { super(baritone, "mine"); } diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index ce9d8878..a51aa968 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -36,6 +36,7 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class PathCommand extends Command { + public PathCommand(IBaritone baritone) { super(baritone, asList("path", "goto")); } diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index 199086a4..87f1b4b1 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -39,6 +39,7 @@ import static java.util.Arrays.asList; * REQUEST_PAUSE} as needed. */ public class PauseResumeCommands { + private final IBaritone baritone; Command pauseCommand; Command resumeCommand; diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index 8d27d7d2..4c405ff6 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -33,6 +33,7 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class ProcCommand extends Command { + public ProcCommand(IBaritone baritone) { super(baritone, "proc"); } diff --git a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index 0cc025ff..e2528394 100644 --- a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ReloadAllCommand extends Command { + public ReloadAllCommand(IBaritone baritone) { super(baritone, "reloadall"); } diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index 536e2847..2eab0bd1 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -29,6 +29,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class RenderCommand extends Command { + public RenderCommand(IBaritone baritone) { super(baritone, "render"); } diff --git a/src/main/java/baritone/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java index 6241541e..0415ca7a 100644 --- a/src/main/java/baritone/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -29,6 +29,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class RepackCommand extends Command { + public RepackCommand(IBaritone baritone) { super(baritone, asList("repack", "rescan")); } diff --git a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index 80b2f321..2da1824d 100644 --- a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class SaveAllCommand extends Command { + public SaveAllCommand(IBaritone baritone) { super(baritone, "saveall"); } diff --git a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index d684f1fd..e54a6e79 100644 --- a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class SchematicaCommand extends Command { + public SchematicaCommand(IBaritone baritone) { super(baritone, "schematica"); } diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index 03293513..d48a79e4 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -54,6 +54,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class SelCommand extends Command { + private ISelectionManager manager = baritone.getSelectionManager(); private BetterBlockPos pos1 = null; diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index a682fde4..fff0e3d3 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -45,6 +45,7 @@ import static java.util.Objects.nonNull; import static java.util.stream.Stream.of; public class SetCommand extends Command { + public SetCommand(IBaritone baritone) { super(baritone, asList("set", "setting", "settings")); } diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index a3b431ea..99d816d7 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -29,6 +29,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ThisWayCommand extends Command { + public ThisWayCommand(IBaritone baritone) { super(baritone, asList("thisway", "forward")); } diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index 95f25350..6f60e0cd 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -30,6 +30,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class TunnelCommand extends Command { + public TunnelCommand(IBaritone baritone) { super(baritone, "tunnel"); } diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index 3711f06c..6ce54ca5 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -30,6 +30,7 @@ import static java.util.Arrays.asList; import static java.util.Objects.isNull; public class VersionCommand extends Command { + public VersionCommand(IBaritone baritone) { super(baritone, "version"); } diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index f26c0f8e..5d60b9d0 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -50,6 +50,7 @@ import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFI import static java.util.Arrays.asList; public class WaypointsCommand extends Command { + public WaypointsCommand(IBaritone baritone) { super(baritone, asList("waypoints", "waypoint", "wp")); } diff --git a/src/main/java/baritone/utils/pathing/Avoidance.java b/src/main/java/baritone/utils/pathing/Avoidance.java index 11b4a73f..ca377fb0 100644 --- a/src/main/java/baritone/utils/pathing/Avoidance.java +++ b/src/main/java/baritone/utils/pathing/Avoidance.java @@ -32,6 +32,7 @@ import java.util.Collections; import java.util.List; public class Avoidance { + private final int centerX; private final int centerY; private final int centerZ; diff --git a/src/main/java/baritone/utils/pathing/Favoring.java b/src/main/java/baritone/utils/pathing/Favoring.java index 56ccb006..bbc23c7f 100644 --- a/src/main/java/baritone/utils/pathing/Favoring.java +++ b/src/main/java/baritone/utils/pathing/Favoring.java @@ -25,6 +25,7 @@ import baritone.pathing.movement.CalculationContext; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; public final class Favoring { + private final Long2DoubleOpenHashMap favorings; public Favoring(IPlayerContext ctx, IPath previous, CalculationContext context) { diff --git a/src/main/java/baritone/utils/pathing/MutableMoveResult.java b/src/main/java/baritone/utils/pathing/MutableMoveResult.java index b6e1ba8a..17fc6ee2 100644 --- a/src/main/java/baritone/utils/pathing/MutableMoveResult.java +++ b/src/main/java/baritone/utils/pathing/MutableMoveResult.java @@ -25,6 +25,7 @@ import baritone.api.pathing.movement.ActionCosts; * @author leijurv */ public final class MutableMoveResult { + public int x; public int y; public int z; diff --git a/src/main/java/baritone/utils/pathing/PathBase.java b/src/main/java/baritone/utils/pathing/PathBase.java index 8bac2dc7..de10fdf3 100644 --- a/src/main/java/baritone/utils/pathing/PathBase.java +++ b/src/main/java/baritone/utils/pathing/PathBase.java @@ -26,6 +26,7 @@ import baritone.utils.BlockStateInterface; import net.minecraft.util.math.BlockPos; public abstract class PathBase implements IPath { + @Override public PathBase cutoffAtLoadedChunks(Object bsi0) { // <-- cursed cursed cursed if (!Baritone.settings().cutoffAtLoadBoundary.value) { diff --git a/src/main/java/baritone/utils/schematic/FillSchematic.java b/src/main/java/baritone/utils/schematic/FillSchematic.java index 86fc7bae..3216f59f 100644 --- a/src/main/java/baritone/utils/schematic/FillSchematic.java +++ b/src/main/java/baritone/utils/schematic/FillSchematic.java @@ -23,6 +23,7 @@ import net.minecraft.block.state.IBlockState; import java.util.List; public class FillSchematic implements ISchematic { + private final int widthX; private final int heightY; private final int lengthZ; diff --git a/src/main/java/baritone/utils/schematic/Schematic.java b/src/main/java/baritone/utils/schematic/Schematic.java index 93e78120..47461e60 100644 --- a/src/main/java/baritone/utils/schematic/Schematic.java +++ b/src/main/java/baritone/utils/schematic/Schematic.java @@ -25,6 +25,7 @@ import net.minecraft.nbt.NBTTagCompound; import java.util.List; public class Schematic implements ISchematic { + public final int widthX; public final int heightY; public final int lengthZ; diff --git a/src/test/java/baritone/pathing/movement/ActionCostsTest.java b/src/test/java/baritone/pathing/movement/ActionCostsTest.java index cce61e4b..9bfdafb0 100644 --- a/src/test/java/baritone/pathing/movement/ActionCostsTest.java +++ b/src/test/java/baritone/pathing/movement/ActionCostsTest.java @@ -23,6 +23,7 @@ import static baritone.api.pathing.movement.ActionCosts.*; import static org.junit.Assert.assertEquals; public class ActionCostsTest { + @Test public void testFallNBlocksCost() { assertEquals(FALL_N_BLOCKS_COST.length, 257); // Fall 0 blocks through fall 256 blocks diff --git a/src/test/java/baritone/utils/pathing/PathingBlockTypeTest.java b/src/test/java/baritone/utils/pathing/PathingBlockTypeTest.java index c30b45d1..d05a323b 100644 --- a/src/test/java/baritone/utils/pathing/PathingBlockTypeTest.java +++ b/src/test/java/baritone/utils/pathing/PathingBlockTypeTest.java @@ -22,6 +22,7 @@ import org.junit.Test; import static org.junit.Assert.assertTrue; public class PathingBlockTypeTest { + @Test public void testBits() { for (PathingBlockType type : PathingBlockType.values()) { From 61d4f102bad354d771cfc7622abe74e71c718b44 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 13:43:40 -0700 Subject: [PATCH 638/682] its too many blank lines --- .../api/event/events/type/Overrideable.java | 1 + .../api/schematic/CompositeSchematic.java | 4 -- .../baritone/api/schematic/FillSchematic.java | 2 - .../api/schematic/ReplaceSchematic.java | 1 - .../utils/command/BaritoneChatControl.java | 29 ------------ .../baritone/api/utils/command/Command.java | 1 - .../utils/command/argparser/ArgParser.java | 2 + .../command/argparser/ArgParserManager.java | 5 +-- .../command/argparser/DefaultArgParsers.java | 12 ++--- .../utils/command/argparser/IArgParser.java | 3 ++ .../command/argument/CommandArgument.java | 4 +- .../utils/command/datatypes/BlockById.java | 2 +- .../command/datatypes/EntityClassById.java | 2 +- .../datatypes/ForBlockOptionalMeta.java | 1 + .../command/datatypes/ForEnumFacing.java | 1 + .../utils/command/datatypes/ForWaypoints.java | 1 + .../utils/command/datatypes/IDatatype.java | 1 + .../utils/command/datatypes/IDatatypeFor.java | 1 + .../command/datatypes/IDatatypePost.java | 1 + .../command/datatypes/PlayerByUsername.java | 3 +- .../command/datatypes/RelativeBlockPos.java | 4 +- .../command/datatypes/RelativeCoordinate.java | 6 +-- .../utils/command/datatypes/RelativeFile.java | 4 +- .../utils/command/datatypes/RelativeGoal.java | 3 +- .../command/datatypes/RelativeGoalBlock.java | 2 +- .../command/datatypes/RelativeGoalXZ.java | 2 +- .../command/datatypes/RelativeGoalYLevel.java | 2 +- .../CommandErrorMessageException.java | 1 + .../command/exception/CommandException.java | 1 + .../CommandInvalidArgumentException.java | 2 +- .../CommandInvalidStateException.java | 1 + .../CommandInvalidTypeException.java | 1 + .../CommandNoParserForTypeException.java | 1 + .../CommandNotEnoughArgumentsException.java | 1 + .../exception/CommandNotFoundException.java | 1 + .../CommandTooManyArgumentsException.java | 1 + .../exception/CommandUnhandledException.java | 6 +-- .../command/execution/CommandExecution.java | 7 +-- .../helpers/arguments/ArgConsumer.java | 10 +---- .../command/helpers/pagination/Paginator.java | 16 +------ .../tabcomplete/TabCompleteHelper.java | 6 +-- .../utils/command/manager/CommandManager.java | 5 +-- .../api/utils/command/registry/Registry.java | 6 +-- .../calc/openset/LinkedListOpenSet.java | 2 + .../command/defaults/BlacklistCommand.java | 2 - .../utils/command/defaults/BuildCommand.java | 8 ---- .../utils/command/defaults/ChestsCommand.java | 4 -- .../command/defaults/ClearareaCommand.java | 4 -- .../utils/command/defaults/ComeCommand.java | 2 - .../command/defaults/DefaultCommands.java | 1 - .../command/defaults/ExploreCommand.java | 3 -- .../defaults/ExploreFilterCommand.java | 5 +-- .../utils/command/defaults/FindCommand.java | 3 -- .../utils/command/defaults/FollowCommand.java | 14 ------ .../utils/command/defaults/GcCommand.java | 2 - .../utils/command/defaults/GoalCommand.java | 6 --- .../utils/command/defaults/HelpCommand.java | 10 ----- .../utils/command/defaults/InvertCommand.java | 4 -- .../utils/command/defaults/MineCommand.java | 2 - .../utils/command/defaults/PathCommand.java | 5 --- .../command/defaults/PauseResumeCommands.java | 9 ---- .../utils/command/defaults/ProcCommand.java | 3 -- .../utils/command/defaults/RenderCommand.java | 2 - .../utils/command/defaults/SelCommand.java | 44 ------------------- .../utils/command/defaults/SetCommand.java | 31 ------------- .../command/defaults/ThisWayCommand.java | 2 - .../utils/command/defaults/TunnelCommand.java | 2 - .../command/defaults/VersionCommand.java | 2 - .../command/defaults/WaypointsCommand.java | 27 ------------ .../schematica/SchematicAdapter.java | 1 + .../lunatrius/core/util/math/MBlockPos.java | 1 + .../lunatrius/schematica/Schematica.java | 1 + .../lunatrius/schematica/api/ISchematic.java | 1 + .../client/world/SchematicWorld.java | 1 + .../schematica/proxy/ClientProxy.java | 1 + 75 files changed, 55 insertions(+), 316 deletions(-) diff --git a/src/api/java/baritone/api/event/events/type/Overrideable.java b/src/api/java/baritone/api/event/events/type/Overrideable.java index 1ce7934e..cbad9b99 100644 --- a/src/api/java/baritone/api/event/events/type/Overrideable.java +++ b/src/api/java/baritone/api/event/events/type/Overrideable.java @@ -21,6 +21,7 @@ package baritone.api.event.events.type; * @author LoganDark */ public class Overrideable { + private T value; private boolean modified; diff --git a/src/api/java/baritone/api/schematic/CompositeSchematic.java b/src/api/java/baritone/api/schematic/CompositeSchematic.java index 6913a8ac..21df29b4 100644 --- a/src/api/java/baritone/api/schematic/CompositeSchematic.java +++ b/src/api/java/baritone/api/schematic/CompositeSchematic.java @@ -30,7 +30,6 @@ public class CompositeSchematic extends AbstractSchematic { private void recalcArr() { schematicArr = schematics.toArray(new CompositeSchematicEntry[0]); - for (CompositeSchematicEntry entry : schematicArr) { this.x = Math.max(x, entry.x + entry.schematic.widthX()); this.y = Math.max(y, entry.y + entry.schematic.heightY()); @@ -56,7 +55,6 @@ public class CompositeSchematic extends AbstractSchematic { return entry; } } - return null; } @@ -69,11 +67,9 @@ public class CompositeSchematic extends AbstractSchematic { @Override public IBlockState desiredState(int x, int y, int z, IBlockState current, List approxPlaceable) { CompositeSchematicEntry entry = getSchematic(x, y, z, current); - if (entry == null) { throw new IllegalStateException("couldn't find schematic for this position"); } - return entry.schematic.desiredState(x - entry.x, y - entry.y, z - entry.z, current, approxPlaceable); } } diff --git a/src/api/java/baritone/api/schematic/FillSchematic.java b/src/api/java/baritone/api/schematic/FillSchematic.java index 509f7a7b..aaaeb5dd 100644 --- a/src/api/java/baritone/api/schematic/FillSchematic.java +++ b/src/api/java/baritone/api/schematic/FillSchematic.java @@ -43,13 +43,11 @@ public class FillSchematic extends AbstractSchematic { } else if (current.getBlock() != Blocks.AIR) { return Blocks.AIR.getDefaultState(); } - for (IBlockState placeable : approxPlaceable) { if (bom.matches(placeable)) { return placeable; } } - return bom.getAnyBlockState(); } } diff --git a/src/api/java/baritone/api/schematic/ReplaceSchematic.java b/src/api/java/baritone/api/schematic/ReplaceSchematic.java index 1418fe0e..988cfd7f 100644 --- a/src/api/java/baritone/api/schematic/ReplaceSchematic.java +++ b/src/api/java/baritone/api/schematic/ReplaceSchematic.java @@ -37,7 +37,6 @@ public class ReplaceSchematic extends MaskSchematic { if (cache[x][y][z] == null) { cache[x][y][z] = filter.has(currentState); } - return cache[x][y][z]; } } diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index 0684aa89..d7b07872 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -68,12 +68,9 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { String msg = event.getMessage(); String prefix = settings.prefix.value; boolean forceRun = msg.startsWith(FORCE_COMMAND_PREFIX); - if ((settings.prefixControl.value && msg.startsWith(prefix)) || forceRun) { event.cancel(); - String commandStr = msg.substring(forceRun ? FORCE_COMMAND_PREFIX.length() : prefix.length()); - if (!runCommand(commandStr) && !commandStr.trim().isEmpty()) { new CommandNotFoundException(CommandExecution.expand(commandStr).first()).handle(null, null); } @@ -86,7 +83,6 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (settings.echoCommands.value) { String msg = command + rest; String toDisplay = settings.censorRanCommands.value ? command + " ..." : msg; - ITextComponent component = new TextComponentString(String.format("> %s", toDisplay)); component.getStyle() .setColor(TextFormatting.WHITE) @@ -98,7 +94,6 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { ClickEvent.Action.RUN_COMMAND, FORCE_COMMAND_PREFIX + msg )); - logDirect(component); } } @@ -111,31 +106,24 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { try { ((IGuiScreen) mc.currentScreen).openLink(new URI("https://www.dominos.com/en/pages/order/")); } catch (NullPointerException | URISyntaxException ignored) {} - return false; } - if (msg.isEmpty()) { msg = "help"; } - Pair> pair = CommandExecution.expand(msg); String command = pair.first(); String rest = msg.substring(pair.first().length()); ArgConsumer argc = new ArgConsumer(pair.second()); - if (!argc.has()) { Settings.Setting setting = settings.byLowerName.get(command.toLowerCase(Locale.US)); - if (setting != null) { logRanCommand(command, rest); - if (setting.getValueClass() == Boolean.class) { CommandManager.execute(String.format("set toggle %s", setting.getName())); } else { CommandManager.execute(String.format("set %s", setting.getName())); } - return true; } } else if (argc.hasExactlyOne()) { @@ -143,7 +131,6 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (setting.getName().equals("logger")) { continue; } - if (setting.getName().equalsIgnoreCase(pair.first())) { logRanCommand(command, rest); CommandManager.execute(String.format("set %s %s", setting.getName(), argc.getString())); @@ -151,16 +138,12 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } } } - CommandExecution execution = CommandExecution.from(pair); - if (isNull(execution)) { return false; } - logRanCommand(command, rest); CommandManager.execute(execution); - return true; } @@ -169,30 +152,23 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (!settings.prefixControl.value) { return; } - String prefix = event.prefix.get(); String commandPrefix = settings.prefix.value; - if (!prefix.startsWith(commandPrefix)) { return; } - String msg = prefix.substring(commandPrefix.length()); - List args = CommandArgument.from(msg, true); Stream stream = tabComplete(msg); - if (args.size() == 1) { stream = stream.map(x -> commandPrefix + x); } - event.completions.set(stream.toArray(String[]::new)); } public Stream tabComplete(String msg) { List args = CommandArgument.from(msg, true); ArgConsumer argc = new ArgConsumer(args); - if (argc.hasAtMost(2)) { if (argc.hasExactly(1)) { return new TabCompleteHelper() @@ -201,26 +177,21 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { .filterPrefix(argc.getString()) .stream(); } - Settings.Setting setting = settings.byLowerName.get(argc.getString().toLowerCase(Locale.US)); - if (nonNull(setting)) { if (setting.getValueClass() == Boolean.class) { TabCompleteHelper helper = new TabCompleteHelper(); - if ((Boolean) setting.value) { helper.append(Stream.of("true", "false")); } else { helper.append(Stream.of("false", "true")); } - return helper.filterPrefix(argc.getString()).stream(); } else { return Stream.of(SettingsUtil.settingValueToString(setting)); } } } - return CommandManager.tabComplete(msg); } } diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index 123adc01..0c982854 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -36,7 +36,6 @@ public abstract class Command implements Helper { protected IBaritone baritone; protected IPlayerContext ctx; protected Minecraft MC = mc; - /** * The names of this command. This is what you put after the command prefix. */ diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParser.java b/src/api/java/baritone/api/utils/command/argparser/ArgParser.java index 8fc08e86..af0083b7 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParser.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParser.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.argparser; public abstract class ArgParser implements IArgParser { + private final Class klass; protected ArgParser(Class klass) { @@ -30,6 +31,7 @@ public abstract class ArgParser implements IArgParser { } public static abstract class Stated extends ArgParser implements IArgParser.Stated { + private final Class stateKlass; protected Stated(Class klass, Class stateKlass) { diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index 7237ea07..8d8d160b 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -25,6 +25,7 @@ import baritone.api.utils.command.registry.Registry; import static java.util.Objects.isNull; public class ArgParserManager { + public static final Registry REGISTRY = new Registry<>(); static { @@ -73,11 +74,9 @@ public class ArgParserManager { */ public static T parseStateless(Class klass, CommandArgument arg) { ArgParser.Stateless parser = getParserStateless(klass); - if (isNull(parser)) { throw new CommandNoParserForTypeException(klass); } - try { return parser.parseArg(arg); } catch (RuntimeException exc) { @@ -98,11 +97,9 @@ public class ArgParserManager { */ public static T parseStated(Class klass, Class stateKlass, CommandArgument arg, S state) { ArgParser.Stated parser = getParserStated(klass, stateKlass); - if (isNull(parser)) { throw new CommandNoParserForTypeException(klass); } - try { return parser.parseArg(arg, state); } catch (RuntimeException exc) { diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index 7518e459..743380e7 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -25,7 +25,9 @@ import java.util.Locale; import static java.util.Arrays.asList; public class DefaultArgParsers { + public static class IntArgumentParser extends ArgParser implements IArgParser.Stateless { + public static final IntArgumentParser INSTANCE = new IntArgumentParser(); public IntArgumentParser() { @@ -39,6 +41,7 @@ public class DefaultArgParsers { } public static class LongArgumentParser extends ArgParser implements IArgParser.Stateless { + public static final LongArgumentParser INSTANCE = new LongArgumentParser(); public LongArgumentParser() { @@ -52,6 +55,7 @@ public class DefaultArgParsers { } public static class FloatArgumentParser extends ArgParser implements IArgParser.Stateless { + public static final FloatArgumentParser INSTANCE = new FloatArgumentParser(); public FloatArgumentParser() { @@ -61,16 +65,15 @@ public class DefaultArgParsers { @Override public Float parseArg(CommandArgument arg) throws RuntimeException { String value = arg.value; - if (!value.matches("^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$")) { throw new RuntimeException("failed float format check"); } - return Float.parseFloat(value); } } public static class DoubleArgumentParser extends ArgParser implements IArgParser.Stateless { + public static final DoubleArgumentParser INSTANCE = new DoubleArgumentParser(); public DoubleArgumentParser() { @@ -80,18 +83,16 @@ public class DefaultArgParsers { @Override public Double parseArg(CommandArgument arg) throws RuntimeException { String value = arg.value; - if (!value.matches("^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$")) { throw new RuntimeException("failed double format check"); } - return Double.parseDouble(value); } } public static class BooleanArgumentParser extends ArgParser implements IArgParser.Stateless { - public static final BooleanArgumentParser INSTANCE = new BooleanArgumentParser(); + public static final BooleanArgumentParser INSTANCE = new BooleanArgumentParser(); public static final List TRUTHY_VALUES = asList("1", "true", "yes", "t", "y", "on", "enable"); public static final List FALSY_VALUES = asList("0", "false", "no", "f", "n", "off", "disable"); @@ -102,7 +103,6 @@ public class DefaultArgParsers { @Override public Boolean parseArg(CommandArgument arg) throws RuntimeException { String value = arg.value; - if (TRUTHY_VALUES.contains(value.toLowerCase(Locale.US))) { return true; } else if (FALSY_VALUES.contains(value.toLowerCase(Locale.US))) { diff --git a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java index c8ac7630..47347c8e 100644 --- a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java +++ b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java @@ -20,6 +20,7 @@ package baritone.api.utils.command.argparser; import baritone.api.utils.command.argument.CommandArgument; public interface IArgParser { + /** * @return the class of this parser. */ @@ -31,6 +32,7 @@ public interface IArgParser { * @see ArgParserManager#REGISTRY */ interface Stateless extends IArgParser { + /** * @param arg The argument to parse. * @return What it was parsed into. @@ -47,6 +49,7 @@ public interface IArgParser { * @see ArgParserManager#REGISTRY */ interface Stated extends IArgParser { + Class getStateKlass(); /** diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index 49d8f477..cfd4f44e 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -38,6 +38,7 @@ import java.util.regex.Pattern; * You're recommended to use {@link ArgConsumer}s to handle these. Check out {@link ArgConsumer#from(String)} */ public class CommandArgument { + public final int index; public final String value; public final String rawRest; @@ -149,14 +150,11 @@ public class CommandArgument { argMatcher.group(), string.substring(argMatcher.start()) )); - lastEnd = argMatcher.end(); } - if (preserveEmptyLast && lastEnd < string.length()) { args.add(new CommandArgument(args.size(), "", "")); } - return args; } diff --git a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java index e8d1589c..e2cf319b 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java @@ -26,6 +26,7 @@ import net.minecraft.util.ResourceLocation; import java.util.stream.Stream; public class BlockById implements IDatatypeFor { + public final Block block; public BlockById() { @@ -34,7 +35,6 @@ public class BlockById implements IDatatypeFor { public BlockById(ArgConsumer consumer) { ResourceLocation id = new ResourceLocation(consumer.getString()); - if ((block = Block.REGISTRY.getObject(id)) == Blocks.AIR) { throw new IllegalArgumentException("no block found by that id"); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java index fd053584..a6dcad75 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import static java.util.Objects.isNull; public class EntityClassById implements IDatatypeFor> { + public final Class entity; public EntityClassById() { @@ -36,7 +37,6 @@ public class EntityClassById implements IDatatypeFor> { public EntityClassById(ArgConsumer consumer) { ResourceLocation id = new ResourceLocation(consumer.getString()); - if (isNull(entity = EntityList.REGISTRY.getObject(id))) { throw new IllegalArgumentException("no entity found by that id"); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java b/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java index e44b7652..cffdb54e 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java @@ -23,6 +23,7 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; public class ForBlockOptionalMeta implements IDatatypeFor { + public final BlockOptionalMeta selector; public ForBlockOptionalMeta() { diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java index f91eea0a..8bee4d41 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java @@ -26,6 +26,7 @@ import java.util.Locale; import java.util.stream.Stream; public class ForEnumFacing implements IDatatypeFor { + private final EnumFacing facing; public ForEnumFacing() { diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java index c6720b1c..6aef2187 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -28,6 +28,7 @@ import java.util.Comparator; import java.util.stream.Stream; public class ForWaypoints implements IDatatypeFor { + private final IWaypoint[] waypoints; public ForWaypoints() { diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java index 5af2a0b8..c79ff495 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java @@ -31,6 +31,7 @@ import java.util.stream.Stream; * can create an instance for tab completion. */ public interface IDatatype { + /** * One benefit over datatypes over {@link ArgParser}s is that instead of each command trying to guess what values * the datatype will accept, or simply not tab completing at all, datatypes that support tab completion can provide diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java index f0c4cb61..126e73b2 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java @@ -18,5 +18,6 @@ package baritone.api.utils.command.datatypes; public interface IDatatypeFor extends IDatatype { + T get(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java index 4e74f03e..6b6e10b1 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java @@ -18,5 +18,6 @@ package baritone.api.utils.command.datatypes; public interface IDatatypePost extends IDatatype { + T apply(O original); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java index 376f6b63..d8406606 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java +++ b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java @@ -28,6 +28,7 @@ import java.util.stream.Stream; import static java.util.Objects.isNull; public class PlayerByUsername implements IDatatypeFor { + private final List players = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().playerEntities; public final EntityPlayer player; @@ -38,13 +39,11 @@ public class PlayerByUsername implements IDatatypeFor { public PlayerByUsername(ArgConsumer consumer) { String username = consumer.getString(); - player = players .stream() .filter(s -> s.getName().equalsIgnoreCase(username)) .findFirst() .orElse(null); - if (isNull(player)) { throw new IllegalArgumentException("no player found by that username"); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java index f8b778df..b69fe003 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java @@ -25,6 +25,7 @@ import java.util.stream.Stream; import static java.util.Objects.isNull; public class RelativeBlockPos implements IDatatypePost { + final RelativeCoordinate x; final RelativeCoordinate y; final RelativeCoordinate z; @@ -57,13 +58,10 @@ public class RelativeBlockPos implements IDatatypePost { - public static Pattern PATTERN = Pattern.compile("^(~?)([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$"); + public static Pattern PATTERN = Pattern.compile("^(~?)([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$"); final boolean isRelative; final double offset; @@ -37,11 +37,9 @@ public class RelativeCoordinate implements IDatatypePost { public RelativeCoordinate(ArgConsumer consumer) { Matcher matcher = PATTERN.matcher(consumer.getString()); - if (!matcher.matches()) { throw new IllegalArgumentException("pattern doesn't match"); } - isRelative = !matcher.group(1).isEmpty(); offset = matcher.group(2).isEmpty() ? 0 : Double.parseDouble(matcher.group(2)); } @@ -51,7 +49,6 @@ public class RelativeCoordinate implements IDatatypePost { if (isRelative) { return origin + offset; } - return offset; } @@ -64,7 +61,6 @@ public class RelativeCoordinate implements IDatatypePost { if (!consumer.has(2) && consumer.getString().matches("^(~|$)")) { return Stream.of("~"); } - return Stream.empty(); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index af790332..f67e4fab 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -32,6 +32,7 @@ import java.util.stream.Stream; import static baritone.api.utils.Helper.HELPER; public class RelativeFile implements IDatatypePost { + private final Path path; public RelativeFile() { @@ -75,7 +76,6 @@ public class RelativeFile implements IDatatypePost { Path basePath = currentPath.isAbsolute() ? currentPath.getRoot() : base.toPath(); boolean useParent = !currentPathStringThing.isEmpty() && !currentPathStringThing.endsWith(File.separator); File currentFile = currentPath.isAbsolute() ? currentPath.toFile() : new File(base, currentPathStringThing); - return Arrays.stream(Objects.requireNonNull(SHUT_THE_FUCK_UP_IOEXCEPTION_NOBODY_LIKES_YOU( useParent ? currentFile.getParentFile() @@ -94,11 +94,9 @@ public class RelativeFile implements IDatatypePost { public static File gameDir() { File gameDir = HELPER.mc.gameDir.getAbsoluteFile(); - if (gameDir.getName().equals(".")) { return gameDir.getParentFile(); } - return gameDir; } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java index 4b4170a9..6abb88b7 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java @@ -31,6 +31,7 @@ import java.util.stream.Stream; import static java.util.Objects.nonNull; public class RelativeGoal implements IDatatypePost { + final RelativeCoordinate[] coords; public RelativeGoal() { @@ -39,13 +40,11 @@ public class RelativeGoal implements IDatatypePost { public RelativeGoal(ArgConsumer consumer) { List coordsList = new ArrayList<>(); - for (int i = 0; i < 3; i++) { if (nonNull(consumer.peekDatatypeOrNull(RelativeCoordinate.class))) { coordsList.add(consumer.getDatatype(RelativeCoordinate.class)); } } - coords = coordsList.toArray(new RelativeCoordinate[0]); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java index ff332493..2d8f9cda 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java @@ -24,6 +24,7 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; public class RelativeGoalBlock implements IDatatypePost { + final RelativeCoordinate[] coords; public RelativeGoalBlock() { @@ -52,7 +53,6 @@ public class RelativeGoalBlock implements IDatatypePost { + final RelativeCoordinate[] coords; public RelativeGoalXZ() { @@ -50,7 +51,6 @@ public class RelativeGoalXZ implements IDatatypePost { if (consumer.hasAtMost(2)) { return consumer.tabCompleteDatatype(RelativeCoordinate.class); } - return Stream.empty(); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java index 9d00350e..6b8a1aa0 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java @@ -24,6 +24,7 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; public class RelativeGoalYLevel implements IDatatypePost { + final RelativeCoordinate coord; public RelativeGoalYLevel() { @@ -44,7 +45,6 @@ public class RelativeGoalYLevel implements IDatatypePost" : Integer.toString(arg.index + 1), reason )); - this.arg = arg; } } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandInvalidStateException.java b/src/api/java/baritone/api/utils/command/exception/CommandInvalidStateException.java index 76ad3af0..4e00c1f7 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandInvalidStateException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandInvalidStateException.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.exception; public class CommandInvalidStateException extends CommandErrorMessageException { + public CommandInvalidStateException(String reason) { super(reason); } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java b/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java index 0988774d..5e5b81cd 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java @@ -20,6 +20,7 @@ package baritone.api.utils.command.exception; import baritone.api.utils.command.argument.CommandArgument; public class CommandInvalidTypeException extends CommandInvalidArgumentException { + public CommandInvalidTypeException(CommandArgument arg, String expected) { super(arg, String.format("Expected %s", expected)); } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java b/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java index 4dbbb962..5a016cd4 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.exception; public class CommandNoParserForTypeException extends CommandErrorMessageException { + public final Class klass; public CommandNoParserForTypeException(Class klass) { diff --git a/src/api/java/baritone/api/utils/command/exception/CommandNotEnoughArgumentsException.java b/src/api/java/baritone/api/utils/command/exception/CommandNotEnoughArgumentsException.java index 29d5d6ba..655652d6 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandNotEnoughArgumentsException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandNotEnoughArgumentsException.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.exception; public class CommandNotEnoughArgumentsException extends CommandErrorMessageException { + public CommandNotEnoughArgumentsException(int minArgs) { super(String.format("Not enough arguments (expected at least %d)", minArgs)); } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java b/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java index 44d3b7b2..e8904cbc 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java @@ -25,6 +25,7 @@ import java.util.List; import static baritone.api.utils.Helper.HELPER; public class CommandNotFoundException extends CommandException { + public final String command; public CommandNotFoundException(String command) { diff --git a/src/api/java/baritone/api/utils/command/exception/CommandTooManyArgumentsException.java b/src/api/java/baritone/api/utils/command/exception/CommandTooManyArgumentsException.java index 459940ab..24fc799f 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandTooManyArgumentsException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandTooManyArgumentsException.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.exception; public class CommandTooManyArgumentsException extends CommandErrorMessageException { + public CommandTooManyArgumentsException(int maxArgs) { super(String.format("Too many arguments (expected at most %d)", maxArgs)); } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java index 9c1f2f35..178fb721 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -26,6 +26,7 @@ import java.util.stream.Collectors; import static java.util.Arrays.asList; public class CommandUnhandledException extends CommandErrorMessageException { + public static String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); throwable.printStackTrace(new PrintWriter(sw)); @@ -35,14 +36,12 @@ public class CommandUnhandledException extends CommandErrorMessageException { public static String getBaritoneStackTrace(String stackTrace) { List lines = Arrays.stream(stackTrace.split("\n")) .collect(Collectors.toList()); - int lastBaritoneLine = 0; for (int i = 0; i < lines.size(); i++) { if (lines.get(i).startsWith("\tat baritone.") && lines.get(i).contains("BaritoneChatControl")) { lastBaritoneLine = i; } } - return String.join("\n", lines.subList(0, lastBaritoneLine + 1)); } @@ -52,21 +51,18 @@ public class CommandUnhandledException extends CommandErrorMessageException { public static String getFriendlierStackTrace(String stackTrace) { List lines = asList(stackTrace.split("\n")); - for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (line.startsWith("\tat ")) { if (line.startsWith("\tat baritone.")) { line = line.replaceFirst("^\tat [a-z.]+?([A-Z])", "\tat $1"); } - // line = line.replaceFirst("\\(([^)]+)\\)$", "\n\t . $1"); line = line.replaceFirst("\\([^:]+:(\\d+)\\)$", ":$1"); line = line.replaceFirst("\\(Unknown Source\\)$", ""); lines.set(i, line); } } - return String.join("\n", lines); } diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java index 1563405e..26716b87 100644 --- a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java +++ b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java @@ -33,21 +33,19 @@ import java.util.stream.Stream; import static java.util.Objects.isNull; public class CommandExecution { + /** * The command itself */ private final Command command; - /** * The name this command was called with */ public final String label; - /** * The arg consumer */ public final ArgConsumer args; - /** * The Baritone settings */ @@ -80,7 +78,6 @@ public class CommandExecution { e.handle(command, args.args); } catch (Throwable t) { t.printStackTrace(); - new CommandUnhandledException(t).handle(command, args.args); } } @@ -91,11 +88,9 @@ public class CommandExecution { public static CommandExecution from(String label, ArgConsumer args) { Command command = CommandManager.getCommand(label); - if (isNull(command)) { return null; } - return new CommandExecution( command, label, diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index 201076c7..6065b5b1 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -55,11 +55,11 @@ import java.util.stream.Stream; * */ public class ArgConsumer implements Cloneable { + /** * The list of arguments in this ArgConsumer */ public final LinkedList args; - /** * The list of consumed arguments for this ArgConsumer. The most recently consumed argument is the last one */ @@ -362,7 +362,6 @@ public class ArgConsumer implements Cloneable { return peekAsOrDefault(type, def, 0); } - /** * Tries to use a stateless {@link ArgParser} to parse the argument at the specified index into the specified * class @@ -743,7 +742,6 @@ public class ArgConsumer implements Cloneable { public T getDatatypeOrNull(Class datatype) { List argsSnapshot = new ArrayList<>(args); List consumedSnapshot = new ArrayList<>(consumed); - try { return getDatatype(datatype); } catch (CommandInvalidTypeException e) { @@ -751,7 +749,6 @@ public class ArgConsumer implements Cloneable { args.addAll(argsSnapshot); consumed.clear(); consumed.addAll(consumedSnapshot); - return null; } } @@ -790,7 +787,6 @@ public class ArgConsumer implements Cloneable { public > T getDatatypePostOrDefault(Class datatype, O original, T def) { List argsSnapshot = new ArrayList<>(args); List consumedSnapshot = new ArrayList<>(consumed); - try { return getDatatypePost(datatype, original); } catch (CommandException e) { @@ -798,7 +794,6 @@ public class ArgConsumer implements Cloneable { args.addAll(argsSnapshot); consumed.clear(); consumed.addAll(consumedSnapshot); - return def; } } @@ -855,7 +850,6 @@ public class ArgConsumer implements Cloneable { public > T getDatatypeForOrDefault(Class datatype, T def) { List argsSnapshot = new ArrayList<>(args); List consumedSnapshot = new ArrayList<>(consumed); - try { return getDatatypeFor(datatype); } catch (CommandInvalidTypeException e) { @@ -863,7 +857,6 @@ public class ArgConsumer implements Cloneable { args.addAll(argsSnapshot); consumed.clear(); consumed.addAll(consumedSnapshot); - return def; } } @@ -904,7 +897,6 @@ public class ArgConsumer implements Cloneable { } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } catch (CommandException ignored) {} - return Stream.empty(); } diff --git a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java index 22c796d0..3904408f 100644 --- a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java +++ b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java @@ -33,6 +33,7 @@ import static java.util.Arrays.asList; import static java.util.Objects.nonNull; public class Paginator implements Helper { + public final List entries; public int pageSize = 8; public int page = 1; @@ -47,7 +48,6 @@ public class Paginator implements Helper { public Paginator setPageSize(int pageSize) { this.pageSize = pageSize; - return this; } @@ -61,13 +61,11 @@ public class Paginator implements Helper { public Paginator skipPages(int pages) { page += pages; - return this; } public void display(Function transform, String commandPrefix) { int offset = (page - 1) * pageSize; - for (int i = offset; i < offset + pageSize; i++) { if (i < entries.size()) { logDirect(transform.apply(entries.get(i))); @@ -75,12 +73,9 @@ public class Paginator implements Helper { logDirect("--", TextFormatting.DARK_GRAY); } } - boolean hasPrevPage = nonNull(commandPrefix) && validPage(page - 1); boolean hasNextPage = nonNull(commandPrefix) && validPage(page + 1); - ITextComponent prevPageComponent = new TextComponentString("<<"); - if (hasPrevPage) { prevPageComponent.getStyle() .setClickEvent(new ClickEvent( @@ -94,9 +89,7 @@ public class Paginator implements Helper { } else { prevPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY); } - ITextComponent nextPageComponent = new TextComponentString(">>"); - if (hasNextPage) { nextPageComponent.getStyle() .setClickEvent(new ClickEvent( @@ -110,7 +103,6 @@ public class Paginator implements Helper { } else { nextPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY); } - ITextComponent pagerComponent = new TextComponentString(""); pagerComponent.getStyle().setColor(TextFormatting.GRAY); pagerComponent.appendSibling(prevPageComponent); @@ -126,12 +118,9 @@ public class Paginator implements Helper { public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform, String commandPrefix) { int page = 1; - consumer.requireMax(1); - if (consumer.has()) { page = consumer.getAs(Integer.class); - if (!pagi.validPage(page)) { throw new CommandInvalidTypeException( consumer.consumed(), @@ -143,13 +132,10 @@ public class Paginator implements Helper { ); } } - pagi.skipPages(page - pagi.page); - if (nonNull(pre)) { pre.run(); } - pagi.display(transform, commandPrefix); } diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index 1c60c085..98b88667 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -53,6 +53,7 @@ import java.util.stream.Stream; * array. */ public class TabCompleteHelper { + private Stream stream; public TabCompleteHelper(String[] base) { @@ -80,7 +81,6 @@ public class TabCompleteHelper { */ public TabCompleteHelper append(Stream source) { stream = Stream.concat(stream, source); - return this; } @@ -131,7 +131,6 @@ public class TabCompleteHelper { */ public TabCompleteHelper prepend(Stream source) { stream = Stream.concat(source, stream); - return this; } @@ -178,7 +177,6 @@ public class TabCompleteHelper { */ public TabCompleteHelper map(Function transform) { stream = stream.map(transform); - return this; } @@ -191,7 +189,6 @@ public class TabCompleteHelper { */ public TabCompleteHelper filter(Predicate filter) { stream = stream.filter(filter); - return this; } @@ -204,7 +201,6 @@ public class TabCompleteHelper { */ public TabCompleteHelper sort(Comparator comparator) { stream = stream.sorted(comparator); - return this; } diff --git a/src/api/java/baritone/api/utils/command/manager/CommandManager.java b/src/api/java/baritone/api/utils/command/manager/CommandManager.java index 425da5ef..ad90131b 100644 --- a/src/api/java/baritone/api/utils/command/manager/CommandManager.java +++ b/src/api/java/baritone/api/utils/command/manager/CommandManager.java @@ -32,6 +32,7 @@ import static java.util.Objects.isNull; import static java.util.Objects.nonNull; public class CommandManager { + public static final Registry REGISTRY = new Registry<>(); /** @@ -44,7 +45,6 @@ public class CommandManager { return command; } } - return null; } @@ -54,11 +54,9 @@ public class CommandManager { public static boolean execute(String string) { CommandExecution execution = CommandExecution.from(string); - if (nonNull(execution)) { execution.execute(); } - return nonNull(execution); } @@ -75,7 +73,6 @@ public class CommandManager { Pair> pair = CommandExecution.expand(prefix, true); String label = pair.first(); List args = pair.second(); - if (args.isEmpty()) { return new TabCompleteHelper() .addCommands() diff --git a/src/api/java/baritone/api/utils/command/registry/Registry.java b/src/api/java/baritone/api/utils/command/registry/Registry.java index 82a3dc6f..e3349874 100644 --- a/src/api/java/baritone/api/utils/command/registry/Registry.java +++ b/src/api/java/baritone/api/utils/command/registry/Registry.java @@ -33,6 +33,7 @@ import java.util.stream.StreamSupport; */ @SuppressWarnings({"unused", "UnusedReturnValue"}) public class Registry { + /** * An internal linked list of all the entries that are currently registered. This is a linked list so that entries * can be inserted at the beginning, which means that newer entries are encountered first during iteration. This is @@ -40,14 +41,12 @@ public class Registry { * not just use a map. */ private final Deque _entries = new LinkedList<>(); - /** * A HashSet containing every entry currently registered. Entries are added to this set when something is registered * and removed from the set when they are unregistered. An entry being present in this set indicates that it is * currently registered, can be removed, and should not be reregistered until it is removed. */ private final Set registered = new HashSet<>(); - /** * The collection of entries that are currently in this registry. This is a collection (and not a list) because, * internally, entries are stored in a linked list, which is not the same as a normal list. @@ -74,10 +73,8 @@ public class Registry { if (!registered(entry)) { _entries.addFirst(entry); registered.add(entry); - return true; } - return false; } @@ -91,7 +88,6 @@ public class Registry { if (registered(entry)) { return; } - _entries.remove(entry); registered.remove(entry); } diff --git a/src/main/java/baritone/pathing/calc/openset/LinkedListOpenSet.java b/src/main/java/baritone/pathing/calc/openset/LinkedListOpenSet.java index 6de8290d..2f7a0af5 100644 --- a/src/main/java/baritone/pathing/calc/openset/LinkedListOpenSet.java +++ b/src/main/java/baritone/pathing/calc/openset/LinkedListOpenSet.java @@ -27,6 +27,7 @@ import baritone.pathing.calc.PathNode; * @author leijurv */ class LinkedListOpenSet implements IOpenSet { + private Node first = null; @Override @@ -83,6 +84,7 @@ class LinkedListOpenSet implements IOpenSet { } public static class Node { //wrapper with next + private Node nextOpen; private PathNode val; } diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index d63a0315..aad23f21 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -39,11 +39,9 @@ public class BlacklistCommand extends Command { protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); IGetToBlockProcess proc = baritone.getGetToBlockProcess(); - if (!proc.isActive()) { throw new CommandInvalidStateException("GetToBlockProcess is not currently active"); } - if (proc.blacklistClosest()) { logDirect("Blacklisted closest instances"); } else { diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index e11f7ad2..146faf0f 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -45,14 +45,11 @@ public class BuildCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { File file = args.getDatatypePost(RelativeFile.class, schematicsDir).getAbsoluteFile(); - if (!file.getName().toLowerCase(Locale.US).endsWith(".schematic")) { file = new File(file.getAbsolutePath() + ".schematic"); } - BetterBlockPos origin = ctx.playerFeet(); BetterBlockPos buildOrigin; - if (args.has()) { args.requireMax(3); buildOrigin = args.getDatatype(RelativeBlockPos.class).apply(origin); @@ -60,13 +57,10 @@ public class BuildCommand extends Command { args.requireMax(0); buildOrigin = origin; } - boolean success = baritone.getBuilderProcess().build(file.getName(), file, buildOrigin); - if (!success) { throw new CommandInvalidStateException("Couldn't load the schematic"); } - logDirect(String.format("Successfully loaded schematic for building\nOrigin: %s", buildOrigin)); } @@ -76,10 +70,8 @@ public class BuildCommand extends Command { return RelativeFile.tabComplete(args, schematicsDir); } else if (args.has(2)) { args.get(); - return args.tabCompleteDatatype(RelativeBlockPos.class); } - return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index 33a88075..7965745d 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -46,18 +46,14 @@ public class ChestsCommand extends Command { args.requireMax(0); Set> entries = ctx.worldData().getContainerMemory().getRememberedInventories().entrySet(); - if (entries.isEmpty()) { throw new CommandInvalidStateException("No remembered inventories"); } - for (Map.Entry entry : entries) { // betterblockpos has censoring BetterBlockPos pos = new BetterBlockPos(entry.getKey()); IRememberedInventory inv = entry.getValue(); - logDirect(pos.toString()); - for (ItemStack item : inv.getContents()) { ITextComponent component = item.getTextComponent(); component.appendText(String.format(" x %d", item.getCount())); diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index bfe3856d..7a73be42 100644 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -42,22 +42,18 @@ public class ClearareaCommand extends Command { protected void executed(String label, ArgConsumer args, Settings settings) { BetterBlockPos pos1 = ctx.playerFeet(); BetterBlockPos pos2; - if (args.has()) { args.requireMax(3); pos2 = args.getDatatype(RelativeBlockPos.class).apply(pos1); } else { args.requireMax(0); - Goal goal = baritone.getCustomGoalProcess().getGoal(); - if (!(goal instanceof GoalBlock)) { throw new CommandInvalidStateException("Goal is not a GoalBlock"); } else { pos2 = new BetterBlockPos(((GoalBlock) goal).getGoalPos()); } } - baritone.getBuilderProcess().clearArea(pos1, pos2); logDirect("Success"); } diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index 0d8440c5..f18d4226 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -42,11 +42,9 @@ public class ComeCommand extends Command { protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); Entity entity = MC.getRenderViewEntity(); - if (isNull(entity)) { throw new CommandInvalidStateException("render view entity is null"); } - baritone.getCustomGoalProcess().setGoalAndPath(new GoalBlock(new BlockPos(entity))); logDirect("Coming"); } diff --git a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java index e8af7891..611ae063 100644 --- a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java +++ b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java @@ -48,7 +48,6 @@ public class DefaultCommands { new GcCommand(baritone), new InvertCommand(baritone), new ClearareaCommand(baritone), - new TunnelCommand(baritone), new RenderCommand(baritone), new FarmCommand(baritone), diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index 374f3260..9f5beb19 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -42,11 +42,9 @@ public class ExploreCommand extends Command { } else { args.requireMax(0); } - GoalXZ goal = args.has() ? args.getDatatypePost(RelativeGoalXZ.class, ctx.playerFeet()) : new GoalXZ(ctx.playerFeet()); - baritone.getExploreProcess().explore(goal.getX(), goal.getZ()); logDirect(String.format("Exploring from %s", goal.toString())); } @@ -56,7 +54,6 @@ public class ExploreCommand extends Command { if (args.hasAtMost(2)) { return args.tabCompleteDatatype(RelativeGoalXZ.class); } - return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index fa459adc..40cf3a6a 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -34,6 +34,7 @@ import java.util.stream.Stream; import static java.util.Arrays.asList; public class ExploreFilterCommand extends Command { + public ExploreFilterCommand(IBaritone baritone) { super(baritone, "explorefilter"); } @@ -43,7 +44,6 @@ public class ExploreFilterCommand extends Command { args.requireMax(2); File file = args.getDatatypePost(RelativeFile.class, MC.gameDir.getAbsoluteFile().getParentFile()); boolean invert = false; - if (args.has()) { if (args.getString().equalsIgnoreCase("invert")) { invert = true; @@ -51,7 +51,6 @@ public class ExploreFilterCommand extends Command { throw new CommandInvalidTypeException(args.consumed(), "either \"invert\" or nothing"); } } - try { baritone.getExploreProcess().applyJsonFilter(file.toPath().toAbsolutePath(), invert); } catch (NoSuchFileException e) { @@ -61,7 +60,6 @@ public class ExploreFilterCommand extends Command { } catch (Exception e) { throw new RuntimeException(e); } - logDirect(String.format("Explore filter applied. Inverted: %s", Boolean.toString(invert))); } @@ -70,7 +68,6 @@ public class ExploreFilterCommand extends Command { if (args.hasExactlyOne()) { return RelativeFile.tabComplete(args, RelativeFile.gameDir()); } - return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index 64dd9728..61d03dd8 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -40,13 +40,10 @@ public class FindCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { List toFind = new ArrayList<>(); - while (args.has()) { toFind.add(args.getDatatypeFor(BlockById.class)); } - BetterBlockPos origin = ctx.playerFeet(); - toFind.stream() .flatMap(block -> ctx.worldData().getCachedWorld().getLocationsOf( diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index c82461f6..9502b6af 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -52,24 +52,19 @@ public class FollowCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMin(1); - FollowGroup group; FollowList list; List entities = new ArrayList<>(); List> classes = new ArrayList<>(); - if (args.hasExactlyOne()) { baritone.getFollowProcess().follow((group = args.getEnum(FollowGroup.class)).filter); } else { args.requireMin(2); - group = null; list = args.getEnum(FollowList.class); - while (args.has()) { //noinspection unchecked Object gotten = args.getDatatypeFor(list.datatype); - if (gotten instanceof Class) { //noinspection unchecked classes.add((Class) gotten); @@ -77,19 +72,16 @@ public class FollowCommand extends Command { entities.add((Entity) gotten); } } - baritone.getFollowProcess().follow( classes.isEmpty() ? entities::contains : e -> classes.stream().anyMatch(c -> c.isInstance(e)) ); } - if (nonNull(group)) { logDirect(String.format("Following all %s", group.name().toLowerCase(Locale.US))); } else { logDirect("Following these types of entities:"); - if (classes.isEmpty()) { entities.stream() .map(Entity::toString) @@ -114,21 +106,17 @@ public class FollowCommand extends Command { .stream(); } else { Class followType; - try { followType = args.getEnum(FollowList.class).datatype; } catch (NullPointerException e) { return Stream.empty(); } - while (args.has(2)) { if (isNull(args.peekDatatypeOrNull(followType))) { return Stream.empty(); } - args.get(); } - return args.tabCompleteDatatype(followType); } } @@ -156,7 +144,6 @@ public class FollowCommand extends Command { PLAYERS(EntityPlayer.class::isInstance); /* , FRIENDLY(entity -> entity.getAttackTarget() != HELPER.mc.player), HOSTILE(FRIENDLY.filter.negate()); */ - final Predicate filter; FollowGroup(Predicate filter) { @@ -167,7 +154,6 @@ public class FollowCommand extends Command { private enum FollowList { ENTITY(EntityClassById.class), PLAYER(PlayerByUsername.class); - final Class datatype; FollowList(Class datatype) { diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index 7a0b124a..6bf1355a 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -36,9 +36,7 @@ public class GcCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - System.gc(); - logDirect("ok called System.gc()"); } diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index 20892037..a62355c3 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -44,10 +44,8 @@ public class GoalCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { ICustomGoalProcess goalProcess = baritone.getCustomGoalProcess(); - if (args.has() && asList("reset", "clear", "none").contains(args.peekString())) { args.requireMax(1); - if (nonNull(goalProcess.getGoal())) { goalProcess.setGoal(null); logDirect("Cleared goal"); @@ -66,7 +64,6 @@ public class GoalCommand extends Command { @Override protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { TabCompleteHelper helper = new TabCompleteHelper(); - if (args.hasExactlyOne()) { helper.append(Stream.of("reset", "clear", "none", "~")); } else { @@ -75,16 +72,13 @@ public class GoalCommand extends Command { if (isNull(args.peekDatatypeOrNull(RelativeCoordinate.class))) { break; } - args.get(); - if (!args.has(2)) { helper.append("~"); } } } } - return helper.filterPrefix(args.getString()).stream(); } diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index fa6e760c..289e709e 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -49,7 +49,6 @@ public class HelpCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(1); - if (!args.has() || args.is(Integer.class)) { Paginator.paginate( args, new Paginator<>( @@ -61,20 +60,16 @@ public class HelpCommand extends Command { command -> { String names = String.join("/", command.names); String name = command.names.get(0); - ITextComponent shortDescComponent = new TextComponentString(" - " + command.getShortDesc()); shortDescComponent.getStyle().setColor(TextFormatting.DARK_GRAY); - ITextComponent namesComponent = new TextComponentString(names); namesComponent.getStyle().setColor(TextFormatting.WHITE); - ITextComponent hoverComponent = new TextComponentString(""); hoverComponent.getStyle().setColor(TextFormatting.GRAY); hoverComponent.appendSibling(namesComponent); hoverComponent.appendText("\n" + command.getShortDesc()); hoverComponent.appendText("\n\nClick to view full help"); String clickCommand = FORCE_COMMAND_PREFIX + String.format("%s %s", label, command.names.get(0)); - ITextComponent component = new TextComponentString(name); component.getStyle().setColor(TextFormatting.GRAY); component.appendSibling(shortDescComponent); @@ -88,22 +83,18 @@ public class HelpCommand extends Command { } else { String commandName = args.getString().toLowerCase(); Command command = getCommand(commandName); - if (isNull(command)) { throw new CommandNotFoundException(commandName); } - logDirect(String.format("%s - %s", String.join(" / ", command.names), command.getShortDesc())); logDirect(""); command.getLongDesc().forEach(this::logDirect); logDirect(""); - ITextComponent returnComponent = new TextComponentString("Click to return to the help menu"); returnComponent.getStyle().setClickEvent(new ClickEvent( ClickEvent.Action.RUN_COMMAND, FORCE_COMMAND_PREFIX + label )); - logDirect(returnComponent); } } @@ -113,7 +104,6 @@ public class HelpCommand extends Command { if (args.hasExactlyOne()) { return new TabCompleteHelper().addCommands().filterPrefix(args.getString()).stream(); } - return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index 133f428f..368bdc4e 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -41,20 +41,16 @@ public class InvertCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; - if (isNull(goal = customGoalProcess.getGoal())) { throw new CommandInvalidStateException("No goal"); } - if (goal instanceof GoalInverted) { goal = ((GoalInverted) goal).origin; } else { goal = new GoalInverted(goal); } - customGoalProcess.setGoal(goal); logDirect(String.format("Goal: %s", goal.toString())); } diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index 61cb1c4d..1dcc962a 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -43,11 +43,9 @@ public class MineCommand extends Command { int quantity = args.getAsOrDefault(Integer.class, 0); args.requireMin(1); List boms = new ArrayList<>(); - while (args.has()) { boms.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); } - WorldScanner.INSTANCE.repack(ctx); baritone.getMineProcess().mine(quantity, boms.toArray(new BlockOptionalMeta[0])); logDirect(String.format("Mining %s", boms.toString())); diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index a51aa968..3a0fc5d4 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -45,14 +45,12 @@ public class PathCommand extends Command { protected void executed(String label, ArgConsumer args, Settings settings) { ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; - if (args.has()) { args.requireMax(3); goal = args.getDatatype(RelativeGoal.class).apply(ctx.playerFeet()); } else if (isNull(goal = customGoalProcess.getGoal())) { throw new CommandInvalidStateException("No goal"); } - args.requireMax(0); WorldScanner.INSTANCE.repack(ctx); customGoalProcess.setGoalAndPath(goal); @@ -66,9 +64,7 @@ public class PathCommand extends Command { if (isNull(args.peekDatatypeOrNull(RelativeCoordinate.class))) { break; } - args.get(); - if (!args.has(2)) { return new TabCompleteHelper() .append("~") @@ -77,7 +73,6 @@ public class PathCommand extends Command { } } } - return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index 87f1b4b1..7e7a242c 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -49,7 +49,6 @@ public class PauseResumeCommands { this.baritone = baritone; // array for mutability, non-field so reflection can't touch it final boolean[] paused = {false}; - baritone.getPathingControlManager().registerProcess( new IBaritoneProcess() { @Override @@ -81,16 +80,13 @@ public class PauseResumeCommands { } } ); - pauseCommand = new Command(baritone, "pause") { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - if (paused[0]) { throw new CommandInvalidStateException("Already paused"); } - paused[0] = true; logDirect("Paused"); } @@ -117,16 +113,13 @@ public class PauseResumeCommands { ); } }; - resumeCommand = new Command(baritone, "resume") { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - if (!paused[0]) { throw new CommandInvalidStateException("Not paused"); } - paused[0] = false; logDirect("Resumed"); } @@ -151,12 +144,10 @@ public class PauseResumeCommands { ); } }; - pausedCommand = new Command(baritone, "paused") { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - logDirect(String.format("Baritone is %spaused", paused[0] ? "" : "not ")); } diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index 4c405ff6..03e069d0 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -41,14 +41,11 @@ public class ProcCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - IPathingControlManager pathingControlManager = baritone.getPathingControlManager(); IBaritoneProcess process = pathingControlManager.mostRecentInControl().orElse(null); - if (isNull(process)) { throw new CommandInvalidStateException("No process in control"); } - logDirect(String.format( "Class: %s\n" + "Priority: %f\n" + diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index 2eab0bd1..0dedc398 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -37,7 +37,6 @@ public class RenderCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - BetterBlockPos origin = ctx.playerFeet(); int renderDistance = (MC.gameSettings.renderDistanceChunks + 1) * 16; MC.renderGlobal.markBlockRangeForRenderUpdate( @@ -48,7 +47,6 @@ public class RenderCommand extends Command { 255, origin.z + renderDistance ); - logDirect("Done"); } diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index d48a79e4..296b6e61 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -66,12 +66,10 @@ public class SelCommand extends Command { if (!Baritone.settings().renderSelectionCorners.value || pos1 == null) { return; } - Color color = Baritone.settings().colorSelectionPos1.value; float opacity = Baritone.settings().selectionOpacity.value; 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.endLines(ignoreDepth); @@ -82,20 +80,16 @@ public class SelCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { Action action = Action.getByName(args.getString()); - if (action == null) { throw new CommandInvalidTypeException(args.consumed(), "an action"); } - if (action == Action.POS1 || action == Action.POS2) { if (action == Action.POS2 && pos1 == null) { throw new CommandInvalidStateException("Set pos1 first before using pos2"); } - BetterBlockPos playerPos = ctx.playerFeet(); BetterBlockPos pos = args.has() ? args.getDatatypePost(RelativeBlockPos.class, playerPos) : playerPos; args.requireMax(0); - if (action == Action.POS1) { pos1 = pos; logDirect("Position 1 has been set"); @@ -110,13 +104,11 @@ public class SelCommand extends Command { logDirect(String.format("Removed %d selections", manager.removeAllSelections().length)); } else if (action == Action.UNDO) { args.requireMax(0); - if (pos1 != null) { pos1 = null; logDirect("Undid pos1"); } else { ISelection[] selections = manager.getSelections(); - if (selections.length < 1) { throw new CommandInvalidStateException("Nothing to undo!"); } else { @@ -129,33 +121,24 @@ public class SelCommand extends Command { ? new BlockOptionalMeta(Blocks.AIR) : args.getDatatypeFor(ForBlockOptionalMeta.class); BlockOptionalMetaLookup replaces = null; - if (action == Action.REPLACE) { args.requireMin(1); - List replacesList = new ArrayList<>(); - replacesList.add(type); - while (args.has(2)) { replacesList.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); } - type = args.getDatatypeFor(ForBlockOptionalMeta.class); replaces = new BlockOptionalMetaLookup(replacesList.toArray(new BlockOptionalMeta[0])); } else { args.requireMax(0); } - ISelection[] selections = manager.getSelections(); - if (selections.length == 0) { throw new CommandInvalidStateException("No selections"); } - BetterBlockPos origin = selections[0].min(); CompositeSchematic composite = new CompositeSchematic(0, 0, 0); - for (ISelection selection : selections) { BetterBlockPos min = selection.min(); origin = new BetterBlockPos( @@ -164,13 +147,10 @@ public class SelCommand extends Command { Math.min(origin.z, min.z) ); } - 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) { @@ -178,31 +158,23 @@ public class SelCommand extends Command { } else if (action == Action.REPLACE) { schematic = new ReplaceSchematic(schematic, replaces); } - composite.put(schematic, min.x - origin.x, min.y - origin.y, min.z - origin.z); } - baritone.getBuilderProcess().build("Fill", composite, origin); logDirect("Filling now"); } else if (action == Action.EXPAND || action == Action.CONTRACT || action == Action.SHIFT) { args.requireExactly(3); TransformTarget transformTarget = TransformTarget.getByName(args.getString()); - if (transformTarget == null) { throw new CommandInvalidStateException("Invalid transform type"); } - EnumFacing direction = args.getDatatypeFor(ForEnumFacing.class); int blocks = args.getAs(Integer.class); - ISelection[] selections = manager.getSelections(); - if (selections.length < 1) { throw new CommandInvalidStateException("No selections found"); } - selections = transformTarget.transform(selections); - for (ISelection selection : selections) { if (action == Action.EXPAND) { manager.expand(selection, direction, blocks); @@ -212,7 +184,6 @@ public class SelCommand extends Command { manager.shift(selection, direction, blocks); } } - logDirect(String.format("Transformed %d selections", selections.length)); } } @@ -227,7 +198,6 @@ public class SelCommand extends Command { .stream(); } else { Action action = Action.getByName(args.getString()); - if (action != null) { if (action == Action.POS1 || action == Action.POS2) { if (args.hasAtMost(3)) { @@ -238,7 +208,6 @@ public class SelCommand extends Command { while (args.has(2)) { args.get(); } - return args.tabCompleteDatatype(ForBlockOptionalMeta.class); } } else if (action == Action.EXPAND || action == Action.CONTRACT || action == Action.SHIFT) { @@ -250,7 +219,6 @@ public class SelCommand extends Command { .stream(); } else { TransformTarget target = TransformTarget.getByName(args.getString()); - if (target != null && args.hasExactlyOne()) { return args.tabCompleteDatatype(ForEnumFacing.class); } @@ -258,7 +226,6 @@ public class SelCommand extends Command { } } } - return Stream.empty(); } @@ -299,20 +266,16 @@ public class SelCommand extends Command { enum Action { POS1("pos1", "p1", "1"), POS2("pos2", "p2", "2"), - CLEAR("clear", "c"), UNDO("undo", "u"), - SET("set", "fill", "s", "f"), WALLS("walls", "w"), SHELL("shell", "shl"), CLEARAREA("cleararea", "ca"), REPLACE("replace", "r"), - EXPAND("expand", "ex"), CONTRACT("contract", "ct"), SHIFT("shift", "sh"); - private final String[] names; Action(String... names) { @@ -327,17 +290,14 @@ public class SelCommand extends Command { } } } - return null; } public static String[] getAllNames() { Set names = new HashSet<>(); - for (Action action : Action.values()) { names.addAll(asList(action.names)); } - return names.toArray(new String[0]); } } @@ -346,7 +306,6 @@ public class SelCommand extends Command { ALL(sels -> sels, "all", "a"), NEWEST(sels -> new ISelection[]{sels[sels.length - 1]}, "newest", "n"), OLDEST(sels -> new ISelection[]{sels[0]}, "oldest", "o"); - private final Function transform; private final String[] names; @@ -367,17 +326,14 @@ public class SelCommand extends Command { } } } - return null; } public static String[] getAllNames() { Set names = new HashSet<>(); - for (TransformTarget target : TransformTarget.values()) { names.addAll(asList(target.names)); } - return names.toArray(new String[0]); } } diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index fff0e3d3..96130414 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -53,27 +53,23 @@ public class SetCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { String arg = args.has() ? args.getString().toLowerCase(Locale.US) : "list"; - if (asList("s", "save").contains(arg)) { SettingsUtil.save(settings); logDirect("Settings saved"); return; } - boolean viewModified = asList("m", "mod", "modified").contains(arg); boolean viewAll = asList("all", "l", "list").contains(arg); boolean paginate = viewModified || viewAll; if (paginate) { String search = args.has() && args.peekAsOrNull(Integer.class) == null ? args.getString() : ""; args.requireMax(1); - List toPaginate = (viewModified ? SettingsUtil.modifiedSettings(settings) : settings.allSettings).stream() .filter(s -> !s.getName().equals("logger")) .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()); - Paginator.paginate( args, new Paginator<>(toPaginate), @@ -88,35 +84,28 @@ public class SetCommand extends Command { settingTypeToString(setting) )); typeComponent.getStyle().setColor(TextFormatting.DARK_GRAY); - ITextComponent hoverComponent = new TextComponentString(""); hoverComponent.getStyle().setColor(TextFormatting.GRAY); hoverComponent.appendText(setting.getName()); hoverComponent.appendText(String.format("\nType: %s", settingTypeToString(setting))); hoverComponent.appendText(String.format("\n\nValue:\n%s", settingValueToString(setting))); String commandSuggestion = settings.prefix.value + String.format("set %s ", setting.getName()); - ITextComponent component = new TextComponentString(setting.getName()); component.getStyle().setColor(TextFormatting.GRAY); component.appendSibling(typeComponent); component.getStyle() .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent)) .setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, commandSuggestion)); - return component; }, FORCE_COMMAND_PREFIX + "set " + arg + " " + search ); - return; } - args.requireMax(1); - boolean resetting = arg.equalsIgnoreCase("reset"); boolean toggling = arg.equalsIgnoreCase("toggle"); boolean doingSomething = resetting || toggling; - if (resetting) { if (!args.has()) { logDirect("Please specify 'all' as an argument to reset to confirm you'd really like to do this"); @@ -126,41 +115,33 @@ public class SetCommand extends Command { SettingsUtil.modifiedSettings(settings).forEach(Settings.Setting::reset); logDirect("All settings have been reset to their default values"); SettingsUtil.save(settings); - return; } } - if (toggling) { args.requireMin(1); } - String settingName = doingSomething ? args.getString() : arg; Settings.Setting setting = settings.allSettings.stream() .filter(s -> s.getName().equalsIgnoreCase(settingName)) .findFirst() .orElse(null); - if (isNull(setting)) { throw new CommandInvalidTypeException(args.consumed(), "a valid setting"); } - if (!doingSomething && !args.has()) { logDirect(String.format("Value of setting %s:", setting.getName())); logDirect(settingValueToString(setting)); } else { String oldValue = settingValueToString(setting); - if (resetting) { setting.reset(); } else if (toggling) { if (setting.getValueClass() != Boolean.class) { throw new CommandInvalidTypeException(args.consumed(), "a toggleable setting", "some other setting"); } - //noinspection unchecked ((Settings.Setting) setting).value ^= true; - logDirect(String.format( "Toggled setting %s to %s", setting.getName(), @@ -168,7 +149,6 @@ public class SetCommand extends Command { )); } else { String newValue = args.getString(); - try { SettingsUtil.parseAndApply(settings, arg, newValue); } catch (Throwable t) { @@ -176,7 +156,6 @@ public class SetCommand extends Command { throw new CommandInvalidTypeException(args.consumed(), "a valid value", t); } } - if (!toggling) { logDirect(String.format( "Successfully %s %s to %s", @@ -185,7 +164,6 @@ public class SetCommand extends Command { settingValueToString(setting) )); } - ITextComponent oldValueComponent = new TextComponentString(String.format("Old value: %s", oldValue)); oldValueComponent.getStyle() .setColor(TextFormatting.GRAY) @@ -197,9 +175,7 @@ public class SetCommand extends Command { ClickEvent.Action.RUN_COMMAND, FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue) )); - logDirect(oldValueComponent); - if ((setting.getName().equals("chatControl") && !(Boolean) setting.value && !settings.chatControlAnyway.value) || setting.getName().equals("chatControlAnyway") && !(Boolean) setting.value && !settings.chatControl.value) { logDirect("Warning: Chat commands will no longer work. If you want to revert this change, use prefix control (if enabled) or click the old value listed above.", TextFormatting.RED); @@ -207,7 +183,6 @@ public class SetCommand extends Command { logDirect("Warning: Prefixed commands will no longer work. If you want to revert this change, use chat control (if enabled) or click the old value listed above.", TextFormatting.RED); } } - SettingsUtil.save(settings); } @@ -215,7 +190,6 @@ public class SetCommand extends Command { protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { if (args.has()) { String arg = args.getString(); - if (args.hasExactlyOne() && !asList("s", "save").contains(args.peekString().toLowerCase(Locale.US))) { if (arg.equalsIgnoreCase("reset")) { return new TabCompleteHelper() @@ -229,19 +203,15 @@ public class SetCommand extends Command { .filterPrefix(args.getString()) .stream(); } - Settings.Setting setting = settings.byLowerName.get(arg.toLowerCase(Locale.US)); - if (nonNull(setting)) { if (setting.getType() == Boolean.class) { TabCompleteHelper helper = new TabCompleteHelper(); - if ((Boolean) setting.value) { helper.append(of("true", "false")); } else { helper.append(of("false", "true")); } - return helper.filterPrefix(args.getString()).stream(); } else { return Stream.of(settingValueToString(setting)); @@ -256,7 +226,6 @@ public class SetCommand extends Command { .stream(); } } - return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index 99d816d7..27cefcc9 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -37,13 +37,11 @@ public class ThisWayCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireExactly(1); - GoalXZ goal = GoalXZ.fromDirection( ctx.playerFeetAsVec(), ctx.player().rotationYawHead, args.getAs(Double.class) ); - baritone.getCustomGoalProcess().setGoal(goal); logDirect(String.format("Goal: %s", goal)); } diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index 6f60e0cd..c7da7f85 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -38,12 +38,10 @@ public class TunnelCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - Goal goal = new GoalStrictDirection( ctx.playerFeet(), ctx.player().getHorizontalFacing() ); - baritone.getCustomGoalProcess().setGoal(goal); logDirect(String.format("Goal: %s", goal.toString())); } diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index 6ce54ca5..f795315d 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -38,9 +38,7 @@ public class VersionCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - String version = getClass().getPackage().getImplementationVersion(); - if (isNull(version)) { throw new CommandInvalidStateException("Null version (this is normal in a dev environment)"); } else { diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 5d60b9d0..97618390 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -58,14 +58,11 @@ public class WaypointsCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { Action action = args.has() ? Action.getByName(args.getString()) : Action.LIST; - if (action == null) { throw new CommandInvalidTypeException(args.consumed(), "an action"); } - BiFunction toComponent = (waypoint, _action) -> { ITextComponent component = new TextComponentString(""); - ITextComponent tagComponent = new TextComponentString(waypoint.getTag().name() + " "); tagComponent.getStyle().setColor(TextFormatting.GRAY); String name = waypoint.getName(); @@ -73,7 +70,6 @@ public class WaypointsCommand extends Command { nameComponent.getStyle().setColor(!name.isEmpty() ? TextFormatting.GRAY : TextFormatting.DARK_GRAY); ITextComponent timestamp = new TextComponentString(" @ " + new Date(waypoint.getCreationTimestamp())); timestamp.getStyle().setColor(TextFormatting.DARK_GRAY); - component.appendSibling(tagComponent); component.appendSibling(nameComponent); component.appendSibling(timestamp); @@ -93,24 +89,18 @@ public class WaypointsCommand extends Command { waypoint.getCreationTimestamp() )) ); - return component; }; - Function transform = waypoint -> toComponent.apply(waypoint, action == Action.LIST ? Action.INFO : action); - if (action == Action.LIST) { IWaypoint.Tag tag = args.has() ? IWaypoint.Tag.getByName(args.peekString()) : null; - if (tag != null) { args.get(); } - IWaypoint[] waypoints = tag != null ? ForWaypoints.getWaypointsByTag(tag) : ForWaypoints.getWaypoints(); - if (waypoints.length > 0) { args.requireMax(1); Paginator.paginate( @@ -140,21 +130,16 @@ public class WaypointsCommand extends Command { } } else if (action == Action.SAVE) { IWaypoint.Tag tag = IWaypoint.Tag.getByName(args.getString()); - if (tag == null) { throw new CommandInvalidStateException(String.format("'%s' is not a tag ", args.consumedString())); } - String name = args.has() ? args.getString() : ""; BetterBlockPos pos = args.has() ? args.getDatatypePost(RelativeBlockPos.class, ctx.playerFeet()) : ctx.playerFeet(); - args.requireMax(0); - IWaypoint waypoint = new Waypoint(name, tag, pos); ForWaypoints.waypoints().addWaypoint(waypoint); - ITextComponent component = new TextComponentString("Waypoint added: "); component.getStyle().setColor(TextFormatting.GRAY); component.appendSibling(toComponent.apply(waypoint, Action.INFO)); @@ -163,28 +148,23 @@ public class WaypointsCommand extends Command { args.requireMax(1); IWaypoint.Tag tag = IWaypoint.Tag.getByName(args.getString()); IWaypoint[] waypoints = ForWaypoints.getWaypointsByTag(tag); - for (IWaypoint waypoint : waypoints) { ForWaypoints.waypoints().removeWaypoint(waypoint); } - logDirect(String.format("Cleared %d waypoints", waypoints.length)); } else { IWaypoint[] waypoints = args.getDatatypeFor(ForWaypoints.class); IWaypoint waypoint = null; - if (args.has() && args.peekString().equals("@")) { args.requireExactly(2); args.get(); long timestamp = args.getAs(Long.class); - for (IWaypoint iWaypoint : waypoints) { if (iWaypoint.getCreationTimestamp() == timestamp) { waypoint = iWaypoint; break; } } - if (waypoint == null) { throw new CommandInvalidStateException("Timestamp was specified but no waypoint was found"); } @@ -196,7 +176,6 @@ public class WaypointsCommand extends Command { waypoint = waypoints[0]; } } - if (waypoint == null) { args.requireMax(1); Paginator.paginate( @@ -273,7 +252,6 @@ public class WaypointsCommand extends Command { .stream(); } else { Action action = Action.getByName(args.getString()); - if (args.hasExactlyOne()) { if (action == Action.LIST || action == Action.SAVE || action == Action.CLEAR) { return new TabCompleteHelper() @@ -291,7 +269,6 @@ public class WaypointsCommand extends Command { } } } - return Stream.empty(); } @@ -327,7 +304,6 @@ public class WaypointsCommand extends Command { INFO("info", "show", "i"), DELETE("delete", "d"), GOAL("goal", "goto", "g"); - private final String[] names; Action(String... names) { @@ -342,17 +318,14 @@ public class WaypointsCommand extends Command { } } } - return null; } public static String[] getAllNames() { Set names = new HashSet<>(); - for (Action action : Action.values()) { names.addAll(asList(action.names)); } - return names.toArray(new String[0]); } } diff --git a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java index 4743b79b..38279031 100644 --- a/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java +++ b/src/main/java/baritone/utils/schematic/schematica/SchematicAdapter.java @@ -25,6 +25,7 @@ import net.minecraft.util.math.BlockPos; import java.util.List; public final class SchematicAdapter implements ISchematic { + private final SchematicWorld schematic; public SchematicAdapter(SchematicWorld schematicWorld) { diff --git a/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java b/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java index 280b38a6..4c9da008 100644 --- a/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java +++ b/src/schematica_api/java/com/github/lunatrius/core/util/math/MBlockPos.java @@ -20,6 +20,7 @@ package com.github.lunatrius.core.util.math; import net.minecraft.util.math.BlockPos; public class MBlockPos extends BlockPos { + MBlockPos() { super(6, 6, 6); } diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/Schematica.java b/src/schematica_api/java/com/github/lunatrius/schematica/Schematica.java index 7d786dbd..415399df 100644 --- a/src/schematica_api/java/com/github/lunatrius/schematica/Schematica.java +++ b/src/schematica_api/java/com/github/lunatrius/schematica/Schematica.java @@ -20,5 +20,6 @@ package com.github.lunatrius.schematica; import com.github.lunatrius.schematica.proxy.CommonProxy; public class Schematica { + public static CommonProxy proxy; } diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/api/ISchematic.java b/src/schematica_api/java/com/github/lunatrius/schematica/api/ISchematic.java index 6430dbfc..bbf11428 100644 --- a/src/schematica_api/java/com/github/lunatrius/schematica/api/ISchematic.java +++ b/src/schematica_api/java/com/github/lunatrius/schematica/api/ISchematic.java @@ -21,6 +21,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; public interface ISchematic { + IBlockState getBlockState(BlockPos var1); int getWidth(); diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java b/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java index d24074c4..25e5c280 100644 --- a/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java +++ b/src/schematica_api/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java @@ -21,6 +21,7 @@ import com.github.lunatrius.core.util.math.MBlockPos; import com.github.lunatrius.schematica.api.ISchematic; public class SchematicWorld { + public final MBlockPos position = (MBlockPos) (Object) "cringe"; public ISchematic getSchematic() { diff --git a/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java b/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java index 191d0110..952f86a1 100644 --- a/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java +++ b/src/schematica_api/java/com/github/lunatrius/schematica/proxy/ClientProxy.java @@ -20,5 +20,6 @@ package com.github.lunatrius.schematica.proxy; import com.github.lunatrius.schematica.client.world.SchematicWorld; public class ClientProxy extends CommonProxy { + public static SchematicWorld schematic; } From 307d6a06284b4d525485c3a0a23df72bc393af02 Mon Sep 17 00:00:00 2001 From: 0x22 <0x22@futureclient.net> Date: Thu, 19 Sep 2019 17:05:15 -0400 Subject: [PATCH 639/682] Remove retarded MC field --- src/api/java/baritone/api/utils/command/Command.java | 2 -- .../java/baritone/utils/command/defaults/ComeCommand.java | 2 +- .../baritone/utils/command/defaults/ExploreFilterCommand.java | 2 +- .../java/baritone/utils/command/defaults/RenderCommand.java | 4 ++-- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index 0c982854..6d415865 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -23,7 +23,6 @@ import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; -import net.minecraft.client.Minecraft; import java.util.Collections; import java.util.List; @@ -35,7 +34,6 @@ public abstract class Command implements Helper { protected IBaritone baritone; protected IPlayerContext ctx; - protected Minecraft MC = mc; /** * The names of this command. This is what you put after the command prefix. */ diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index f18d4226..857d8d01 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -41,7 +41,7 @@ public class ComeCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); - Entity entity = MC.getRenderViewEntity(); + Entity entity = mc.getRenderViewEntity(); if (isNull(entity)) { throw new CommandInvalidStateException("render view entity is null"); } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index 40cf3a6a..64c6335e 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -42,7 +42,7 @@ public class ExploreFilterCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(2); - File file = args.getDatatypePost(RelativeFile.class, MC.gameDir.getAbsoluteFile().getParentFile()); + File file = args.getDatatypePost(RelativeFile.class, mc.gameDir.getAbsoluteFile().getParentFile()); boolean invert = false; if (args.has()) { if (args.getString().equalsIgnoreCase("invert")) { diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index 0dedc398..cc07f477 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -38,8 +38,8 @@ public class RenderCommand extends Command { protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); BetterBlockPos origin = ctx.playerFeet(); - int renderDistance = (MC.gameSettings.renderDistanceChunks + 1) * 16; - MC.renderGlobal.markBlockRangeForRenderUpdate( + int renderDistance = (mc.gameSettings.renderDistanceChunks + 1) * 16; + mc.renderGlobal.markBlockRangeForRenderUpdate( origin.x - renderDistance, 0, origin.z - renderDistance, From b63c54b657f8211e289349edc6c6b873067ec2af Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 14:09:09 -0700 Subject: [PATCH 640/682] remove isNull and nonNull --- src/api/java/baritone/api/utils/BlockOptionalMeta.java | 4 +--- .../baritone/api/utils/command/BaritoneChatControl.java | 7 ++----- .../api/utils/command/argparser/ArgParserManager.java | 6 ++---- .../api/utils/command/datatypes/EntityClassById.java | 4 +--- .../api/utils/command/datatypes/PlayerByUsername.java | 4 +--- .../api/utils/command/datatypes/RelativeBlockPos.java | 4 +--- .../baritone/api/utils/command/datatypes/RelativeGoal.java | 4 +--- .../api/utils/command/execution/CommandExecution.java | 4 +--- .../api/utils/command/helpers/pagination/Paginator.java | 7 +++---- .../baritone/api/utils/command/manager/CommandManager.java | 5 ++--- .../java/baritone/launch/mixins/MixinTabCompleter.java | 4 +--- src/main/java/baritone/cache/WorldScanner.java | 4 +--- .../java/baritone/utils/command/defaults/ComeCommand.java | 3 +-- .../baritone/utils/command/defaults/FollowCommand.java | 6 ++---- .../java/baritone/utils/command/defaults/GoalCommand.java | 6 ++---- .../java/baritone/utils/command/defaults/HelpCommand.java | 3 +-- .../baritone/utils/command/defaults/InvertCommand.java | 3 +-- .../java/baritone/utils/command/defaults/PathCommand.java | 5 ++--- .../java/baritone/utils/command/defaults/ProcCommand.java | 3 +-- .../java/baritone/utils/command/defaults/SetCommand.java | 6 ++---- .../baritone/utils/command/defaults/VersionCommand.java | 3 +-- 21 files changed, 30 insertions(+), 65 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMeta.java b/src/api/java/baritone/api/utils/BlockOptionalMeta.java index 7effe4bd..c65b6d3d 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMeta.java @@ -35,8 +35,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; -import static java.util.Objects.isNull; - public final class BlockOptionalMeta { private final Block block; @@ -50,7 +48,7 @@ public final class BlockOptionalMeta { public BlockOptionalMeta(@Nonnull Block block, @Nullable Integer meta) { this.block = block; - this.noMeta = isNull(meta); + this.noMeta = meta == null; this.meta = noMeta ? 0 : meta; this.blockstates = getStates(block, meta); this.stateHashes = getStateHashes(blockstates); diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index d7b07872..0c6fc5fd 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -47,9 +47,6 @@ import java.util.Locale; import java.util.UUID; import java.util.stream.Stream; -import static java.util.Objects.isNull; -import static java.util.Objects.nonNull; - public class BaritoneChatControl implements Helper, AbstractGameEventListener { public final IBaritone baritone; @@ -139,7 +136,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } } CommandExecution execution = CommandExecution.from(pair); - if (isNull(execution)) { + if (execution == null) { return false; } logRanCommand(command, rest); @@ -178,7 +175,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { .stream(); } Settings.Setting setting = settings.byLowerName.get(argc.getString().toLowerCase(Locale.US)); - if (nonNull(setting)) { + if (setting != null) { if (setting.getValueClass() == Boolean.class) { TabCompleteHelper helper = new TabCompleteHelper(); if ((Boolean) setting.value) { diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index 8d8d160b..a87a8925 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -22,8 +22,6 @@ import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.exception.CommandNoParserForTypeException; import baritone.api.utils.command.registry.Registry; -import static java.util.Objects.isNull; - public class ArgParserManager { public static final Registry REGISTRY = new Registry<>(); @@ -74,7 +72,7 @@ public class ArgParserManager { */ public static T parseStateless(Class klass, CommandArgument arg) { ArgParser.Stateless parser = getParserStateless(klass); - if (isNull(parser)) { + if (parser == null) { throw new CommandNoParserForTypeException(klass); } try { @@ -97,7 +95,7 @@ public class ArgParserManager { */ public static T parseStated(Class klass, Class stateKlass, CommandArgument arg, S state) { ArgParser.Stated parser = getParserStated(klass, stateKlass); - if (isNull(parser)) { + if (parser == null) { throw new CommandNoParserForTypeException(klass); } try { diff --git a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java index a6dcad75..45546119 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java @@ -25,8 +25,6 @@ import net.minecraft.util.ResourceLocation; import java.util.stream.Stream; -import static java.util.Objects.isNull; - public class EntityClassById implements IDatatypeFor> { public final Class entity; @@ -37,7 +35,7 @@ public class EntityClassById implements IDatatypeFor> { public EntityClassById(ArgConsumer consumer) { ResourceLocation id = new ResourceLocation(consumer.getString()); - if (isNull(entity = EntityList.REGISTRY.getObject(id))) { + if ((entity = EntityList.REGISTRY.getObject(id)) == null) { throw new IllegalArgumentException("no entity found by that id"); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java index d8406606..5cf25066 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java +++ b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java @@ -25,8 +25,6 @@ import net.minecraft.entity.player.EntityPlayer; import java.util.List; import java.util.stream.Stream; -import static java.util.Objects.isNull; - public class PlayerByUsername implements IDatatypeFor { private final List players = @@ -44,7 +42,7 @@ public class PlayerByUsername implements IDatatypeFor { .filter(s -> s.getName().equalsIgnoreCase(username)) .findFirst() .orElse(null); - if (isNull(player)) { + if (player == null) { throw new IllegalArgumentException("no player found by that username"); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java index b69fe003..610b8d5f 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java @@ -22,8 +22,6 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; -import static java.util.Objects.isNull; - public class RelativeBlockPos implements IDatatypePost { final RelativeCoordinate x; @@ -55,7 +53,7 @@ public class RelativeBlockPos implements IDatatypePost tabComplete(ArgConsumer consumer) { if (consumer.has() && !consumer.has(4)) { while (consumer.has(2)) { - if (isNull(consumer.peekDatatypeOrNull(RelativeCoordinate.class))) { + if (consumer.peekDatatypeOrNull(RelativeCoordinate.class) == null) { break; } consumer.get(); diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java index 6abb88b7..d3aad7b9 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java @@ -28,8 +28,6 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; -import static java.util.Objects.nonNull; - public class RelativeGoal implements IDatatypePost { final RelativeCoordinate[] coords; @@ -41,7 +39,7 @@ public class RelativeGoal implements IDatatypePost { public RelativeGoal(ArgConsumer consumer) { List coordsList = new ArrayList<>(); for (int i = 0; i < 3; i++) { - if (nonNull(consumer.peekDatatypeOrNull(RelativeCoordinate.class))) { + if (consumer.peekDatatypeOrNull(RelativeCoordinate.class) != null) { coordsList.add(consumer.getDatatype(RelativeCoordinate.class)); } } diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java index 26716b87..b82926e4 100644 --- a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java +++ b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java @@ -30,8 +30,6 @@ import com.mojang.realmsclient.util.Pair; import java.util.List; import java.util.stream.Stream; -import static java.util.Objects.isNull; - public class CommandExecution { /** @@ -88,7 +86,7 @@ public class CommandExecution { public static CommandExecution from(String label, ArgConsumer args) { Command command = CommandManager.getCommand(label); - if (isNull(command)) { + if (command == null) { return null; } return new CommandExecution( diff --git a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java index 3904408f..05016d63 100644 --- a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java +++ b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java @@ -30,7 +30,6 @@ import java.util.List; import java.util.function.Function; import static java.util.Arrays.asList; -import static java.util.Objects.nonNull; public class Paginator implements Helper { @@ -73,8 +72,8 @@ public class Paginator implements Helper { logDirect("--", TextFormatting.DARK_GRAY); } } - boolean hasPrevPage = nonNull(commandPrefix) && validPage(page - 1); - boolean hasNextPage = nonNull(commandPrefix) && validPage(page + 1); + boolean hasPrevPage = commandPrefix != null && validPage(page - 1); + boolean hasNextPage = commandPrefix != null && validPage(page + 1); ITextComponent prevPageComponent = new TextComponentString("<<"); if (hasPrevPage) { prevPageComponent.getStyle() @@ -133,7 +132,7 @@ public class Paginator implements Helper { } } pagi.skipPages(page - pagi.page); - if (nonNull(pre)) { + if (pre != null) { pre.run(); } pagi.display(transform, commandPrefix); diff --git a/src/api/java/baritone/api/utils/command/manager/CommandManager.java b/src/api/java/baritone/api/utils/command/manager/CommandManager.java index ad90131b..8203ce45 100644 --- a/src/api/java/baritone/api/utils/command/manager/CommandManager.java +++ b/src/api/java/baritone/api/utils/command/manager/CommandManager.java @@ -29,7 +29,6 @@ import java.util.Locale; import java.util.stream.Stream; import static java.util.Objects.isNull; -import static java.util.Objects.nonNull; public class CommandManager { @@ -54,10 +53,10 @@ public class CommandManager { public static boolean execute(String string) { CommandExecution execution = CommandExecution.from(string); - if (nonNull(execution)) { + if (execution != null) { execution.execute(); } - return nonNull(execution); + return execution != null; } public static Stream tabComplete(CommandExecution execution) { diff --git a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java index 7de73ead..cdbae3b4 100644 --- a/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java +++ b/src/launch/java/baritone/launch/mixins/MixinTabCompleter.java @@ -31,8 +31,6 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import static java.util.Objects.isNull; - @Mixin(TabCompleter.class) public abstract class MixinTabCompleter implements ITabCompleter { @@ -105,7 +103,7 @@ public abstract class MixinTabCompleter implements ITabCompleter { public boolean onGuiChatSetCompletions(String[] newCompl) { IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone(); - if (isNull(baritone)) { + if (baritone == null) { return false; } diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index de9e6fe9..d31c17ab 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -34,8 +34,6 @@ import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import java.util.*; import java.util.stream.IntStream; -import static java.util.Objects.nonNull; - public enum WorldScanner implements IWorldScanner { INSTANCE; @@ -162,7 +160,7 @@ public enum WorldScanner implements IWorldScanner { for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) { Chunk chunk = chunkProvider.getLoadedChunk(x, z); - if (nonNull(chunk) && !chunk.isEmpty()) { + if (chunk != null && !chunk.isEmpty()) { queued++; cachedWorld.queueForPacking(chunk); } diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index 857d8d01..e6b1431a 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -30,7 +30,6 @@ import java.util.List; import java.util.stream.Stream; import static java.util.Arrays.asList; -import static java.util.Objects.isNull; public class ComeCommand extends Command { @@ -42,7 +41,7 @@ public class ComeCommand extends Command { protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); Entity entity = mc.getRenderViewEntity(); - if (isNull(entity)) { + if (entity == null) { throw new CommandInvalidStateException("render view entity is null"); } baritone.getCustomGoalProcess().setGoalAndPath(new GoalBlock(new BlockPos(entity))); diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index 9502b6af..5424fd14 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -40,8 +40,6 @@ import java.util.function.Predicate; import java.util.stream.Stream; import static java.util.Arrays.asList; -import static java.util.Objects.isNull; -import static java.util.Objects.nonNull; public class FollowCommand extends Command { @@ -78,7 +76,7 @@ public class FollowCommand extends Command { : e -> classes.stream().anyMatch(c -> c.isInstance(e)) ); } - if (nonNull(group)) { + if (group != null) { logDirect(String.format("Following all %s", group.name().toLowerCase(Locale.US))); } else { logDirect("Following these types of entities:"); @@ -112,7 +110,7 @@ public class FollowCommand extends Command { return Stream.empty(); } while (args.has(2)) { - if (isNull(args.peekDatatypeOrNull(followType))) { + if (args.peekDatatypeOrNull(followType) == null) { return Stream.empty(); } args.get(); diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index a62355c3..c793182a 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -32,8 +32,6 @@ import java.util.List; import java.util.stream.Stream; import static java.util.Arrays.asList; -import static java.util.Objects.isNull; -import static java.util.Objects.nonNull; public class GoalCommand extends Command { @@ -46,7 +44,7 @@ public class GoalCommand extends Command { ICustomGoalProcess goalProcess = baritone.getCustomGoalProcess(); if (args.has() && asList("reset", "clear", "none").contains(args.peekString())) { args.requireMax(1); - if (nonNull(goalProcess.getGoal())) { + if (goalProcess.getGoal() != null) { goalProcess.setGoal(null); logDirect("Cleared goal"); } else { @@ -69,7 +67,7 @@ public class GoalCommand extends Command { } else { if (args.hasAtMost(3)) { while (args.has(2)) { - if (isNull(args.peekDatatypeOrNull(RelativeCoordinate.class))) { + if (args.peekDatatypeOrNull(RelativeCoordinate.class) == null) { break; } args.get(); diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index 289e709e..b41e5d28 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -38,7 +38,6 @@ import java.util.stream.Stream; import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; import static baritone.api.utils.command.manager.CommandManager.getCommand; import static java.util.Arrays.asList; -import static java.util.Objects.isNull; public class HelpCommand extends Command { @@ -83,7 +82,7 @@ public class HelpCommand extends Command { } else { String commandName = args.getString().toLowerCase(); Command command = getCommand(commandName); - if (isNull(command)) { + if (command == null) { throw new CommandNotFoundException(commandName); } logDirect(String.format("%s - %s", String.join(" / ", command.names), command.getShortDesc())); diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index 368bdc4e..e7c8ef8f 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -30,7 +30,6 @@ import java.util.List; import java.util.stream.Stream; import static java.util.Arrays.asList; -import static java.util.Objects.isNull; public class InvertCommand extends Command { @@ -43,7 +42,7 @@ public class InvertCommand extends Command { args.requireMax(0); ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; - if (isNull(goal = customGoalProcess.getGoal())) { + if ((goal = customGoalProcess.getGoal()) == null) { throw new CommandInvalidStateException("No goal"); } if (goal instanceof GoalInverted) { diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index 3a0fc5d4..5f3c06bc 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -33,7 +33,6 @@ import java.util.List; import java.util.stream.Stream; import static java.util.Arrays.asList; -import static java.util.Objects.isNull; public class PathCommand extends Command { @@ -48,7 +47,7 @@ public class PathCommand extends Command { if (args.has()) { args.requireMax(3); goal = args.getDatatype(RelativeGoal.class).apply(ctx.playerFeet()); - } else if (isNull(goal = customGoalProcess.getGoal())) { + } else if ((goal = customGoalProcess.getGoal()) == null) { throw new CommandInvalidStateException("No goal"); } args.requireMax(0); @@ -61,7 +60,7 @@ public class PathCommand extends Command { protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { if (args.has() && !args.has(4)) { while (args.has(2)) { - if (isNull(args.peekDatatypeOrNull(RelativeCoordinate.class))) { + if (args.peekDatatypeOrNull(RelativeCoordinate.class) == null) { break; } args.get(); diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index 03e069d0..33a29362 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -30,7 +30,6 @@ import java.util.List; import java.util.stream.Stream; import static java.util.Arrays.asList; -import static java.util.Objects.isNull; public class ProcCommand extends Command { @@ -43,7 +42,7 @@ public class ProcCommand extends Command { args.requireMax(0); IPathingControlManager pathingControlManager = baritone.getPathingControlManager(); IBaritoneProcess process = pathingControlManager.mostRecentInControl().orElse(null); - if (isNull(process)) { + if (process == null) { throw new CommandInvalidStateException("No process in control"); } logDirect(String.format( diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index 96130414..4c93f77a 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -40,8 +40,6 @@ import static baritone.api.utils.SettingsUtil.settingTypeToString; import static baritone.api.utils.SettingsUtil.settingValueToString; import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; import static java.util.Arrays.asList; -import static java.util.Objects.isNull; -import static java.util.Objects.nonNull; import static java.util.stream.Stream.of; public class SetCommand extends Command { @@ -126,7 +124,7 @@ public class SetCommand extends Command { .filter(s -> s.getName().equalsIgnoreCase(settingName)) .findFirst() .orElse(null); - if (isNull(setting)) { + if (setting == null) { throw new CommandInvalidTypeException(args.consumed(), "a valid setting"); } if (!doingSomething && !args.has()) { @@ -204,7 +202,7 @@ public class SetCommand extends Command { .stream(); } Settings.Setting setting = settings.byLowerName.get(arg.toLowerCase(Locale.US)); - if (nonNull(setting)) { + if (setting != null) { if (setting.getType() == Boolean.class) { TabCompleteHelper helper = new TabCompleteHelper(); if ((Boolean) setting.value) { diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index f795315d..ef07b688 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -27,7 +27,6 @@ import java.util.List; import java.util.stream.Stream; import static java.util.Arrays.asList; -import static java.util.Objects.isNull; public class VersionCommand extends Command { @@ -39,7 +38,7 @@ public class VersionCommand extends Command { protected void executed(String label, ArgConsumer args, Settings settings) { args.requireMax(0); String version = getClass().getPackage().getImplementationVersion(); - if (isNull(version)) { + if (version == null) { throw new CommandInvalidStateException("Null version (this is normal in a dev environment)"); } else { logDirect(String.format("You are running Baritone v%s", version)); From fbabbe69c0c76b2b898590b0168844e09aafc45f Mon Sep 17 00:00:00 2001 From: 0x22 <0x22@futureclient.net> Date: Thu, 19 Sep 2019 17:36:06 -0400 Subject: [PATCH 641/682] =?UTF-8?q?Fix=20a=20MAJOR=20bug=20caused=20by=20t?= =?UTF-8?q?he=20JetBrains=E2=84=A2=20AutoFormatter=E2=84=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/baritone/cache/ChunkPacker.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index 9b754869..bfeeabd7 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -87,9 +87,9 @@ public final class ChunkPacker { //System.out.println("Chunk packing took " + (end - start) + "ms for " + chunk.x + "," + chunk.z); IBlockState[] blocks = new IBlockState[256]; + // @formatter:off for (int z = 0; z < 16; z++) { - https: -//www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html + https://www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html for (int x = 0; x < 16; x++) { for (int y = 255; y >= 0; y--) { int index = CachedChunk.getPositionIndex(x, y, z); @@ -101,6 +101,7 @@ public final class ChunkPacker { blocks[z << 4 | x] = Blocks.AIR.getDefaultState(); } } + // @formatter:on return new CachedChunk(chunk.x, chunk.z, bitSet, blocks, specialBlocks, System.currentTimeMillis()); } From f0c78751bf71657cc15e4eb6daf6fb33fb3780ae Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 14:38:13 -0700 Subject: [PATCH 642/682] no more asList static --- .../java/baritone/api/cache/IWaypoint.java | 4 +--- .../api/utils/BlockOptionalMetaLookup.java | 4 +--- src/api/java/baritone/api/utils/Helper.java | 4 +--- .../command/argparser/DefaultArgParsers.java | 9 ++++----- .../exception/CommandUnhandledException.java | 4 +--- .../command/helpers/pagination/Paginator.java | 13 ++++++------- .../utils/command/defaults/AxisCommand.java | 7 +++---- .../command/defaults/BlacklistCommand.java | 5 ++--- .../utils/command/defaults/BuildCommand.java | 5 ++--- .../utils/command/defaults/CancelCommand.java | 7 +++---- .../utils/command/defaults/ChestsCommand.java | 5 ++--- .../command/defaults/ClearareaCommand.java | 5 ++--- .../utils/command/defaults/ClickCommand.java | 5 ++--- .../utils/command/defaults/ComeCommand.java | 5 ++--- .../command/defaults/DefaultCommands.java | 4 +--- .../utils/command/defaults/EmptyCommand.java | 7 +++---- .../command/defaults/ExploreCommand.java | 5 ++--- .../defaults/ExploreFilterCommand.java | 5 ++--- .../utils/command/defaults/FarmCommand.java | 5 ++--- .../utils/command/defaults/FindCommand.java | 5 ++--- .../utils/command/defaults/FollowCommand.java | 9 ++------- .../command/defaults/ForceCancelCommand.java | 5 ++--- .../utils/command/defaults/GcCommand.java | 5 ++--- .../utils/command/defaults/GoalCommand.java | 7 +++---- .../utils/command/defaults/HelpCommand.java | 6 +++--- .../utils/command/defaults/InvertCommand.java | 5 ++--- .../utils/command/defaults/MineCommand.java | 5 ++--- .../utils/command/defaults/PathCommand.java | 7 +++---- .../command/defaults/PauseResumeCommands.java | 9 ++++----- .../utils/command/defaults/ProcCommand.java | 5 ++--- .../command/defaults/ReloadAllCommand.java | 5 ++--- .../utils/command/defaults/RenderCommand.java | 5 ++--- .../utils/command/defaults/RepackCommand.java | 7 +++---- .../command/defaults/SaveAllCommand.java | 5 ++--- .../command/defaults/SchematicaCommand.java | 5 ++--- .../utils/command/defaults/SelCommand.java | 14 +++++--------- .../utils/command/defaults/SetCommand.java | 19 +++++++++---------- .../command/defaults/ThisWayCommand.java | 7 +++---- .../utils/command/defaults/TunnelCommand.java | 5 ++--- .../command/defaults/VersionCommand.java | 5 ++--- .../command/defaults/WaypointsCommand.java | 12 ++++-------- 41 files changed, 105 insertions(+), 160 deletions(-) diff --git a/src/api/java/baritone/api/cache/IWaypoint.java b/src/api/java/baritone/api/cache/IWaypoint.java index 4c086ba2..ff235099 100644 --- a/src/api/java/baritone/api/cache/IWaypoint.java +++ b/src/api/java/baritone/api/cache/IWaypoint.java @@ -21,8 +21,6 @@ import baritone.api.utils.BetterBlockPos; import java.util.*; -import static java.util.Arrays.asList; - /** * A marker for a position in the world. * @@ -129,7 +127,7 @@ public interface IWaypoint { Set names = new HashSet<>(); for (Tag tag : Tag.values()) { - names.addAll(asList(tag.names)); + names.addAll(Arrays.asList(tag.names)); } return names.toArray(new String[0]); diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index a5f7d626..705800b8 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -24,8 +24,6 @@ import net.minecraft.item.ItemStack; import java.util.Arrays; import java.util.List; -import static java.util.Arrays.asList; - public class BlockOptionalMetaLookup { private final BlockOptionalMeta[] boms; @@ -83,7 +81,7 @@ public class BlockOptionalMetaLookup { } public List blocks() { - return asList(boms); + return Arrays.asList(boms); } @Override diff --git a/src/api/java/baritone/api/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java index 87884cd2..8ef0d29e 100755 --- a/src/api/java/baritone/api/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -25,8 +25,6 @@ import net.minecraft.util.text.TextFormatting; import java.util.Arrays; -import static java.util.Arrays.asList; - /** * @author Brady * @since 8/1/2018 @@ -75,7 +73,7 @@ public interface Helper { ITextComponent component = new TextComponentString(""); component.appendSibling(getPrefix()); component.appendSibling(new TextComponentString(" ")); - asList(components).forEach(component::appendSibling); + Arrays.asList(components).forEach(component::appendSibling); Minecraft.getMinecraft().addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component)); } diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index 743380e7..f45f7faf 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -19,11 +19,10 @@ package baritone.api.utils.command.argparser; import baritone.api.utils.command.argument.CommandArgument; +import java.util.Arrays; import java.util.List; import java.util.Locale; -import static java.util.Arrays.asList; - public class DefaultArgParsers { public static class IntArgumentParser extends ArgParser implements IArgParser.Stateless { @@ -93,8 +92,8 @@ public class DefaultArgParsers { public static class BooleanArgumentParser extends ArgParser implements IArgParser.Stateless { public static final BooleanArgumentParser INSTANCE = new BooleanArgumentParser(); - public static final List TRUTHY_VALUES = asList("1", "true", "yes", "t", "y", "on", "enable"); - public static final List FALSY_VALUES = asList("0", "false", "no", "f", "n", "off", "disable"); + public static final List TRUTHY_VALUES = Arrays.asList("1", "true", "yes", "t", "y", "on", "enable"); + public static final List FALSY_VALUES = Arrays.asList("0", "false", "no", "f", "n", "off", "disable"); public BooleanArgumentParser() { super(Boolean.class); @@ -113,7 +112,7 @@ public class DefaultArgParsers { } } - public static final List> ALL = asList( + public static final List> ALL = Arrays.asList( IntArgumentParser.INSTANCE, LongArgumentParser.INSTANCE, FloatArgumentParser.INSTANCE, diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java index 178fb721..b3cf1819 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -23,8 +23,6 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import static java.util.Arrays.asList; - public class CommandUnhandledException extends CommandErrorMessageException { public static String getStackTrace(Throwable throwable) { @@ -50,7 +48,7 @@ public class CommandUnhandledException extends CommandErrorMessageException { } public static String getFriendlierStackTrace(String stackTrace) { - List lines = asList(stackTrace.split("\n")); + List lines = Arrays.asList(stackTrace.split("\n")); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (line.startsWith("\tat ")) { diff --git a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java index 05016d63..c143d507 100644 --- a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java +++ b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java @@ -26,11 +26,10 @@ import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.HoverEvent; +import java.util.Arrays; import java.util.List; import java.util.function.Function; -import static java.util.Arrays.asList; - public class Paginator implements Helper { public final List entries; @@ -42,7 +41,7 @@ public class Paginator implements Helper { } public Paginator(E... entries) { - this.entries = asList(entries); + this.entries = Arrays.asList(entries); } public Paginator setPageSize(int pageSize) { @@ -143,7 +142,7 @@ public class Paginator implements Helper { } public static void paginate(ArgConsumer consumer, T[] elems, Runnable pre, Function transform, String commandPrefix) { - paginate(consumer, asList(elems), pre, transform, commandPrefix); + paginate(consumer, Arrays.asList(elems), pre, transform, commandPrefix); } public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform, String commandPrefix) { @@ -155,7 +154,7 @@ public class Paginator implements Helper { } public static void paginate(ArgConsumer consumer, T[] elems, Function transform, String commandPrefix) { - paginate(consumer, asList(elems), null, transform, commandPrefix); + paginate(consumer, Arrays.asList(elems), null, transform, commandPrefix); } public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform) { @@ -167,7 +166,7 @@ public class Paginator implements Helper { } public static void paginate(ArgConsumer consumer, T[] elems, Runnable pre, Function transform) { - paginate(consumer, asList(elems), pre, transform, null); + paginate(consumer, Arrays.asList(elems), pre, transform, null); } public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform) { @@ -179,6 +178,6 @@ public class Paginator implements Helper { } public static void paginate(ArgConsumer consumer, T[] elems, Function transform) { - paginate(consumer, asList(elems), null, transform, null); + paginate(consumer, Arrays.asList(elems), null, transform, null); } } diff --git a/src/main/java/baritone/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java index dd9d5a83..322fa696 100644 --- a/src/main/java/baritone/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -24,15 +24,14 @@ import baritone.api.pathing.goals.GoalAxis; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class AxisCommand extends Command { public AxisCommand(IBaritone baritone) { - super(baritone, asList("axis", "highway")); + super(baritone, Arrays.asList("axis", "highway")); } @Override @@ -55,7 +54,7 @@ public class AxisCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The axis command sets a goal that tells Baritone to head towards the nearest axis. That is, X=0 or Z=0.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index aad23f21..8264a648 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -24,11 +24,10 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class BlacklistCommand extends Command { public BlacklistCommand(IBaritone baritone) { @@ -61,7 +60,7 @@ public class BlacklistCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "While, for example, mining, this command blacklists the closest block so that Baritone won't attempt to get to it.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index 146faf0f..09cb2437 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -28,12 +28,11 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.client.Minecraft; import java.io.File; +import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class BuildCommand extends Command { private static final File schematicsDir = new File(Minecraft.getMinecraft().gameDir, "schematics"); @@ -82,7 +81,7 @@ public class BuildCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Build a schematic from a file.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index 742e2aaf..42025c9a 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -22,15 +22,14 @@ import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class CancelCommand extends Command { public CancelCommand(IBaritone baritone) { - super(baritone, asList("cancel", "stop")); + super(baritone, Arrays.asList("cancel", "stop")); } @Override @@ -52,7 +51,7 @@ public class CancelCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The cancel command tells Baritons to stop whatever it's currently doing.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index 7965745d..bde736e9 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -28,13 +28,12 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ChestsCommand extends Command { public ChestsCommand(IBaritone baritone) { @@ -74,7 +73,7 @@ public class ChestsCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The chests command lists remembered inventories, I guess?", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index 7a73be42..17fa2863 100644 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -27,11 +27,10 @@ import baritone.api.utils.command.datatypes.RelativeBlockPos; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ClearareaCommand extends Command { public ClearareaCommand(IBaritone baritone) { @@ -70,7 +69,7 @@ public class ClearareaCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Clear an area of all blocks.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java index 126f64f6..c09fd8b0 100644 --- a/src/main/java/baritone/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -22,11 +22,10 @@ import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ClickCommand extends Command { public ClickCommand(IBaritone baritone) { @@ -52,7 +51,7 @@ public class ClickCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Opens click dude", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index e6b1431a..be99cf63 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -26,11 +26,10 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ComeCommand extends Command { public ComeCommand(IBaritone baritone) { @@ -60,7 +59,7 @@ public class ComeCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The come command tells Baritone to head towards your camera.", "", "This can be useful in hacked clients where freecam doesn't move your player position.", diff --git a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java index 611ae063..1245cef8 100644 --- a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java +++ b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java @@ -22,8 +22,6 @@ import baritone.api.utils.command.Command; import java.util.*; -import static java.util.Arrays.asList; - public class DefaultCommands { public static List commands(IBaritone baritone) { @@ -32,7 +30,7 @@ public class DefaultCommands { commands.addAll(Arrays.asList( new HelpCommand(baritone), new SetCommand(baritone), - new CommandAlias(baritone, asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), + new CommandAlias(baritone, Arrays.asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), new CommandAlias(baritone, "reset", "Reset all settings or just one", "set reset"), new GoalCommand(baritone), new PathCommand(baritone), diff --git a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java index cc45e800..e673c0d2 100644 --- a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java +++ b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java @@ -22,15 +22,14 @@ import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class EmptyCommand extends Command { public EmptyCommand(IBaritone baritone) { - super(baritone, asList("name1", "name2")); + super(baritone, Arrays.asList("name1", "name2")); } @Override @@ -50,7 +49,7 @@ public class EmptyCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index 9f5beb19..86f975b7 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -24,11 +24,10 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeGoalXZ; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ExploreCommand extends Command { public ExploreCommand(IBaritone baritone) { @@ -64,7 +63,7 @@ public class ExploreCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Tell Baritone to explore randomly. If you used explorefilter before this, it will be applied.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index 64c6335e..815dc8ac 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -28,11 +28,10 @@ import com.google.gson.JsonSyntaxException; import java.io.File; import java.nio.file.NoSuchFileException; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ExploreFilterCommand extends Command { public ExploreFilterCommand(IBaritone baritone) { @@ -78,7 +77,7 @@ public class ExploreFilterCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Apply an explore filter before using explore, which tells the explore process which chunks have been explored/not explored.", "", "The JSON file will follow this format: [{\"x\":0,\"z\":0},...]", diff --git a/src/main/java/baritone/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java index ee699490..62db521d 100644 --- a/src/main/java/baritone/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -22,11 +22,10 @@ import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class FarmCommand extends Command { public FarmCommand(IBaritone baritone) { @@ -52,7 +51,7 @@ public class FarmCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The farm command starts farming nearby plants. It harvests mature crops and plants new ones.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index 61d03dd8..2f36ec01 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -26,11 +26,10 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.block.Block; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class FindCommand extends Command { public FindCommand(IBaritone baritone) { @@ -71,7 +70,7 @@ public class FindCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index 5424fd14..8240be2e 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -32,15 +32,10 @@ import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Objects; +import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class FollowCommand extends Command { public FollowCommand(IBaritone baritone) { @@ -126,7 +121,7 @@ public class FollowCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The follow command tells Baritone to follow certain kinds of entities.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index 09d2065f..6c6c740c 100644 --- a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -23,11 +23,10 @@ import baritone.api.behavior.IPathingBehavior; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ForceCancelCommand extends Command { public ForceCancelCommand(IBaritone baritone) { @@ -55,7 +54,7 @@ public class ForceCancelCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Like cancel, but more forceful.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index 6bf1355a..a0acf98f 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -22,11 +22,10 @@ import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class GcCommand extends Command { public GcCommand(IBaritone baritone) { @@ -52,7 +51,7 @@ public class GcCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Calls System.gc().", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index c793182a..e3da6330 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -28,11 +28,10 @@ import baritone.api.utils.command.datatypes.RelativeGoal; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class GoalCommand extends Command { public GoalCommand(IBaritone baritone) { @@ -42,7 +41,7 @@ public class GoalCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { ICustomGoalProcess goalProcess = baritone.getCustomGoalProcess(); - if (args.has() && asList("reset", "clear", "none").contains(args.peekString())) { + if (args.has() && Arrays.asList("reset", "clear", "none").contains(args.peekString())) { args.requireMax(1); if (goalProcess.getGoal() != null) { goalProcess.setGoal(null); @@ -87,7 +86,7 @@ public class GoalCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The goal command allows you to set or clear Baritone's goal.", "", "Wherever a coordinate is expected, you can use ~ just like in regular Minecraft commands. Or, you can just use regular numbers.", diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index b41e5d28..716e72ea 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -31,18 +31,18 @@ import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.HoverEvent; +import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; import static baritone.api.utils.command.manager.CommandManager.getCommand; -import static java.util.Arrays.asList; public class HelpCommand extends Command { public HelpCommand(IBaritone baritone) { - super(baritone, asList("help", "?")); + super(baritone, Arrays.asList("help", "?")); } @Override @@ -113,7 +113,7 @@ public class HelpCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Using this command, you can view detailed help information on how to use certain commands of Baritone.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index e7c8ef8f..bc8e1765 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -26,11 +26,10 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class InvertCommand extends Command { public InvertCommand(IBaritone baritone) { @@ -66,7 +65,7 @@ public class InvertCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The invert command tells Baritone to head away from the current goal rather than towards it.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index 1dcc962a..d9328984 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -27,11 +27,10 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.cache.WorldScanner; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class MineCommand extends Command { public MineCommand(IBaritone baritone) { @@ -63,7 +62,7 @@ public class MineCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The mine command allows you to tell Baritone to search for and mine individual blocks.", "", "The specified blocks can be ores (which are commonly cached), or any other block.", diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index 5f3c06bc..45172299 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -29,15 +29,14 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.cache.WorldScanner; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class PathCommand extends Command { public PathCommand(IBaritone baritone) { - super(baritone, asList("path", "goto")); + super(baritone, Arrays.asList("path", "goto")); } @Override @@ -82,7 +81,7 @@ public class PathCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The path command tells Baritone to head towards the current goal.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index 7e7a242c..ce221190 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -26,11 +26,10 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - /** * Contains the pause, resume, and paused commands. *

@@ -103,7 +102,7 @@ public class PauseResumeCommands { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The pause command tells Baritone to temporarily stop whatever it's doing.", "", "This can be used to pause pathing, building, following, whatever. A single use of the resume command will start it right back up again!", @@ -136,7 +135,7 @@ public class PauseResumeCommands { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The resume command tells Baritone to resume whatever it was doing when you last used pause.", "", "Usage:", @@ -163,7 +162,7 @@ public class PauseResumeCommands { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The paused command tells you if Baritone is currently paused by use of the pause command.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index 33a29362..d5d5b156 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -26,11 +26,10 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ProcCommand extends Command { public ProcCommand(IBaritone baritone) { @@ -74,7 +73,7 @@ public class ProcCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The proc command provides miscellaneous information about the process currently controlling Baritone.", "", "You are not expected to understand this if you aren't familiar with how Baritone works.", diff --git a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index e2528394..37640fbd 100644 --- a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -22,11 +22,10 @@ import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ReloadAllCommand extends Command { public ReloadAllCommand(IBaritone baritone) { @@ -52,7 +51,7 @@ public class ReloadAllCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The reloadall command reloads Baritone's world cache.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index cc07f477..494104ec 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -23,11 +23,10 @@ import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class RenderCommand extends Command { public RenderCommand(IBaritone baritone) { @@ -62,7 +61,7 @@ public class RenderCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The render command fixes glitched chunk rendering without having to reload all of them.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java index 0415ca7a..1c5a79f7 100644 --- a/src/main/java/baritone/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -23,15 +23,14 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.cache.WorldScanner; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class RepackCommand extends Command { public RepackCommand(IBaritone baritone) { - super(baritone, asList("repack", "rescan")); + super(baritone, Arrays.asList("repack", "rescan")); } @Override @@ -52,7 +51,7 @@ public class RepackCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Repack chunks around you. This basically re-caches them.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index 2da1824d..92601467 100644 --- a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -22,11 +22,10 @@ import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class SaveAllCommand extends Command { public SaveAllCommand(IBaritone baritone) { @@ -52,7 +51,7 @@ public class SaveAllCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The saveall command saves Baritone's world cache.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index e54a6e79..18e51738 100644 --- a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -22,11 +22,10 @@ import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class SchematicaCommand extends Command { public SchematicaCommand(IBaritone baritone) { @@ -51,7 +50,7 @@ public class SchematicaCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Builds the schematica currently open in Schematica.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index 296b6e61..25c3ffd8 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -44,22 +44,18 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.Vec3i; import java.awt.*; -import java.util.ArrayList; -import java.util.HashSet; +import java.util.*; import java.util.List; -import java.util.Set; import java.util.function.Function; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class SelCommand extends Command { private ISelectionManager manager = baritone.getSelectionManager(); private BetterBlockPos pos1 = null; public SelCommand(IBaritone baritone) { - super(baritone, asList("sel", "selection", "s")); + super(baritone, Arrays.asList("sel", "selection", "s")); baritone.getGameEventHandler().registerEventListener(new AbstractGameEventListener() { @Override public void onRenderPass(RenderEvent event) { @@ -236,7 +232,7 @@ public class SelCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The sel command allows you to manipulate Baritone's selections, similarly to WorldEdit.", "", "Using these selections, you can clear areas, fill them with blocks, or something else.", @@ -296,7 +292,7 @@ public class SelCommand extends Command { public static String[] getAllNames() { Set names = new HashSet<>(); for (Action action : Action.values()) { - names.addAll(asList(action.names)); + names.addAll(Arrays.asList(action.names)); } return names.toArray(new String[0]); } @@ -332,7 +328,7 @@ public class SelCommand extends Command { public static String[] getAllNames() { Set names = new HashSet<>(); for (TransformTarget target : TransformTarget.values()) { - names.addAll(asList(target.names)); + names.addAll(Arrays.asList(target.names)); } return names.toArray(new String[0]); } diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index 4c93f77a..dbcfbae0 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -31,6 +31,7 @@ import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.HoverEvent; +import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; @@ -39,25 +40,23 @@ import java.util.stream.Stream; import static baritone.api.utils.SettingsUtil.settingTypeToString; import static baritone.api.utils.SettingsUtil.settingValueToString; import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; -import static java.util.Arrays.asList; -import static java.util.stream.Stream.of; public class SetCommand extends Command { public SetCommand(IBaritone baritone) { - super(baritone, asList("set", "setting", "settings")); + super(baritone, Arrays.asList("set", "setting", "settings")); } @Override protected void executed(String label, ArgConsumer args, Settings settings) { String arg = args.has() ? args.getString().toLowerCase(Locale.US) : "list"; - if (asList("s", "save").contains(arg)) { + if (Arrays.asList("s", "save").contains(arg)) { SettingsUtil.save(settings); logDirect("Settings saved"); return; } - boolean viewModified = asList("m", "mod", "modified").contains(arg); - boolean viewAll = asList("all", "l", "list").contains(arg); + boolean viewModified = Arrays.asList("m", "mod", "modified").contains(arg); + boolean viewAll = Arrays.asList("all", "l", "list").contains(arg); boolean paginate = viewModified || viewAll; if (paginate) { String search = args.has() && args.peekAsOrNull(Integer.class) == null ? args.getString() : ""; @@ -188,7 +187,7 @@ public class SetCommand extends Command { protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { if (args.has()) { String arg = args.getString(); - if (args.hasExactlyOne() && !asList("s", "save").contains(args.peekString().toLowerCase(Locale.US))) { + if (args.hasExactlyOne() && !Arrays.asList("s", "save").contains(args.peekString().toLowerCase(Locale.US))) { if (arg.equalsIgnoreCase("reset")) { return new TabCompleteHelper() .addModifiedSettings() @@ -206,9 +205,9 @@ public class SetCommand extends Command { if (setting.getType() == Boolean.class) { TabCompleteHelper helper = new TabCompleteHelper(); if ((Boolean) setting.value) { - helper.append(of("true", "false")); + helper.append(Stream.of("true", "false")); } else { - helper.append(of("false", "true")); + helper.append(Stream.of("false", "true")); } return helper.filterPrefix(args.getString()).stream(); } else { @@ -234,7 +233,7 @@ public class SetCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Using the set command, you can manage all of Baritone's settings. Almost every aspect is controlled by these settings - go wild!", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index 27cefcc9..80c3d69b 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -23,15 +23,14 @@ import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class ThisWayCommand extends Command { public ThisWayCommand(IBaritone baritone) { - super(baritone, asList("thisway", "forward")); + super(baritone, Arrays.asList("thisway", "forward")); } @Override @@ -58,7 +57,7 @@ public class ThisWayCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "Creates a GoalXZ some amount of blocks in the direction you're currently looking", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index c7da7f85..d89c996a 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -24,11 +24,10 @@ import baritone.api.pathing.goals.GoalStrictDirection; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class TunnelCommand extends Command { public TunnelCommand(IBaritone baritone) { @@ -58,7 +57,7 @@ public class TunnelCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The tunnel command sets a goal that tells Baritone to mine completely straight in the direction that you're facing.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index ef07b688..6e8812a4 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -23,11 +23,10 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import java.util.Arrays; import java.util.List; import java.util.stream.Stream; -import static java.util.Arrays.asList; - public class VersionCommand extends Command { public VersionCommand(IBaritone baritone) { @@ -57,7 +56,7 @@ public class VersionCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The version command prints the version of Baritone you're currently running.", "", "Usage:", diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 97618390..863c9754 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -38,21 +38,17 @@ import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.HoverEvent; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; -import static java.util.Arrays.asList; public class WaypointsCommand extends Command { public WaypointsCommand(IBaritone baritone) { - super(baritone, asList("waypoints", "waypoint", "wp")); + super(baritone, Arrays.asList("waypoints", "waypoint", "wp")); } @Override @@ -279,7 +275,7 @@ public class WaypointsCommand extends Command { @Override public List getLongDesc() { - return asList( + return Arrays.asList( "The waypoint command allows you to manage Baritone's waypoints.", "", "Waypoints can be used to mark positions for later. Waypoints are each given a tag and an optional name.", @@ -324,7 +320,7 @@ public class WaypointsCommand extends Command { public static String[] getAllNames() { Set names = new HashSet<>(); for (Action action : Action.values()) { - names.addAll(asList(action.names)); + names.addAll(Arrays.asList(action.names)); } return names.toArray(new String[0]); } From 050b6046d7ae57f2ae414689f77fe9d6cb90002a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 14:43:18 -0700 Subject: [PATCH 643/682] small tweaks --- .../java/baritone/utils/command/defaults/BlacklistCommand.java | 2 +- .../java/baritone/utils/command/defaults/CancelCommand.java | 2 +- .../java/baritone/utils/command/defaults/InvertCommand.java | 2 +- .../java/baritone/utils/command/defaults/TunnelCommand.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index 8264a648..b70a9a13 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -61,7 +61,7 @@ public class BlacklistCommand extends Command { @Override public List getLongDesc() { return Arrays.asList( - "While, for example, mining, this command blacklists the closest block so that Baritone won't attempt to get to it.", + "While going to a block this command blacklists the closest block so that Baritone won't attempt to get to it.", "", "Usage:", "> blacklist" diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index 42025c9a..64b977a3 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -52,7 +52,7 @@ public class CancelCommand extends Command { @Override public List getLongDesc() { return Arrays.asList( - "The cancel command tells Baritons to stop whatever it's currently doing.", + "The cancel command tells Baritone to stop whatever it's currently doing.", "", "Usage:", "> cancel" diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index bc8e1765..1f3b1b98 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -49,7 +49,7 @@ public class InvertCommand extends Command { } else { goal = new GoalInverted(goal); } - customGoalProcess.setGoal(goal); + customGoalProcess.setGoalAndPath(goal); logDirect(String.format("Goal: %s", goal.toString())); } diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index d89c996a..dbed314d 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -41,7 +41,7 @@ public class TunnelCommand extends Command { ctx.playerFeet(), ctx.player().getHorizontalFacing() ); - baritone.getCustomGoalProcess().setGoal(goal); + baritone.getCustomGoalProcess().setGoalAndPath(goal); logDirect(String.format("Goal: %s", goal.toString())); } From e976224258dd6566a8a984a527ee1b518c92b7c2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 15:31:21 -0700 Subject: [PATCH 644/682] a moderate amount of gamer --- src/api/java/baritone/api/Settings.java | 2 +- .../baritone/api/schematic/MaskSchematic.java | 2 +- src/main/java/baritone/utils/GuiClick.java | 17 ++++++++++++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 22d597da..9a03fac2 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -991,7 +991,7 @@ public final class Settings { /** * Line width of the goal when rendered, in pixels */ - public final Setting selectionLineWidth = new Setting<>(1F); + public final Setting selectionLineWidth = new Setting<>(2F); /** * Render selections diff --git a/src/api/java/baritone/api/schematic/MaskSchematic.java b/src/api/java/baritone/api/schematic/MaskSchematic.java index f74ccc8f..fa9b8126 100644 --- a/src/api/java/baritone/api/schematic/MaskSchematic.java +++ b/src/api/java/baritone/api/schematic/MaskSchematic.java @@ -35,7 +35,7 @@ public abstract class MaskSchematic extends AbstractSchematic { @Override public boolean inSchematic(int x, int y, int z, IBlockState currentState) { - return partOfMask(x, y, z, currentState) && schematic.inSchematic(x, y, z, currentState); + return schematic.inSchematic(x, y, z, currentState) && partOfMask(x, y, z, currentState); } @Override diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index 48b80231..ec8ade72 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -22,6 +22,8 @@ import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Helper; +import baritone.api.utils.command.BaritoneChatControl; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; @@ -29,6 +31,10 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.event.ClickEvent; import org.lwjgl.BufferUtils; import org.lwjgl.input.Mouse; import org.lwjgl.util.glu.GLU; @@ -75,7 +81,16 @@ public class GuiClick extends GuiScreen { protected void mouseReleased(int mouseX, int mouseY, int mouseButton) { if (mouseButton == 0) { if (clickStart != null && !clickStart.equals(currentMouseOver)) { - ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getBuilderProcess().clearArea(clickStart, currentMouseOver); + BaritoneAPI.getProvider().getPrimaryBaritone().getSelectionManager().removeAllSelections(); + BaritoneAPI.getProvider().getPrimaryBaritone().getSelectionManager().addSelection(BetterBlockPos.from(clickStart), BetterBlockPos.from(currentMouseOver)); + ITextComponent component = new TextComponentString("Selection made! For usage: " + Baritone.settings().prefix.value + "help sel"); + component.getStyle() + .setColor(TextFormatting.WHITE) + .setClickEvent(new ClickEvent( + ClickEvent.Action.RUN_COMMAND, + BaritoneChatControl.FORCE_COMMAND_PREFIX + "help sel" + )); + Helper.HELPER.logDirect(component); clickStart = null; } else { BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalTwoBlocks(currentMouseOver)); From 6f2529c2431702ab4f49529adad1ffc77f61d6d0 Mon Sep 17 00:00:00 2001 From: 0x22 <0x22@futureclient.net> Date: Thu, 19 Sep 2019 18:54:24 -0400 Subject: [PATCH 645/682] Removed very angry code. Started feeding Codacy. --- src/api/java/baritone/api/Settings.java | 2 +- src/api/java/baritone/api/utils/BlockUtils.java | 2 +- .../api/utils/command/BaritoneChatControl.java | 2 +- .../utils/command/argparser/DefaultArgParsers.java | 6 +++--- .../api/utils/command/datatypes/ForWaypoints.java | 2 +- .../api/utils/command/datatypes/RelativeFile.java | 13 +++++++------ src/main/java/baritone/process/MineProcess.java | 3 ++- .../utils/command/defaults/EmptyCommand.java | 1 - .../command/defaults/ExploreFilterCommand.java | 2 +- .../baritone/utils/command/defaults/SelCommand.java | 2 +- .../utils/command/defaults/WaypointsCommand.java | 3 +++ 11 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 9a03fac2..8d54cbde 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -30,8 +30,8 @@ import java.awt.*; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.*; import java.util.List; +import java.util.*; import java.util.function.Consumer; /** diff --git a/src/api/java/baritone/api/utils/BlockUtils.java b/src/api/java/baritone/api/utils/BlockUtils.java index 8fad35f8..43a97f83 100644 --- a/src/api/java/baritone/api/utils/BlockUtils.java +++ b/src/api/java/baritone/api/utils/BlockUtils.java @@ -41,7 +41,7 @@ public class BlockUtils { Block block = stringToBlockNullable(name); if (block == null) { - throw new NullPointerException(String.format("Invalid block name %s", name)); + throw new IllegalArgumentException(String.format("Invalid block name %s", name)); } return block; diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index 0c6fc5fd..84b6f927 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -106,7 +106,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { return false; } if (msg.isEmpty()) { - msg = "help"; + return this.runCommand("help"); } Pair> pair = CommandExecution.expand(msg); String command = pair.first(); diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index f45f7faf..6e7e70bc 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -65,7 +65,7 @@ public class DefaultArgParsers { public Float parseArg(CommandArgument arg) throws RuntimeException { String value = arg.value; if (!value.matches("^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$")) { - throw new RuntimeException("failed float format check"); + throw new IllegalArgumentException("failed float format check"); } return Float.parseFloat(value); } @@ -83,7 +83,7 @@ public class DefaultArgParsers { public Double parseArg(CommandArgument arg) throws RuntimeException { String value = arg.value; if (!value.matches("^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$")) { - throw new RuntimeException("failed double format check"); + throw new IllegalArgumentException("failed double format check"); } return Double.parseDouble(value); } @@ -107,7 +107,7 @@ public class DefaultArgParsers { } else if (FALSY_VALUES.contains(value.toLowerCase(Locale.US))) { return false; } else { - throw new RuntimeException("invalid boolean"); + throw new IllegalArgumentException("invalid boolean"); } } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java index 6aef2187..53ee8837 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -76,7 +76,7 @@ public class ForWaypoints implements IDatatypeFor { public static String[] getWaypointNames() { return Arrays.stream(getWaypoints()) .map(IWaypoint::getName) - .filter(name -> !name.equals("")) + .filter(name -> !"".equals(name)) .toArray(String[]::new); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index f67e4fab..c3d5479f 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -21,6 +21,7 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.io.File; import java.io.IOException; +import java.io.UncheckedIOException; import java.nio.file.FileSystems; import java.nio.file.InvalidPathException; import java.nio.file.Path; @@ -57,26 +58,26 @@ public class RelativeFile implements IDatatypePost { * * @param file File * @return Canonical file of file - * @author LoganDark and his hate of checked exceptions + * @author LoganDark */ - private static File SHUT_THE_FUCK_UP_IOEXCEPTION_NOBODY_LIKES_YOU(File file) { + private static File getCanonicalFileUnchecked(File file) { try { return file.getCanonicalFile(); } catch (IOException e) { - throw new RuntimeException("Fuck you", e); + throw new UncheckedIOException(e); } } public static Stream tabComplete(ArgConsumer consumer, File base0) { // I will not make the caller deal with this, seriously // Tab complete code is beautiful and I'm not going to bloat it with dumb ass checked exception bullshit - File base = SHUT_THE_FUCK_UP_IOEXCEPTION_NOBODY_LIKES_YOU(base0); + File base = getCanonicalFileUnchecked(base0); String currentPathStringThing = consumer.getString(); Path currentPath = FileSystems.getDefault().getPath(currentPathStringThing); Path basePath = currentPath.isAbsolute() ? currentPath.getRoot() : base.toPath(); boolean useParent = !currentPathStringThing.isEmpty() && !currentPathStringThing.endsWith(File.separator); File currentFile = currentPath.isAbsolute() ? currentPath.toFile() : new File(base, currentPathStringThing); - return Arrays.stream(Objects.requireNonNull(SHUT_THE_FUCK_UP_IOEXCEPTION_NOBODY_LIKES_YOU( + return Arrays.stream(Objects.requireNonNull(getCanonicalFileUnchecked( useParent ? currentFile.getParentFile() : currentFile @@ -89,7 +90,7 @@ public class RelativeFile implements IDatatypePost { @Override public File apply(File original) { - return SHUT_THE_FUCK_UP_IOEXCEPTION_NOBODY_LIKES_YOU(original.toPath().resolve(path).toFile()); + return getCanonicalFileUnchecked(original.toPath().resolve(path).toFile()); } public static File gameDir() { diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index a2e1f120..4043e627 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -408,7 +408,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro this.filter = filter; if (filter != null && !Baritone.settings().allowBreak.value) { logDirect("Unable to mine when allowBreak is false!"); - filter = null; + this.mine(quantity, (BlockOptionalMetaLookup) null); + return; } this.desiredQuantity = quantity; this.knownOreLocations = new ArrayList<>(); diff --git a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java index e673c0d2..c36bd044 100644 --- a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java +++ b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java @@ -34,7 +34,6 @@ public class EmptyCommand extends Command { @Override protected void executed(String label, ArgConsumer args, Settings settings) { - ; } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index 815dc8ac..cdbc0e8c 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -57,7 +57,7 @@ public class ExploreFilterCommand extends Command { } catch (JsonSyntaxException e) { throw new CommandInvalidStateException("Invalid JSON syntax"); } catch (Exception e) { - throw new RuntimeException(e); + throw new IllegalStateException(e); } logDirect(String.format("Explore filter applied. Inverted: %s", Boolean.toString(invert))); } diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index 25c3ffd8..dfa8e957 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -44,8 +44,8 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.Vec3i; import java.awt.*; -import java.util.*; import java.util.List; +import java.util.*; import java.util.function.Function; import java.util.stream.Stream; diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 863c9754..c94d757d 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -170,6 +170,9 @@ public class WaypointsCommand extends Command { throw new CommandInvalidStateException("No waypoints found"); case 1: waypoint = waypoints[0]; + break; + default: + break; } } if (waypoint == null) { From 394775fb9a088854d7a1794a0907e224e8629d2f Mon Sep 17 00:00:00 2001 From: 0x22 <0x22@futureclient.net> Date: Thu, 19 Sep 2019 20:06:18 -0400 Subject: [PATCH 646/682] Attempt to "fix" travis. --- .../api/event/listener/IGameEventListener.java | 2 +- .../utils/command/argparser/ArgParserManager.java | 1 - .../api/utils/command/argument/CommandArgument.java | 4 ---- .../api/utils/command/datatypes/ForWaypoints.java | 2 +- .../command/helpers/arguments/ArgConsumer.java | 13 ++----------- 5 files changed, 4 insertions(+), 18 deletions(-) diff --git a/src/api/java/baritone/api/event/listener/IGameEventListener.java b/src/api/java/baritone/api/event/listener/IGameEventListener.java index 00b24e3d..b7522125 100644 --- a/src/api/java/baritone/api/event/listener/IGameEventListener.java +++ b/src/api/java/baritone/api/event/listener/IGameEventListener.java @@ -66,7 +66,7 @@ public interface IGameEventListener { /** * Runs whenever the client player tries to tab complete in chat once completions have been recieved from the - * server. This will only be called if the {@link TabCompleteEvent.Pre#cancel()} method was not called. + * server. This will only be called if the {@link TabCompleteEvent#cancel()} method was not called. * * @param event The event */ diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index a87a8925..0f7de303 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -68,7 +68,6 @@ public class ArgParserManager { * @return An instance of the specified class. * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed - * @see ArgParser.Stateless */ public static T parseStateless(Class klass, CommandArgument arg) { ArgParser.Stateless parser = getParserStateless(klass); diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index cfd4f44e..1928c65e 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -80,7 +80,6 @@ public class CommandArgument { * @return An instance of the specified type * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed - * @see ArgParser.Stateless */ public T getAs(Class type) { return ArgParserManager.parseStateless(type, this); @@ -91,7 +90,6 @@ public class CommandArgument { * * @param type The class to parse this argument into * @return If the parser succeeded - * @see ArgParser.Stateless */ public boolean is(Class type) { try { @@ -109,7 +107,6 @@ public class CommandArgument { * @return An instance of the specified type * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed - * @see ArgParser.Stated */ @SuppressWarnings("UnusedReturnValue") public T getAs(Class type, Class stateType, S state) { @@ -121,7 +118,6 @@ public class CommandArgument { * * @param type The class to parse this argument into * @return If the parser succeeded - * @see ArgParser.Stated */ public boolean is(Class type, Class stateType, S state) { try { diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java index 53ee8837..6dd302f2 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -76,7 +76,7 @@ public class ForWaypoints implements IDatatypeFor { public static String[] getWaypointNames() { return Arrays.stream(getWaypoints()) .map(IWaypoint::getName) - .filter(name -> !"".equals(name)) + .filter(name -> !name.isEmpty()) .toArray(String[]::new); } diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index 6065b5b1..219e3645 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -168,7 +168,7 @@ public class ArgConsumer implements Cloneable { /** * @param index The index to peek * @param type The type to check for - * @return If an {@link ArgParser.Stateless} for the specified {@code type} would succeed in parsing the next + * @return If an ArgParser.Stateless for the specified {@code type} would succeed in parsing the next * argument * @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left * @see #peek() @@ -180,7 +180,7 @@ public class ArgConsumer implements Cloneable { /** * @param type The type to check for - * @return If an {@link ArgParser.Stateless} for the specified {@code type} would succeed in parsing the next + * @return If an ArgParser.Stateless for the specified {@code type} would succeed in parsing the next * argument * @throws CommandNotEnoughArgumentsException If there is less than one argument left * @see #peek() @@ -286,7 +286,6 @@ public class ArgConsumer implements Cloneable { * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed * @see ArgParser - * @see ArgParser.Stateless * @see #peekAs(Class) * @see #peekAsOrDefault(Class, Object, int) * @see #peekAsOrNull(Class, int) @@ -307,7 +306,6 @@ public class ArgConsumer implements Cloneable { * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed * @see ArgParser - * @see ArgParser.Stateless * @see #peekAs(Class, int) * @see #peekAsOrDefault(Class, Object) * @see #peekAsOrNull(Class) @@ -329,7 +327,6 @@ public class ArgConsumer implements Cloneable { * @param index The index to peek * @return An instance of the specified type, or {@code def} if it couldn't be parsed * @see ArgParser - * @see ArgParser.Stateless * @see #peekAsOrDefault(Class, Object) * @see #peekAs(Class, int) * @see #peekAsOrNull(Class, int) @@ -353,7 +350,6 @@ public class ArgConsumer implements Cloneable { * @param def The value to return if the argument can't be parsed * @return An instance of the specified type, or {@code def} if it couldn't be parsed * @see ArgParser - * @see ArgParser.Stateless * @see #peekAsOrDefault(Class, Object, int) * @see #peekAs(Class) * @see #peekAsOrNull(Class) @@ -374,7 +370,6 @@ public class ArgConsumer implements Cloneable { * @param index The index to peek * @return An instance of the specified type, or {@code null} if it couldn't be parsed * @see ArgParser - * @see ArgParser.Stateless * @see #peekAsOrNull(Class) * @see #peekAs(Class, int) * @see #peekAsOrDefault(Class, Object, int) @@ -393,7 +388,6 @@ public class ArgConsumer implements Cloneable { * @param type The type to peek as * @return An instance of the specified type, or {@code null} if it couldn't be parsed * @see ArgParser - * @see ArgParser.Stateless * @see #peekAsOrNull(Class, int) * @see #peekAs(Class) * @see #peekAsOrDefault(Class, Object) @@ -642,7 +636,6 @@ public class ArgConsumer implements Cloneable { * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed * @see ArgParser - * @see ArgParser.Stateless * @see #get() * @see #getAsOrDefault(Class, Object) * @see #getAsOrNull(Class) @@ -665,7 +658,6 @@ public class ArgConsumer implements Cloneable { * @param def The default value * @return An instance of the specified type, or {@code def} if it couldn't be parsed * @see ArgParser - * @see ArgParser.Stateless * @see #get() * @see #getAs(Class) * @see #getAsOrNull(Class) @@ -693,7 +685,6 @@ public class ArgConsumer implements Cloneable { * @param type The type to peek as * @return An instance of the specified type, or {@code null} if it couldn't be parsed * @see ArgParser - * @see ArgParser.Stateless * @see #get() * @see #getAs(Class) * @see #getAsOrDefault(Class, Object) From 6cc29712e2817a42d290c52750ce69bdfc450979 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 17:53:29 -0700 Subject: [PATCH 647/682] fix mine ordering --- src/main/java/baritone/utils/command/defaults/MineCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index d9328984..c9602a90 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -46,8 +46,8 @@ public class MineCommand extends Command { boms.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); } WorldScanner.INSTANCE.repack(ctx); - baritone.getMineProcess().mine(quantity, boms.toArray(new BlockOptionalMeta[0])); logDirect(String.format("Mining %s", boms.toString())); + baritone.getMineProcess().mine(quantity, boms.toArray(new BlockOptionalMeta[0])); } @Override From 0a2e3f98f91fd32714f97e1fab87a6ef176d5a6b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 19 Sep 2019 18:23:05 -0700 Subject: [PATCH 648/682] freecam meme --- .../java/baritone/utils/command/defaults/SelCommand.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index dfa8e957..7bd0fa2c 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -41,11 +41,12 @@ import baritone.utils.IRenderer; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import java.awt.*; -import java.util.List; import java.util.*; +import java.util.List; import java.util.function.Function; import java.util.stream.Stream; @@ -83,7 +84,7 @@ public class SelCommand extends Command { if (action == Action.POS2 && pos1 == null) { throw new CommandInvalidStateException("Set pos1 first before using pos2"); } - BetterBlockPos playerPos = ctx.playerFeet(); + BetterBlockPos playerPos = mc.getRenderViewEntity() != null ? BetterBlockPos.from(new BlockPos(mc.getRenderViewEntity())) : ctx.playerFeet(); BetterBlockPos pos = args.has() ? args.getDatatypePost(RelativeBlockPos.class, playerPos) : playerPos; args.requireMax(0); if (action == Action.POS1) { From a0f412f25524dd1b8be03d943e0a5484830e3690 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 19 Sep 2019 21:24:23 -0500 Subject: [PATCH 649/682] Some ArgParser cleanups --- .../utils/command/argparser/ArgParser.java | 29 ++++++++++------ .../command/argparser/ArgParserManager.java | 34 +++++++++---------- .../command/argparser/DefaultArgParsers.java | 10 +++--- .../utils/command/argparser/IArgParser.java | 4 +-- .../api/utils/command/registry/Registry.java | 1 - 5 files changed, 42 insertions(+), 36 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParser.java b/src/api/java/baritone/api/utils/command/argparser/ArgParser.java index af0083b7..6fcd5468 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParser.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParser.java @@ -19,29 +19,36 @@ package baritone.api.utils.command.argparser; public abstract class ArgParser implements IArgParser { - private final Class klass; + private final Class target; - protected ArgParser(Class klass) { - this.klass = klass; + private ArgParser(Class target) { + this.target = target; } @Override - public Class getKlass() { - return klass; + public Class getTarget() { + return target; + } + + public static abstract class Stateless extends ArgParser implements IArgParser.Stateless { + + public Stateless(Class target) { + super(target); + } } public static abstract class Stated extends ArgParser implements IArgParser.Stated { - private final Class stateKlass; + private final Class stateType; - protected Stated(Class klass, Class stateKlass) { - super(klass); - this.stateKlass = stateKlass; + protected Stated(Class target, Class stateType) { + super(target); + this.stateType = stateType; } @Override - public Class getStateKlass() { - return stateKlass; + public Class getStateType() { + return stateType; } } } diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index 0f7de303..5fc2c45a 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -31,30 +31,30 @@ public class ArgParserManager { } /** - * @param klass The class to search for. + * @param type The type trying to be parsed * @return A parser that can parse arguments into this class, if found. */ - public static ArgParser.Stateless getParserStateless(Class klass) { + public static ArgParser.Stateless getParserStateless(Class type) { //noinspection unchecked return REGISTRY.descendingStream() .filter(ArgParser.Stateless.class::isInstance) .map(ArgParser.Stateless.class::cast) - .filter(parser -> parser.getKlass().isAssignableFrom(klass)) + .filter(parser -> parser.getTarget().isAssignableFrom(type)) .findFirst() .orElse(null); } /** - * @param klass The class to search for. + * @param type The type trying to be parsed * @return A parser that can parse arguments into this class, if found. */ - public static ArgParser.Stated getParserStated(Class klass, Class stateKlass) { + public static ArgParser.Stated getParserStated(Class type, Class stateKlass) { //noinspection unchecked return REGISTRY.descendingStream() .filter(ArgParser.Stated.class::isInstance) .map(ArgParser.Stated.class::cast) - .filter(parser -> parser.getKlass().isAssignableFrom(klass)) - .filter(parser -> parser.getStateKlass().isAssignableFrom(stateKlass)) + .filter(parser -> parser.getTarget().isAssignableFrom(type)) + .filter(parser -> parser.getStateType().isAssignableFrom(stateKlass)) .map(ArgParser.Stated.class::cast) .findFirst() .orElse(null); @@ -63,28 +63,28 @@ public class ArgParserManager { /** * Attempt to parse the specified argument with a stateless {@link ArgParser} that outputs the specified class. * - * @param klass The class to parse the argument into. + * @param type The type to try and parse the argument into. * @param arg The argument to parse. * @return An instance of the specified class. * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed */ - public static T parseStateless(Class klass, CommandArgument arg) { - ArgParser.Stateless parser = getParserStateless(klass); + public static T parseStateless(Class type, CommandArgument arg) { + ArgParser.Stateless parser = getParserStateless(type); if (parser == null) { - throw new CommandNoParserForTypeException(klass); + throw new CommandNoParserForTypeException(type); } try { return parser.parseArg(arg); } catch (RuntimeException exc) { - throw new CommandInvalidTypeException(arg, klass.getSimpleName()); + throw new CommandInvalidTypeException(arg, type.getSimpleName()); } } /** * Attempt to parse the specified argument with a stated {@link ArgParser} that outputs the specified class. * - * @param klass The class to parse the argument into. + * @param type The type to try and parse the argument into. * @param arg The argument to parse. * @param state The state to pass to the {@link ArgParser.Stated}. * @return An instance of the specified class. @@ -92,15 +92,15 @@ public class ArgParserManager { * @throws CommandInvalidTypeException If the parsing failed * @see ArgParser.Stated */ - public static T parseStated(Class klass, Class stateKlass, CommandArgument arg, S state) { - ArgParser.Stated parser = getParserStated(klass, stateKlass); + public static T parseStated(Class type, Class stateKlass, CommandArgument arg, S state) { + ArgParser.Stated parser = getParserStated(type, stateKlass); if (parser == null) { - throw new CommandNoParserForTypeException(klass); + throw new CommandNoParserForTypeException(type); } try { return parser.parseArg(arg, state); } catch (RuntimeException exc) { - throw new CommandInvalidTypeException(arg, klass.getSimpleName()); + throw new CommandInvalidTypeException(arg, type.getSimpleName()); } } } diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index 6e7e70bc..35110999 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -25,7 +25,7 @@ import java.util.Locale; public class DefaultArgParsers { - public static class IntArgumentParser extends ArgParser implements IArgParser.Stateless { + public static class IntArgumentParser extends ArgParser.Stateless { public static final IntArgumentParser INSTANCE = new IntArgumentParser(); @@ -39,7 +39,7 @@ public class DefaultArgParsers { } } - public static class LongArgumentParser extends ArgParser implements IArgParser.Stateless { + public static class LongArgumentParser extends ArgParser.Stateless { public static final LongArgumentParser INSTANCE = new LongArgumentParser(); @@ -53,7 +53,7 @@ public class DefaultArgParsers { } } - public static class FloatArgumentParser extends ArgParser implements IArgParser.Stateless { + public static class FloatArgumentParser extends ArgParser.Stateless { public static final FloatArgumentParser INSTANCE = new FloatArgumentParser(); @@ -71,7 +71,7 @@ public class DefaultArgParsers { } } - public static class DoubleArgumentParser extends ArgParser implements IArgParser.Stateless { + public static class DoubleArgumentParser extends ArgParser.Stateless { public static final DoubleArgumentParser INSTANCE = new DoubleArgumentParser(); @@ -89,7 +89,7 @@ public class DefaultArgParsers { } } - public static class BooleanArgumentParser extends ArgParser implements IArgParser.Stateless { + public static class BooleanArgumentParser extends ArgParser.Stateless { public static final BooleanArgumentParser INSTANCE = new BooleanArgumentParser(); public static final List TRUTHY_VALUES = Arrays.asList("1", "true", "yes", "t", "y", "on", "enable"); diff --git a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java index 47347c8e..568955af 100644 --- a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java +++ b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java @@ -24,7 +24,7 @@ public interface IArgParser { /** * @return the class of this parser. */ - Class getKlass(); + Class getTarget(); /** * A stateless argument parser is just that. It takes a {@link CommandArgument} and outputs its type. @@ -50,7 +50,7 @@ public interface IArgParser { */ interface Stated extends IArgParser { - Class getStateKlass(); + Class getStateType(); /** * @param arg The argument to parse. diff --git a/src/api/java/baritone/api/utils/command/registry/Registry.java b/src/api/java/baritone/api/utils/command/registry/Registry.java index e3349874..bac50dcf 100644 --- a/src/api/java/baritone/api/utils/command/registry/Registry.java +++ b/src/api/java/baritone/api/utils/command/registry/Registry.java @@ -31,7 +31,6 @@ import java.util.stream.StreamSupport; * @param The entry type that will be stored in this registry. This can be anything, really - preferably anything * that works as a HashMap key, as that's what's used to keep track of which entries are registered or not. */ -@SuppressWarnings({"unused", "UnusedReturnValue"}) public class Registry { /** From 8b4ac3893ee20e047d63c86a6c734e32d717161b Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Thu, 19 Sep 2019 21:40:55 -0700 Subject: [PATCH 650/682] Tweaks and \n fix --- src/api/java/baritone/api/utils/Helper.java | 2 +- src/api/java/baritone/api/utils/ISchematic.java | 2 +- .../api/utils/command/BaritoneChatControl.java | 12 ++++++++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java index 87884cd2..5f77384b 100755 --- a/src/api/java/baritone/api/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -87,7 +87,7 @@ public interface Helper { * @param color The color to print that message in */ default void logDirect(String message, TextFormatting color) { - Arrays.stream(message.split("\\n")).forEach(line -> { + Arrays.stream(message.split("\n")).forEach(line -> { ITextComponent component = new TextComponentString(line.replace("\t", " ")); component.getStyle().setColor(color); logDirect(component); diff --git a/src/api/java/baritone/api/utils/ISchematic.java b/src/api/java/baritone/api/utils/ISchematic.java index b2dfc308..d0b9ddbe 100644 --- a/src/api/java/baritone/api/utils/ISchematic.java +++ b/src/api/java/baritone/api/utils/ISchematic.java @@ -23,7 +23,7 @@ import net.minecraft.util.EnumFacing; import java.util.List; /** - * Basic representation of a schematic. Provides the dimensions and the desired statefor a given position relative to + * Basic representation of a schematic. Provides the dimensions and the desired state for a given position relative to * the origin. * * @author leijurv diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index 23bbd4a7..b5e64930 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -54,6 +54,18 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { public final IBaritone baritone; public final IPlayerContext ctx; public final Settings settings = BaritoneAPI.getSettings(); + + /** + * In certain cases chat components need to execute commands for you. For example, the paginator automatically runs + * commands when you click the forward and back arrows to show you the previous/next page. + *

+ * If the prefix is changed in the meantime, then the command will go to chat. That's no good. So here's a permanent + * prefix that forces a command to run, regardless of the current prefix, chat/prefix control being enabled, etc. + *

+ * If used right (by both developers and users), it should be impossible to expose a command accidentally to the + * server. As a rule of thumb, if you have a clickable chat component, always use this prefix. If you're suggesting + * a command (a component that puts text into your text box, or something else), use {@link Settings#prefix}. + */ public static String FORCE_COMMAND_PREFIX = String.format("<<%s>>", UUID.randomUUID().toString()); public BaritoneChatControl(IBaritone baritone) { From eaa426dd6626946aaec37ce135a702df1ed82de6 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 20 Sep 2019 09:51:57 -0500 Subject: [PATCH 651/682] Fix poor usage of Cloneable Because super.clone() isn't being called, the idea of "Cloneable" isn't upheld. --- .../helpers/arguments/ArgConsumer.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index 219e3645..f0d5139f 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -54,7 +54,7 @@ import java.util.stream.Stream; * handlers can do their job and log the error to chat. * */ -public class ArgConsumer implements Cloneable { +public class ArgConsumer { /** * The list of arguments in this ArgConsumer @@ -410,7 +410,7 @@ public class ArgConsumer implements Cloneable { * @see IDatatype */ public T peekDatatype(Class datatype) { - return clone().getDatatype(datatype); + return copy().getDatatype(datatype); } /** @@ -427,7 +427,7 @@ public class ArgConsumer implements Cloneable { * @see IDatatype */ public T peekDatatypeOrNull(Class datatype) { - return clone().getDatatypeOrNull(datatype); + return copy().getDatatypeOrNull(datatype); } /** @@ -445,7 +445,7 @@ public class ArgConsumer implements Cloneable { * @see IDatatypePost */ public > T peekDatatypePost(Class datatype, O original) { - return clone().getDatatypePost(datatype, original); + return copy().getDatatypePost(datatype, original); } /** @@ -464,7 +464,7 @@ public class ArgConsumer implements Cloneable { * @see IDatatypePost */ public > T peekDatatypePostOrDefault(Class datatype, O original, T def) { - return clone().getDatatypePostOrDefault(datatype, original, def); + return copy().getDatatypePostOrDefault(datatype, original, def); } /** @@ -500,7 +500,7 @@ public class ArgConsumer implements Cloneable { * @see IDatatypeFor */ public > T peekDatatypeFor(Class datatype) { - return clone().peekDatatypeFor(datatype); + return copy().peekDatatypeFor(datatype); } /** @@ -519,7 +519,7 @@ public class ArgConsumer implements Cloneable { * @see IDatatypeFor */ public > T peekDatatypeForOrDefault(Class datatype, T def) { - return clone().peekDatatypeForOrDefault(datatype, def); + return copy().peekDatatypeForOrDefault(datatype, def); } /** @@ -975,12 +975,10 @@ public class ArgConsumer implements Cloneable { } /** - * @return A clone of this {@link ArgConsumer}. It has the same arguments (both consumed and not), but does not + * @return A copy of this {@link ArgConsumer}. It has the same arguments (both consumed and not), but does not * affect or mutate this instance. Useful for the various {@code peek} functions */ - @SuppressWarnings("MethodDoesntCallSuperMethod") - @Override - public ArgConsumer clone() { + public ArgConsumer copy() { return new ArgConsumer(args, consumed); } From b7eaae88a8ac4d2cdca301f9900b8b582c8da659 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 20 Sep 2019 18:32:43 -0500 Subject: [PATCH 652/682] Checked Command Exceptions --- .../utils/command/BaritoneChatControl.java | 53 ++++++----- .../baritone/api/utils/command/Command.java | 7 +- .../command/argparser/ArgParserManager.java | 13 +-- .../command/argument/CommandArgument.java | 10 +- .../utils/command/datatypes/BlockById.java | 6 +- .../command/datatypes/EntityClassById.java | 5 +- .../datatypes/ForBlockOptionalMeta.java | 3 +- .../command/datatypes/ForEnumFacing.java | 6 +- .../utils/command/datatypes/ForWaypoints.java | 6 +- .../utils/command/datatypes/IDatatype.java | 3 +- .../command/datatypes/PlayerByUsername.java | 5 +- .../command/datatypes/RelativeBlockPos.java | 7 +- .../command/datatypes/RelativeCoordinate.java | 6 +- .../utils/command/datatypes/RelativeFile.java | 11 ++- .../utils/command/datatypes/RelativeGoal.java | 3 +- .../command/datatypes/RelativeGoalBlock.java | 4 +- .../command/datatypes/RelativeGoalXZ.java | 3 +- .../command/datatypes/RelativeGoalYLevel.java | 3 +- .../CommandErrorMessageException.java | 13 --- .../command/exception/CommandException.java | 15 +-- .../exception/CommandUnhandledException.java | 26 +++--- .../command/exception/ICommandException.java | 55 +++++++++++ .../helpers/arguments/ArgConsumer.java | 93 +++++++++---------- .../command/helpers/pagination/Paginator.java | 27 +++--- .../utils/command/defaults/AxisCommand.java | 3 +- .../command/defaults/BlacklistCommand.java | 3 +- .../utils/command/defaults/BuildCommand.java | 7 +- .../utils/command/defaults/CancelCommand.java | 3 +- .../utils/command/defaults/ChestsCommand.java | 3 +- .../command/defaults/ClearareaCommand.java | 5 +- .../utils/command/defaults/ClickCommand.java | 3 +- .../utils/command/defaults/ComeCommand.java | 3 +- .../utils/command/defaults/EmptyCommand.java | 58 ------------ .../command/defaults/ExploreCommand.java | 7 +- .../defaults/ExploreFilterCommand.java | 7 +- .../utils/command/defaults/FarmCommand.java | 3 +- .../utils/command/defaults/FindCommand.java | 5 +- .../utils/command/defaults/FollowCommand.java | 7 +- .../command/defaults/ForceCancelCommand.java | 3 +- .../utils/command/defaults/GcCommand.java | 3 +- .../utils/command/defaults/GoalCommand.java | 7 +- .../utils/command/defaults/HelpCommand.java | 7 +- .../utils/command/defaults/InvertCommand.java | 3 +- .../utils/command/defaults/MineCommand.java | 5 +- .../utils/command/defaults/PathCommand.java | 9 +- .../command/defaults/PauseResumeCommands.java | 7 +- .../utils/command/defaults/ProcCommand.java | 3 +- .../command/defaults/ReloadAllCommand.java | 3 +- .../utils/command/defaults/RenderCommand.java | 3 +- .../utils/command/defaults/RepackCommand.java | 3 +- .../command/defaults/SaveAllCommand.java | 3 +- .../command/defaults/SchematicaCommand.java | 3 +- .../utils/command/defaults/SelCommand.java | 7 +- .../utils/command/defaults/SetCommand.java | 17 ++-- .../command/defaults/ThisWayCommand.java | 3 +- .../utils/command/defaults/TunnelCommand.java | 3 +- .../command/defaults/VersionCommand.java | 3 +- .../command/defaults/WaypointsCommand.java | 17 ++-- 58 files changed, 320 insertions(+), 292 deletions(-) create mode 100644 src/api/java/baritone/api/utils/command/exception/ICommandException.java delete mode 100644 src/main/java/baritone/utils/command/defaults/EmptyCommand.java diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index 7c3de5ad..7724e1bf 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -28,6 +28,7 @@ import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.api.utils.SettingsUtil; import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.exception.CommandNotFoundException; import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -124,7 +125,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { String command = pair.first(); String rest = msg.substring(pair.first().length()); ArgConsumer argc = new ArgConsumer(pair.second()); - if (!argc.has()) { + if (!argc.hasAny()) { Settings.Setting setting = settings.byLowerName.get(command.toLowerCase(Locale.US)); if (setting != null) { logRanCommand(command, rest); @@ -142,7 +143,9 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } if (setting.getName().equalsIgnoreCase(pair.first())) { logRanCommand(command, rest); - CommandManager.execute(String.format("set %s %s", setting.getName(), argc.getString())); + try { + CommandManager.execute(String.format("set %s %s", setting.getName(), argc.getString())); + } catch (CommandNotEnoughArgumentsException ignored) {} // The operation is safe return true; } } @@ -176,31 +179,35 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } public Stream tabComplete(String msg) { - List args = CommandArgument.from(msg, true); - ArgConsumer argc = new ArgConsumer(args); - if (argc.hasAtMost(2)) { - if (argc.hasExactly(1)) { - return new TabCompleteHelper() - .addCommands() - .addSettings() - .filterPrefix(argc.getString()) - .stream(); - } - Settings.Setting setting = settings.byLowerName.get(argc.getString().toLowerCase(Locale.US)); - if (setting != null) { - if (setting.getValueClass() == Boolean.class) { - TabCompleteHelper helper = new TabCompleteHelper(); - if ((Boolean) setting.value) { - helper.append(Stream.of("true", "false")); + try { + List args = CommandArgument.from(msg, true); + ArgConsumer argc = new ArgConsumer(args); + if (argc.hasAtMost(2)) { + if (argc.hasExactly(1)) { + return new TabCompleteHelper() + .addCommands() + .addSettings() + .filterPrefix(argc.getString()) + .stream(); + } + Settings.Setting setting = settings.byLowerName.get(argc.getString().toLowerCase(Locale.US)); + if (setting != null) { + if (setting.getValueClass() == Boolean.class) { + TabCompleteHelper helper = new TabCompleteHelper(); + if ((Boolean) setting.value) { + helper.append(Stream.of("true", "false")); + } else { + helper.append(Stream.of("false", "true")); + } + return helper.filterPrefix(argc.getString()).stream(); } else { - helper.append(Stream.of("false", "true")); + return Stream.of(SettingsUtil.settingValueToString(setting)); } - return helper.filterPrefix(argc.getString()).stream(); - } else { - return Stream.of(SettingsUtil.settingValueToString(setting)); } } + return CommandManager.tabComplete(msg); + } catch (CommandNotEnoughArgumentsException ignored) { // Shouldn't happen, the operation is safe + return Stream.empty(); } - return CommandManager.tabComplete(msg); } } diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index 6d415865..1d198c9a 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -21,6 +21,7 @@ import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -61,7 +62,7 @@ public abstract class Command implements Helper { * * @param execution The command execution to execute this command with */ - public void execute(CommandExecution execution) { + public void execute(CommandExecution execution) throws CommandException { executed(execution.label, execution.args, execution.settings); } @@ -82,13 +83,13 @@ public abstract class Command implements Helper { /** * Called when this command is executed. */ - protected abstract void executed(String label, ArgConsumer args, Settings settings); + protected abstract void executed(String label, ArgConsumer args, Settings settings) throws CommandException; /** * Called when the command needs to tab complete. Return a Stream representing the entries to put in the completions * list. */ - protected abstract Stream tabCompleted(String label, ArgConsumer args, Settings settings); + protected abstract Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException; /** * @return A single-line string containing a short description of this command's purpose. diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index 5fc2c45a..447e8f1b 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -20,6 +20,7 @@ package baritone.api.utils.command.argparser; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.exception.CommandNoParserForTypeException; +import baritone.api.utils.command.exception.CommandUnhandledException; import baritone.api.utils.command.registry.Registry; public class ArgParserManager { @@ -66,13 +67,13 @@ public class ArgParserManager { * @param type The type to try and parse the argument into. * @param arg The argument to parse. * @return An instance of the specified class. - * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed */ - public static T parseStateless(Class type, CommandArgument arg) { + public static T parseStateless(Class type, CommandArgument arg) throws CommandInvalidTypeException { ArgParser.Stateless parser = getParserStateless(type); if (parser == null) { - throw new CommandNoParserForTypeException(type); + // TODO: Fix this scuff lol + throw new CommandUnhandledException(new CommandNoParserForTypeException(type)); } try { return parser.parseArg(arg); @@ -88,14 +89,14 @@ public class ArgParserManager { * @param arg The argument to parse. * @param state The state to pass to the {@link ArgParser.Stated}. * @return An instance of the specified class. - * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed * @see ArgParser.Stated */ - public static T parseStated(Class type, Class stateKlass, CommandArgument arg, S state) { + public static T parseStated(Class type, Class stateKlass, CommandArgument arg, S state) throws CommandInvalidTypeException { ArgParser.Stated parser = getParserStated(type, stateKlass); if (parser == null) { - throw new CommandNoParserForTypeException(type); + // TODO: Fix this scuff lol + throw new CommandUnhandledException(new CommandNoParserForTypeException(type)); } try { return parser.parseArg(arg, state); diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index 1928c65e..2914f707 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -66,7 +66,7 @@ public class CommandArgument { * @see ArgConsumer#getEnum(Class) * @see ArgConsumer#getEnumOrNull(Class) */ - public > E getEnum(Class enumClass) { + public > E getEnum(Class enumClass) throws CommandInvalidTypeException { return Arrays.stream(enumClass.getEnumConstants()) .filter(e -> e.name().equalsIgnoreCase(value)) .findFirst() @@ -78,10 +78,9 @@ public class CommandArgument { * * @param type The class to parse this argument into * @return An instance of the specified type - * @throws CommandNoParserForTypeException If no parser exists for that type - * @throws CommandInvalidTypeException If the parsing failed + * @throws CommandInvalidTypeException If the parsing failed */ - public T getAs(Class type) { + public T getAs(Class type) throws CommandInvalidTypeException { return ArgParserManager.parseStateless(type, this); } @@ -105,11 +104,10 @@ public class CommandArgument { * * @param type The class to parse this argument into * @return An instance of the specified type - * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed */ @SuppressWarnings("UnusedReturnValue") - public T getAs(Class type, Class stateType, S state) { + public T getAs(Class type, Class stateType, S state) throws CommandInvalidTypeException { return ArgParserManager.parseStated(type, stateType, this, state); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java index e2cf319b..4733c67d 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java @@ -17,6 +17,8 @@ package baritone.api.utils.command.datatypes; +import baritone.api.utils.command.exception.CommandException; +import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.block.Block; @@ -33,7 +35,7 @@ public class BlockById implements IDatatypeFor { block = null; } - public BlockById(ArgConsumer consumer) { + public BlockById(ArgConsumer consumer) throws CommandNotEnoughArgumentsException { ResourceLocation id = new ResourceLocation(consumer.getString()); if ((block = Block.REGISTRY.getObject(id)) == Blocks.AIR) { throw new IllegalArgumentException("no block found by that id"); @@ -46,7 +48,7 @@ public class BlockById implements IDatatypeFor { } @Override - public Stream tabComplete(ArgConsumer consumer) { + public Stream tabComplete(ArgConsumer consumer) throws CommandException { return new TabCompleteHelper() .append( Block.REGISTRY.getKeys() diff --git a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java index 45546119..62a80ba7 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java @@ -17,6 +17,7 @@ package baritone.api.utils.command.datatypes; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.entity.Entity; @@ -33,7 +34,7 @@ public class EntityClassById implements IDatatypeFor> { entity = null; } - public EntityClassById(ArgConsumer consumer) { + public EntityClassById(ArgConsumer consumer) throws CommandException { ResourceLocation id = new ResourceLocation(consumer.getString()); if ((entity = EntityList.REGISTRY.getObject(id)) == null) { throw new IllegalArgumentException("no entity found by that id"); @@ -46,7 +47,7 @@ public class EntityClassById implements IDatatypeFor> { } @Override - public Stream tabComplete(ArgConsumer consumer) { + public Stream tabComplete(ArgConsumer consumer) throws CommandException { return new TabCompleteHelper() .append( EntityList.getEntityNameList() diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java b/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java index cffdb54e..85f2ca61 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.BlockOptionalMeta; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; @@ -30,7 +31,7 @@ public class ForBlockOptionalMeta implements IDatatypeFor { selector = null; } - public ForBlockOptionalMeta(ArgConsumer consumer) { + public ForBlockOptionalMeta(ArgConsumer consumer) throws CommandException { selector = new BlockOptionalMeta(consumer.getString()); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java index 8bee4d41..b8ee355a 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java @@ -17,6 +17,8 @@ package baritone.api.utils.command.datatypes; +import baritone.api.utils.command.exception.CommandException; +import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.util.EnumFacing; @@ -33,7 +35,7 @@ public class ForEnumFacing implements IDatatypeFor { facing = null; } - public ForEnumFacing(ArgConsumer consumer) { + public ForEnumFacing(ArgConsumer consumer) throws CommandNotEnoughArgumentsException { facing = EnumFacing.valueOf(consumer.getString().toUpperCase(Locale.US)); } @@ -43,7 +45,7 @@ public class ForEnumFacing implements IDatatypeFor { } @Override - public Stream tabComplete(ArgConsumer consumer) { + public Stream tabComplete(ArgConsumer consumer) throws CommandException { return new TabCompleteHelper() .append( Arrays.stream(EnumFacing.values()) diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java index 6dd302f2..04717952 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -20,6 +20,8 @@ package baritone.api.utils.command.datatypes; import baritone.api.BaritoneAPI; import baritone.api.cache.IWaypoint; import baritone.api.cache.IWaypointCollection; +import baritone.api.utils.command.exception.CommandException; +import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; @@ -40,7 +42,7 @@ public class ForWaypoints implements IDatatypeFor { waypoints = tag == null ? getWaypointsByName(arg) : getWaypointsByTag(tag); } - public ForWaypoints(ArgConsumer consumer) { + public ForWaypoints(ArgConsumer consumer) throws CommandNotEnoughArgumentsException { this(consumer.getString()); } @@ -50,7 +52,7 @@ public class ForWaypoints implements IDatatypeFor { } @Override - public Stream tabComplete(ArgConsumer consumer) { + public Stream tabComplete(ArgConsumer consumer) throws CommandException { return new TabCompleteHelper() .append(getWaypointNames()) .sortAlphabetically() diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java index c79ff495..a3cf07a4 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.argparser.ArgParser; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidArgumentException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -44,5 +45,5 @@ public interface IDatatype { * @return A stream representing the strings that can be tab completed. DO NOT INCLUDE SPACES IN ANY STRINGS. * @see ArgConsumer#tabCompleteDatatype(Class) */ - Stream tabComplete(ArgConsumer consumer); + Stream tabComplete(ArgConsumer consumer) throws CommandException; } diff --git a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java index 5cf25066..0912c74d 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java +++ b/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.BaritoneAPI; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.entity.player.EntityPlayer; @@ -35,7 +36,7 @@ public class PlayerByUsername implements IDatatypeFor { player = null; } - public PlayerByUsername(ArgConsumer consumer) { + public PlayerByUsername(ArgConsumer consumer) throws CommandException { String username = consumer.getString(); player = players .stream() @@ -53,7 +54,7 @@ public class PlayerByUsername implements IDatatypeFor { } @Override - public Stream tabComplete(ArgConsumer consumer) { + public Stream tabComplete(ArgConsumer consumer) throws CommandException { return new TabCompleteHelper() .append( players diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java index 610b8d5f..0f7ffb4f 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; @@ -34,7 +35,7 @@ public class RelativeBlockPos implements IDatatypePost tabComplete(ArgConsumer consumer) { - if (consumer.has() && !consumer.has(4)) { + public Stream tabComplete(ArgConsumer consumer) throws CommandException { + if (consumer.hasAny() && !consumer.has(4)) { while (consumer.has(2)) { if (consumer.peekDatatypeOrNull(RelativeCoordinate.class) == null) { break; diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java index b521881c..7e234711 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java @@ -17,6 +17,8 @@ package baritone.api.utils.command.datatypes; +import baritone.api.utils.command.exception.CommandException; +import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.util.math.MathHelper; @@ -35,7 +37,7 @@ public class RelativeCoordinate implements IDatatypePost { offset = 0; } - public RelativeCoordinate(ArgConsumer consumer) { + public RelativeCoordinate(ArgConsumer consumer) throws CommandNotEnoughArgumentsException { Matcher matcher = PATTERN.matcher(consumer.getString()); if (!matcher.matches()) { throw new IllegalArgumentException("pattern doesn't match"); @@ -57,7 +59,7 @@ public class RelativeCoordinate implements IDatatypePost { } @Override - public Stream tabComplete(ArgConsumer consumer) { + public Stream tabComplete(ArgConsumer consumer) throws CommandException { if (!consumer.has(2) && consumer.getString().matches("^(~|$)")) { return Stream.of("~"); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index c3d5479f..a02f1fc5 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -17,6 +17,8 @@ package baritone.api.utils.command.datatypes; +import baritone.api.utils.command.exception.CommandException; +import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.io.File; @@ -40,7 +42,7 @@ public class RelativeFile implements IDatatypePost { path = null; } - public RelativeFile(ArgConsumer consumer) { + public RelativeFile(ArgConsumer consumer) throws CommandNotEnoughArgumentsException { try { path = FileSystems.getDefault().getPath(consumer.getString()); } catch (InvalidPathException e) { @@ -68,9 +70,12 @@ public class RelativeFile implements IDatatypePost { } } - public static Stream tabComplete(ArgConsumer consumer, File base0) { + public static Stream tabComplete(ArgConsumer consumer, File base0) throws CommandException { // I will not make the caller deal with this, seriously - // Tab complete code is beautiful and I'm not going to bloat it with dumb ass checked exception bullshit + // Tab complete code is beautiful and I'm not going to bloat it with dumb ass checked exception bullshit -LoganDark + + // lol owned -Brady + File base = getCanonicalFileUnchecked(base0); String currentPathStringThing = consumer.getString(); Path currentPath = FileSystems.getDefault().getPath(currentPathStringThing); diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java index d3aad7b9..943c0732 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java @@ -22,6 +22,7 @@ import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalXZ; import baritone.api.pathing.goals.GoalYLevel; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.ArrayList; @@ -36,7 +37,7 @@ public class RelativeGoal implements IDatatypePost { coords = new RelativeCoordinate[0]; } - public RelativeGoal(ArgConsumer consumer) { + public RelativeGoal(ArgConsumer consumer) throws CommandException { List coordsList = new ArrayList<>(); for (int i = 0; i < 3; i++) { if (consumer.peekDatatypeOrNull(RelativeCoordinate.class) != null) { diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java index 2d8f9cda..f368d62e 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java @@ -19,6 +19,8 @@ package baritone.api.utils.command.datatypes; import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.exception.CommandException; +import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; @@ -31,7 +33,7 @@ public class RelativeGoalBlock implements IDatatypePost { coords = new RelativeCoordinate[0]; } - public RelativeGoalXZ(ArgConsumer consumer) { + public RelativeGoalXZ(ArgConsumer consumer) throws CommandException { coords = new RelativeCoordinate[]{ consumer.getDatatype(RelativeCoordinate.class), consumer.getDatatype(RelativeCoordinate.class) diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java index 6b8a1aa0..126565da 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java @@ -19,6 +19,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.pathing.goals.GoalYLevel; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; @@ -31,7 +32,7 @@ public class RelativeGoalYLevel implements IDatatypePost args) { - HELPER.logDirect(getMessage(), TextFormatting.RED); - } } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandException.java b/src/api/java/baritone/api/utils/command/exception/CommandException.java index 1f8af3ca..9fdc3f73 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandException.java @@ -17,22 +17,9 @@ package baritone.api.utils.command.exception; -import baritone.api.utils.command.Command; -import baritone.api.utils.command.argument.CommandArgument; - -import java.util.List; - -public abstract class CommandException extends RuntimeException { +public abstract class CommandException extends Exception implements ICommandException { protected CommandException(String reason) { super(reason); } - - /** - * Called when this exception is thrown, to handle the exception. - * - * @param command The command that threw it. - * @param args The arguments the command was called with. - */ - public abstract void handle(Command command, List args); } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java index b3cf1819..0ff822ad 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -23,15 +23,22 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -public class CommandUnhandledException extends CommandErrorMessageException { +public class CommandUnhandledException extends RuntimeException implements ICommandException { - public static String getStackTrace(Throwable throwable) { + public CommandUnhandledException(Throwable cause) { + super(String.format( + "An unhandled exception has occurred:\n\n%s", + getFriendlierStackTrace(cause) + )); + } + + private static String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); throwable.printStackTrace(new PrintWriter(sw)); return sw.toString(); } - public static String getBaritoneStackTrace(String stackTrace) { + private static String getBaritoneStackTrace(String stackTrace) { List lines = Arrays.stream(stackTrace.split("\n")) .collect(Collectors.toList()); int lastBaritoneLine = 0; @@ -43,11 +50,11 @@ public class CommandUnhandledException extends CommandErrorMessageException { return String.join("\n", lines.subList(0, lastBaritoneLine + 1)); } - public static String getBaritoneStackTrace(Throwable throwable) { + private static String getBaritoneStackTrace(Throwable throwable) { return getBaritoneStackTrace(getStackTrace(throwable)); } - public static String getFriendlierStackTrace(String stackTrace) { + private static String getFriendlierStackTrace(String stackTrace) { List lines = Arrays.asList(stackTrace.split("\n")); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); @@ -64,14 +71,7 @@ public class CommandUnhandledException extends CommandErrorMessageException { return String.join("\n", lines); } - public static String getFriendlierStackTrace(Throwable throwable) { + private static String getFriendlierStackTrace(Throwable throwable) { return getFriendlierStackTrace(getBaritoneStackTrace(throwable)); } - - public CommandUnhandledException(Throwable cause) { - super(String.format( - "An unhandled exception has occurred:\n\n%s", - getFriendlierStackTrace(cause) - )); - } } diff --git a/src/api/java/baritone/api/utils/command/exception/ICommandException.java b/src/api/java/baritone/api/utils/command/exception/ICommandException.java new file mode 100644 index 00000000..379e97b7 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/exception/ICommandException.java @@ -0,0 +1,55 @@ +/* + * 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.command.exception; + +import baritone.api.utils.command.Command; +import baritone.api.utils.command.argument.CommandArgument; +import net.minecraft.util.text.TextFormatting; + +import java.util.List; + +import static baritone.api.utils.Helper.HELPER; + +/** + * The base for a Baritone Command Exception, checked or unchecked. Provides a + * {@link #handle(Command, List)} method that is used to provide useful output + * to the user for diagnosing issues that may have occurred during execution. + *

+ * Anything implementing this interface should be assignable to {@link Exception}. + * + * @author Brady + * @since 9/20/2019 + */ +public interface ICommandException { + + /** + * @see Exception#getMessage() + * @return The exception details + */ + String getMessage(); + + /** + * Called when this exception is thrown, to handle the exception. + * + * @param command The command that threw it. + * @param args The arguments the command was called with. + */ + default void handle(Command command, List args) { + HELPER.logDirect(this.getMessage(), TextFormatting.RED); + } +} diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index f0d5139f..55df9866 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -77,7 +77,7 @@ public class ArgConsumer { /** * @param num The number of arguments to check for * @return {@code true} if there are at least {@code num} arguments left in this {@link ArgConsumer} - * @see #has() + * @see #hasAny() * @see #hasAtMost(int) * @see #hasExactly(int) */ @@ -91,7 +91,7 @@ public class ArgConsumer { * @see #hasAtMostOne() * @see #hasExactlyOne() */ - public boolean has() { + public boolean hasAny() { return has(1); } @@ -108,7 +108,7 @@ public class ArgConsumer { /** * @return {@code true} if there is at most 1 argument left in this {@link ArgConsumer} - * @see #has() + * @see #hasAny() * @see #hasAtMostOne() * @see #hasExactlyOne() */ @@ -128,7 +128,7 @@ public class ArgConsumer { /** * @return {@code true} if there is exactly 1 argument left in this {@link ArgConsumer} - * @see #has() + * @see #hasAny() * @see #hasAtMostOne() */ public boolean hasExactlyOne() { @@ -145,7 +145,7 @@ public class ArgConsumer { * @see #peekAs(Class, int) * @see #get() */ - public CommandArgument peek(int index) { + public CommandArgument peek(int index) throws CommandNotEnoughArgumentsException { requireMin(index + 1); return args.get(index); } @@ -161,7 +161,7 @@ public class ArgConsumer { * @see #peekDatatypePost(Class, Object) * @see #get() */ - public CommandArgument peek() { + public CommandArgument peek() throws CommandNotEnoughArgumentsException { return peek(0); } @@ -174,7 +174,7 @@ public class ArgConsumer { * @see #peek() * @see #getAs(Class) */ - public boolean is(Class type, int index) { + public boolean is(Class type, int index) throws CommandNotEnoughArgumentsException { return peek(index).is(type); } @@ -186,7 +186,7 @@ public class ArgConsumer { * @see #peek() * @see #getAs(Class) */ - public boolean is(Class type) { + public boolean is(Class type) throws CommandNotEnoughArgumentsException { return is(type, 0); } @@ -198,7 +198,7 @@ public class ArgConsumer { * @see #peek() * @see #peekString() */ - public String peekString(int index) { + public String peekString(int index) throws CommandNotEnoughArgumentsException { return peek(index).value; } @@ -208,7 +208,7 @@ public class ArgConsumer { * @see #peekString(int) * @see #getString() */ - public String peekString() { + public String peekString() throws CommandNotEnoughArgumentsException { return peekString(0); } @@ -222,7 +222,7 @@ public class ArgConsumer { * @see #getEnum(Class) * @see CommandArgument#getEnum(Class) */ - public > E peekEnum(Class enumClass, int index) { + public > E peekEnum(Class enumClass, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return peek(index).getEnum(enumClass); } @@ -235,7 +235,7 @@ public class ArgConsumer { * @see #getEnum(Class) * @see CommandArgument#getEnum(Class) */ - public > E peekEnum(Class enumClass) { + public > E peekEnum(Class enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return peekEnum(enumClass, 0); } @@ -248,7 +248,7 @@ public class ArgConsumer { * @see #getEnumOrNull(Class) * @see CommandArgument#getEnum(Class) */ - public > E peekEnumOrNull(Class enumClass, int index) { + public > E peekEnumOrNull(Class enumClass, int index) throws CommandNotEnoughArgumentsException { try { return peekEnum(enumClass, index); } catch (CommandInvalidTypeException e) { @@ -264,12 +264,8 @@ public class ArgConsumer { * @see #getEnumOrNull(Class) * @see CommandArgument#getEnum(Class) */ - public > E peekEnumOrNull(Class enumClass) { - try { - return peekEnumOrNull(enumClass, 0); - } catch (CommandInvalidTypeException e) { - return null; - } + public > E peekEnumOrNull(Class enumClass) throws CommandNotEnoughArgumentsException { + return peekEnumOrNull(enumClass, 0); } /** @@ -283,14 +279,13 @@ public class ArgConsumer { * @param type The type to peek as * @param index The index to peek * @return An instance of the specified type - * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed * @see ArgParser * @see #peekAs(Class) * @see #peekAsOrDefault(Class, Object, int) * @see #peekAsOrNull(Class, int) */ - public T peekAs(Class type, int index) { + public T peekAs(Class type, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return peek(index).getAs(type); } @@ -303,14 +298,13 @@ public class ArgConsumer { * * @param type The type to peek as * @return An instance of the specified type - * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed * @see ArgParser * @see #peekAs(Class, int) * @see #peekAsOrDefault(Class, Object) * @see #peekAsOrNull(Class) */ - public T peekAs(Class type) { + public T peekAs(Class type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return peekAs(type, 0); } @@ -331,7 +325,7 @@ public class ArgConsumer { * @see #peekAs(Class, int) * @see #peekAsOrNull(Class, int) */ - public T peekAsOrDefault(Class type, T def, int index) { + public T peekAsOrDefault(Class type, T def, int index) throws CommandNotEnoughArgumentsException { try { return peekAs(type, index); } catch (CommandInvalidTypeException e) { @@ -354,7 +348,7 @@ public class ArgConsumer { * @see #peekAs(Class) * @see #peekAsOrNull(Class) */ - public T peekAsOrDefault(Class type, T def) { + public T peekAsOrDefault(Class type, T def) throws CommandNotEnoughArgumentsException { return peekAsOrDefault(type, def, 0); } @@ -374,7 +368,7 @@ public class ArgConsumer { * @see #peekAs(Class, int) * @see #peekAsOrDefault(Class, Object, int) */ - public T peekAsOrNull(Class type, int index) { + public T peekAsOrNull(Class type, int index) throws CommandNotEnoughArgumentsException { return peekAsOrDefault(type, null, index); } @@ -392,7 +386,7 @@ public class ArgConsumer { * @see #peekAs(Class) * @see #peekAsOrDefault(Class, Object) */ - public T peekAsOrNull(Class type) { + public T peekAsOrNull(Class type) throws CommandNotEnoughArgumentsException { return peekAsOrNull(type, 0); } @@ -409,7 +403,7 @@ public class ArgConsumer { * @return The datatype instance * @see IDatatype */ - public T peekDatatype(Class datatype) { + public T peekDatatype(Class datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return copy().getDatatype(datatype); } @@ -426,7 +420,7 @@ public class ArgConsumer { * @return The datatype instance, or {@code null} if it throws an exception * @see IDatatype */ - public T peekDatatypeOrNull(Class datatype) { + public T peekDatatypeOrNull(Class datatype) throws CommandNotEnoughArgumentsException { return copy().getDatatypeOrNull(datatype); } @@ -444,7 +438,7 @@ public class ArgConsumer { * @see IDatatype * @see IDatatypePost */ - public > T peekDatatypePost(Class datatype, O original) { + public > T peekDatatypePost(Class datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return copy().getDatatypePost(datatype, original); } @@ -547,7 +541,7 @@ public class ArgConsumer { * @return The next argument * @throws CommandNotEnoughArgumentsException If there's less than one argument left */ - public CommandArgument get() { + public CommandArgument get() throws CommandNotEnoughArgumentsException { requireMin(1); CommandArgument arg = args.removeFirst(); consumed.add(arg); @@ -561,7 +555,7 @@ public class ArgConsumer { * @return The value of the next argument * @throws CommandNotEnoughArgumentsException If there's less than one argument left */ - public String getString() { + public String getString() throws CommandNotEnoughArgumentsException { return get().value; } @@ -578,7 +572,7 @@ public class ArgConsumer { * @see #getEnumOrNull(Class) * @see CommandArgument#getEnum(Class) */ - public > E getEnum(Class enumClass) { + public > E getEnum(Class enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return get().getEnum(enumClass); } @@ -597,7 +591,7 @@ public class ArgConsumer { * @see #peekEnumOrNull(Class) * @see CommandArgument#getEnum(Class) */ - public > E getEnumOrDefault(Class enumClass, E def) { + public > E getEnumOrDefault(Class enumClass, E def) throws CommandNotEnoughArgumentsException { try { peekEnum(enumClass); return getEnum(enumClass); @@ -620,7 +614,7 @@ public class ArgConsumer { * @see #peekEnumOrNull(Class) * @see CommandArgument#getEnum(Class) */ - public > E getEnumOrNull(Class enumClass) { + public > E getEnumOrNull(Class enumClass) throws CommandNotEnoughArgumentsException { return getEnumOrDefault(enumClass, null); } @@ -633,7 +627,6 @@ public class ArgConsumer { * * @param type The type to peek as * @return An instance of the specified type - * @throws CommandNoParserForTypeException If no parser exists for that type * @throws CommandInvalidTypeException If the parsing failed * @see ArgParser * @see #get() @@ -643,7 +636,7 @@ public class ArgConsumer { * @see #peekAsOrDefault(Class, Object, int) * @see #peekAsOrNull(Class, int) */ - public T getAs(Class type) { + public T getAs(Class type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return get().getAs(type); } @@ -665,7 +658,7 @@ public class ArgConsumer { * @see #peekAsOrDefault(Class, Object, int) * @see #peekAsOrNull(Class, int) */ - public T getAsOrDefault(Class type, T def) { + public T getAsOrDefault(Class type, T def) throws CommandNotEnoughArgumentsException { try { T val = peek().getAs(type); get(); @@ -692,7 +685,7 @@ public class ArgConsumer { * @see #peekAsOrDefault(Class, Object, int) * @see #peekAsOrNull(Class, int) */ - public T getAsOrNull(Class type) { + public T getAsOrNull(Class type) throws CommandNotEnoughArgumentsException { return getAsOrDefault(type, null); } @@ -707,11 +700,11 @@ public class ArgConsumer { * @return The datatype instance * @see IDatatype */ - public T getDatatype(Class datatype) { + public T getDatatype(Class datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { try { return datatype.getConstructor(ArgConsumer.class).newInstance(this); } catch (InvocationTargetException e) { - throw new CommandInvalidTypeException(has() ? peek() : consumed(), datatype.getSimpleName()); + throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getSimpleName()); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException e) { throw new CommandUnhandledException(e); } @@ -730,7 +723,7 @@ public class ArgConsumer { * @return The datatype instance, or {@code null} if it throws an exception * @see IDatatype */ - public T getDatatypeOrNull(Class datatype) { + public T getDatatypeOrNull(Class datatype) throws CommandNotEnoughArgumentsException { List argsSnapshot = new ArrayList<>(args); List consumedSnapshot = new ArrayList<>(consumed); try { @@ -756,7 +749,7 @@ public class ArgConsumer { * @see IDatatype * @see IDatatypePost */ - public > T getDatatypePost(Class datatype, O original) { + public > T getDatatypePost(Class datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return getDatatype(datatype).apply(original); } @@ -819,7 +812,7 @@ public class ArgConsumer { * @see IDatatype * @see IDatatypeFor */ - public > T getDatatypeFor(Class datatype) { + public > T getDatatypeFor(Class datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return getDatatype(datatype).get(); } @@ -838,7 +831,7 @@ public class ArgConsumer { * @see IDatatype * @see IDatatypeFor */ - public > T getDatatypeForOrDefault(Class datatype, T def) { + public > T getDatatypeForOrDefault(Class datatype, T def) throws CommandNotEnoughArgumentsException { List argsSnapshot = new ArrayList<>(args); List consumedSnapshot = new ArrayList<>(consumed); try { @@ -866,7 +859,7 @@ public class ArgConsumer { * @see IDatatype * @see IDatatypeFor */ - public > T getDatatypeForOrNull(Class datatype) { + public > T getDatatypeForOrNull(Class datatype) throws CommandNotEnoughArgumentsException { return getDatatypeForOrDefault(datatype, null); } @@ -915,7 +908,7 @@ public class ArgConsumer { * @see #requireMax(int) * @see #requireExactly(int) */ - public void requireMin(int min) { + public void requireMin(int min) throws CommandNotEnoughArgumentsException { if (args.size() < min) { throw new CommandNotEnoughArgumentsException(min + consumed.size()); } @@ -923,11 +916,11 @@ public class ArgConsumer { /** * @param max The maximum amount of arguments allowed. - * @throws CommandNotEnoughArgumentsException If there are more than {@code max} arguments left. + * @throws CommandTooManyArgumentsException If there are more than {@code max} arguments left. * @see #requireMin(int) * @see #requireExactly(int) */ - public void requireMax(int max) { + public void requireMax(int max) throws CommandTooManyArgumentsException { if (args.size() > max) { throw new CommandTooManyArgumentsException(max + consumed.size()); } @@ -940,7 +933,7 @@ public class ArgConsumer { * @see #requireMin(int) * @see #requireMax(int) */ - public void requireExactly(int args) { + public void requireExactly(int args) throws CommandException { requireMin(args); requireMax(args); } diff --git a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java index c143d507..da5ac436 100644 --- a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java +++ b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.helpers.pagination; import baritone.api.utils.Helper; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.util.text.ITextComponent; @@ -114,10 +115,10 @@ public class Paginator implements Helper { display(transform, null); } - public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform, String commandPrefix) { + public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform, String commandPrefix) throws CommandException { int page = 1; consumer.requireMax(1); - if (consumer.has()) { + if (consumer.hasAny()) { page = consumer.getAs(Integer.class); if (!pagi.validPage(page)) { throw new CommandInvalidTypeException( @@ -137,47 +138,47 @@ public class Paginator implements Helper { pagi.display(transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, List elems, Runnable pre, Function transform, String commandPrefix) { + public static void paginate(ArgConsumer consumer, List elems, Runnable pre, Function transform, String commandPrefix) throws CommandException { paginate(consumer, new Paginator<>(elems), pre, transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, T[] elems, Runnable pre, Function transform, String commandPrefix) { + public static void paginate(ArgConsumer consumer, T[] elems, Runnable pre, Function transform, String commandPrefix) throws CommandException { paginate(consumer, Arrays.asList(elems), pre, transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform, String commandPrefix) { + public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform, String commandPrefix) throws CommandException { paginate(consumer, pagi, null, transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, List elems, Function transform, String commandPrefix) { + public static void paginate(ArgConsumer consumer, List elems, Function transform, String commandPrefix) throws CommandException { paginate(consumer, new Paginator<>(elems), null, transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, T[] elems, Function transform, String commandPrefix) { + public static void paginate(ArgConsumer consumer, T[] elems, Function transform, String commandPrefix) throws CommandException { paginate(consumer, Arrays.asList(elems), null, transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform) { + public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform) throws CommandException { paginate(consumer, pagi, pre, transform, null); } - public static void paginate(ArgConsumer consumer, List elems, Runnable pre, Function transform) { + public static void paginate(ArgConsumer consumer, List elems, Runnable pre, Function transform) throws CommandException { paginate(consumer, new Paginator<>(elems), pre, transform, null); } - public static void paginate(ArgConsumer consumer, T[] elems, Runnable pre, Function transform) { + public static void paginate(ArgConsumer consumer, T[] elems, Runnable pre, Function transform) throws CommandException { paginate(consumer, Arrays.asList(elems), pre, transform, null); } - public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform) { + public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform) throws CommandException { paginate(consumer, pagi, null, transform, null); } - public static void paginate(ArgConsumer consumer, List elems, Function transform) { + public static void paginate(ArgConsumer consumer, List elems, Function transform) throws CommandException { paginate(consumer, new Paginator<>(elems), null, transform, null); } - public static void paginate(ArgConsumer consumer, T[] elems, Function transform) { + public static void paginate(ArgConsumer consumer, T[] elems, Function transform) throws CommandException { paginate(consumer, Arrays.asList(elems), null, transform, null); } } diff --git a/src/main/java/baritone/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java index 322fa696..50525f2d 100644 --- a/src/main/java/baritone/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -22,6 +22,7 @@ import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalAxis; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -35,7 +36,7 @@ public class AxisCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); Goal goal = new GoalAxis(); baritone.getCustomGoalProcess().setGoal(goal); diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index b70a9a13..e680e4fa 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -21,6 +21,7 @@ import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.process.IGetToBlockProcess; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -35,7 +36,7 @@ public class BlacklistCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); IGetToBlockProcess proc = baritone.getGetToBlockProcess(); if (!proc.isActive()) { diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index 09cb2437..85f51da1 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -23,6 +23,7 @@ import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeBlockPos; import baritone.api.utils.command.datatypes.RelativeFile; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.client.Minecraft; @@ -42,14 +43,14 @@ public class BuildCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { File file = args.getDatatypePost(RelativeFile.class, schematicsDir).getAbsoluteFile(); if (!file.getName().toLowerCase(Locale.US).endsWith(".schematic")) { file = new File(file.getAbsolutePath() + ".schematic"); } BetterBlockPos origin = ctx.playerFeet(); BetterBlockPos buildOrigin; - if (args.has()) { + if (args.hasAny()) { args.requireMax(3); buildOrigin = args.getDatatype(RelativeBlockPos.class).apply(origin); } else { @@ -64,7 +65,7 @@ public class BuildCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { if (args.hasExactlyOne()) { return RelativeFile.tabComplete(args, schematicsDir); } else if (args.has(2)) { diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index 64b977a3..55c172b8 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -20,6 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -33,7 +34,7 @@ public class CancelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); baritone.getPathingBehavior().cancelEverything(); logDirect("ok canceled"); diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index bde736e9..8e2cee79 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -22,6 +22,7 @@ import baritone.api.Settings; import baritone.api.cache.IRememberedInventory; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.item.ItemStack; @@ -41,7 +42,7 @@ public class ChestsCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); Set> entries = ctx.worldData().getContainerMemory().getRememberedInventories().entrySet(); diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index 17fa2863..99f39307 100644 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -24,6 +24,7 @@ import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeBlockPos; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -38,10 +39,10 @@ public class ClearareaCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { BetterBlockPos pos1 = ctx.playerFeet(); BetterBlockPos pos2; - if (args.has()) { + if (args.hasAny()) { args.requireMax(3); pos2 = args.getDatatype(RelativeBlockPos.class).apply(pos1); } else { diff --git a/src/main/java/baritone/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java index c09fd8b0..49324d88 100644 --- a/src/main/java/baritone/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -20,6 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -33,7 +34,7 @@ public class ClickCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); baritone.openClick(); logDirect("aight dude"); diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index be99cf63..bf02d75d 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -21,6 +21,7 @@ import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.entity.Entity; @@ -37,7 +38,7 @@ public class ComeCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); Entity entity = mc.getRenderViewEntity(); if (entity == null) { diff --git a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java b/src/main/java/baritone/utils/command/defaults/EmptyCommand.java deleted file mode 100644 index c36bd044..00000000 --- a/src/main/java/baritone/utils/command/defaults/EmptyCommand.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.utils.command.defaults; - -import baritone.api.IBaritone; -import baritone.api.Settings; -import baritone.api.utils.command.Command; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Stream; - -public class EmptyCommand extends Command { - - public EmptyCommand(IBaritone baritone) { - super(baritone, Arrays.asList("name1", "name2")); - } - - @Override - protected void executed(String label, ArgConsumer args, Settings settings) { - } - - @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { - return Stream.empty(); - } - - @Override - public String getShortDesc() { - return "Short description"; - } - - @Override - public List getLongDesc() { - return Arrays.asList( - "", - "", - "Usage:", - "> " - ); - } -} diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index 86f975b7..57b95d59 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -22,6 +22,7 @@ import baritone.api.Settings; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeGoalXZ; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -35,13 +36,13 @@ public class ExploreCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { - if (args.has()) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + if (args.hasAny()) { args.requireExactly(2); } else { args.requireMax(0); } - GoalXZ goal = args.has() + GoalXZ goal = args.hasAny() ? args.getDatatypePost(RelativeGoalXZ.class, ctx.playerFeet()) : new GoalXZ(ctx.playerFeet()); baritone.getExploreProcess().explore(goal.getX(), goal.getZ()); diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index cdbc0e8c..338a622c 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -21,6 +21,7 @@ import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeFile; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -39,11 +40,11 @@ public class ExploreFilterCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(2); File file = args.getDatatypePost(RelativeFile.class, mc.gameDir.getAbsoluteFile().getParentFile()); boolean invert = false; - if (args.has()) { + if (args.hasAny()) { if (args.getString().equalsIgnoreCase("invert")) { invert = true; } else { @@ -63,7 +64,7 @@ public class ExploreFilterCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { if (args.hasExactlyOne()) { return RelativeFile.tabComplete(args, RelativeFile.gameDir()); } diff --git a/src/main/java/baritone/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java index 62db521d..af3efa2c 100644 --- a/src/main/java/baritone/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -20,6 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -33,7 +34,7 @@ public class FarmCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); baritone.getFarmProcess().farm(); logDirect("Farming"); diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index 2f36ec01..552985a4 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -22,6 +22,7 @@ import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.BlockById; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.block.Block; @@ -37,9 +38,9 @@ public class FindCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { List toFind = new ArrayList<>(); - while (args.has()) { + while (args.hasAny()) { toFind.add(args.getDatatypeFor(BlockById.class)); } BetterBlockPos origin = ctx.playerFeet(); diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index 8240be2e..46f89d75 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -24,6 +24,7 @@ import baritone.api.utils.command.datatypes.EntityClassById; import baritone.api.utils.command.datatypes.IDatatype; import baritone.api.utils.command.datatypes.IDatatypeFor; import baritone.api.utils.command.datatypes.PlayerByUsername; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.entity.Entity; @@ -43,7 +44,7 @@ public class FollowCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMin(1); FollowGroup group; FollowList list; @@ -55,7 +56,7 @@ public class FollowCommand extends Command { args.requireMin(2); group = null; list = args.getEnum(FollowList.class); - while (args.has()) { + while (args.hasAny()) { //noinspection unchecked Object gotten = args.getDatatypeFor(list.datatype); if (gotten instanceof Class) { @@ -90,7 +91,7 @@ public class FollowCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper() .append(FollowGroup.class) diff --git a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index 6c6c740c..6596749d 100644 --- a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -21,6 +21,7 @@ import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.behavior.IPathingBehavior; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -34,7 +35,7 @@ public class ForceCancelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); IPathingBehavior pathingBehavior = baritone.getPathingBehavior(); pathingBehavior.cancelEverything(); diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index a0acf98f..aa29d667 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -20,6 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -33,7 +34,7 @@ public class GcCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); System.gc(); logDirect("ok called System.gc()"); diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index e3da6330..bd50e33e 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -25,6 +25,7 @@ import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeCoordinate; import baritone.api.utils.command.datatypes.RelativeGoal; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; @@ -39,9 +40,9 @@ public class GoalCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { ICustomGoalProcess goalProcess = baritone.getCustomGoalProcess(); - if (args.has() && Arrays.asList("reset", "clear", "none").contains(args.peekString())) { + if (args.hasAny() && Arrays.asList("reset", "clear", "none").contains(args.peekString())) { args.requireMax(1); if (goalProcess.getGoal() != null) { goalProcess.setGoal(null); @@ -59,7 +60,7 @@ public class GoalCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { TabCompleteHelper helper = new TabCompleteHelper(); if (args.hasExactlyOne()) { helper.append(Stream.of("reset", "clear", "none", "~")); diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index 716e72ea..6b02fa30 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -20,6 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandNotFoundException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.pagination.Paginator; @@ -46,9 +47,9 @@ public class HelpCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(1); - if (!args.has() || args.is(Integer.class)) { + if (!args.hasAny() || args.is(Integer.class)) { Paginator.paginate( args, new Paginator<>( CommandManager.REGISTRY.descendingStream() @@ -99,7 +100,7 @@ public class HelpCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper().addCommands().filterPrefix(args.getString()).stream(); } diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index 1f3b1b98..6a8d3f06 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -23,6 +23,7 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalInverted; import baritone.api.process.ICustomGoalProcess; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -37,7 +38,7 @@ public class InvertCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index c9602a90..473296c9 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -23,6 +23,7 @@ import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.BlockById; import baritone.api.utils.command.datatypes.ForBlockOptionalMeta; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.cache.WorldScanner; @@ -38,11 +39,11 @@ public class MineCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { int quantity = args.getAsOrDefault(Integer.class, 0); args.requireMin(1); List boms = new ArrayList<>(); - while (args.has()) { + while (args.hasAny()) { boms.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); } WorldScanner.INSTANCE.repack(ctx); diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index 45172299..b5972e6b 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -24,6 +24,7 @@ import baritone.api.process.ICustomGoalProcess; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeCoordinate; import baritone.api.utils.command.datatypes.RelativeGoal; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; @@ -40,10 +41,10 @@ public class PathCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; - if (args.has()) { + if (args.hasAny()) { args.requireMax(3); goal = args.getDatatype(RelativeGoal.class).apply(ctx.playerFeet()); } else if ((goal = customGoalProcess.getGoal()) == null) { @@ -56,8 +57,8 @@ public class PathCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { - if (args.has() && !args.has(4)) { + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + if (args.hasAny() && !args.has(4)) { while (args.has(2)) { if (args.peekDatatypeOrNull(RelativeCoordinate.class) == null) { break; diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index ce221190..06e91377 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -23,6 +23,7 @@ import baritone.api.process.IBaritoneProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -81,7 +82,7 @@ public class PauseResumeCommands { ); pauseCommand = new Command(baritone, "pause") { @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); if (paused[0]) { throw new CommandInvalidStateException("Already paused"); @@ -114,7 +115,7 @@ public class PauseResumeCommands { }; resumeCommand = new Command(baritone, "resume") { @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); if (!paused[0]) { throw new CommandInvalidStateException("Not paused"); @@ -145,7 +146,7 @@ public class PauseResumeCommands { }; pausedCommand = new Command(baritone, "paused") { @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); logDirect(String.format("Baritone is %spaused", paused[0] ? "" : "not ")); } diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index d5d5b156..09c0b0c4 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -23,6 +23,7 @@ import baritone.api.pathing.calc.IPathingControlManager; import baritone.api.process.IBaritoneProcess; import baritone.api.process.PathingCommand; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -37,7 +38,7 @@ public class ProcCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); IPathingControlManager pathingControlManager = baritone.getPathingControlManager(); IBaritoneProcess process = pathingControlManager.mostRecentInControl().orElse(null); diff --git a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index 37640fbd..877be0b6 100644 --- a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -20,6 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -33,7 +34,7 @@ public class ReloadAllCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); ctx.worldData().getCachedWorld().reloadAllFromDisk(); logDirect("Reloaded"); diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index 494104ec..92aedc43 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -21,6 +21,7 @@ import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -34,7 +35,7 @@ public class RenderCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); BetterBlockPos origin = ctx.playerFeet(); int renderDistance = (mc.gameSettings.renderDistanceChunks + 1) * 16; diff --git a/src/main/java/baritone/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java index 1c5a79f7..90c131e9 100644 --- a/src/main/java/baritone/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -20,6 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.cache.WorldScanner; @@ -34,7 +35,7 @@ public class RepackCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); logDirect(String.format("Queued %d chunks for repacking", WorldScanner.INSTANCE.repack(ctx))); } diff --git a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index 92601467..6729e968 100644 --- a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -20,6 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -33,7 +34,7 @@ public class SaveAllCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); ctx.worldData().getCachedWorld().save(); logDirect("Saved"); diff --git a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index 18e51738..53ba4c1d 100644 --- a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -20,6 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -33,7 +34,7 @@ public class SchematicaCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); baritone.getBuilderProcess().buildOpenSchematic(); } diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index 7bd0fa2c..7895586b 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -33,6 +33,7 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.ForBlockOptionalMeta; import baritone.api.utils.command.datatypes.ForEnumFacing; import baritone.api.utils.command.datatypes.RelativeBlockPos; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -75,7 +76,7 @@ public class SelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { Action action = Action.getByName(args.getString()); if (action == null) { throw new CommandInvalidTypeException(args.consumed(), "an action"); @@ -85,7 +86,7 @@ public class SelCommand extends Command { throw new CommandInvalidStateException("Set pos1 first before using pos2"); } BetterBlockPos playerPos = mc.getRenderViewEntity() != null ? BetterBlockPos.from(new BlockPos(mc.getRenderViewEntity())) : ctx.playerFeet(); - BetterBlockPos pos = args.has() ? args.getDatatypePost(RelativeBlockPos.class, playerPos) : playerPos; + BetterBlockPos pos = args.hasAny() ? args.getDatatypePost(RelativeBlockPos.class, playerPos) : playerPos; args.requireMax(0); if (action == Action.POS1) { pos1 = pos; @@ -186,7 +187,7 @@ public class SelCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper() .append(Action.getAllNames()) diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index dbcfbae0..294fe0ce 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -21,6 +21,7 @@ import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.SettingsUtil; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.pagination.Paginator; @@ -48,8 +49,8 @@ public class SetCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { - String arg = args.has() ? args.getString().toLowerCase(Locale.US) : "list"; + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + String arg = args.hasAny() ? args.getString().toLowerCase(Locale.US) : "list"; if (Arrays.asList("s", "save").contains(arg)) { SettingsUtil.save(settings); logDirect("Settings saved"); @@ -59,7 +60,7 @@ public class SetCommand extends Command { boolean viewAll = Arrays.asList("all", "l", "list").contains(arg); boolean paginate = viewModified || viewAll; if (paginate) { - String search = args.has() && args.peekAsOrNull(Integer.class) == null ? args.getString() : ""; + String search = args.hasAny() && args.peekAsOrNull(Integer.class) == null ? args.getString() : ""; args.requireMax(1); List toPaginate = (viewModified ? SettingsUtil.modifiedSettings(settings) : settings.allSettings).stream() @@ -104,7 +105,7 @@ public class SetCommand extends Command { boolean toggling = arg.equalsIgnoreCase("toggle"); boolean doingSomething = resetting || toggling; if (resetting) { - if (!args.has()) { + if (!args.hasAny()) { logDirect("Please specify 'all' as an argument to reset to confirm you'd really like to do this"); logDirect("ALL settings will be reset. Use the 'set modified' or 'modified' commands to see what will be reset."); logDirect("Specify a setting name instead of 'all' to only reset one setting"); @@ -126,7 +127,7 @@ public class SetCommand extends Command { if (setting == null) { throw new CommandInvalidTypeException(args.consumed(), "a valid setting"); } - if (!doingSomething && !args.has()) { + if (!doingSomething && !args.hasAny()) { logDirect(String.format("Value of setting %s:", setting.getName())); logDirect(settingValueToString(setting)); } else { @@ -184,8 +185,8 @@ public class SetCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { - if (args.has()) { + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + if (args.hasAny()) { String arg = args.getString(); if (args.hasExactlyOne() && !Arrays.asList("s", "save").contains(args.peekString().toLowerCase(Locale.US))) { if (arg.equalsIgnoreCase("reset")) { @@ -214,7 +215,7 @@ public class SetCommand extends Command { return Stream.of(settingValueToString(setting)); } } - } else if (!args.has()) { + } else if (!args.hasAny()) { return new TabCompleteHelper() .addSettings() .sortAlphabetically() diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index 80c3d69b..2cbde830 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -21,6 +21,7 @@ import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -34,7 +35,7 @@ public class ThisWayCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireExactly(1); GoalXZ goal = GoalXZ.fromDirection( ctx.playerFeetAsVec(), diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index dbed314d..5f1dca55 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -22,6 +22,7 @@ import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalStrictDirection; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Arrays; @@ -35,7 +36,7 @@ public class TunnelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); Goal goal = new GoalStrictDirection( ctx.playerFeet(), diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index 6e8812a4..80170a42 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -20,6 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.command.Command; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -34,7 +35,7 @@ public class VersionCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { args.requireMax(0); String version = getClass().getPackage().getImplementationVersion(); if (version == null) { diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index c94d757d..3af2ebd9 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -27,6 +27,7 @@ import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.ForWaypoints; import baritone.api.utils.command.datatypes.RelativeBlockPos; +import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -52,8 +53,8 @@ public class WaypointsCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { - Action action = args.has() ? Action.getByName(args.getString()) : Action.LIST; + protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + Action action = args.hasAny() ? Action.getByName(args.getString()) : Action.LIST; if (action == null) { throw new CommandInvalidTypeException(args.consumed(), "an action"); } @@ -90,7 +91,7 @@ public class WaypointsCommand extends Command { Function transform = waypoint -> toComponent.apply(waypoint, action == Action.LIST ? Action.INFO : action); if (action == Action.LIST) { - IWaypoint.Tag tag = args.has() ? IWaypoint.Tag.getByName(args.peekString()) : null; + IWaypoint.Tag tag = args.hasAny() ? IWaypoint.Tag.getByName(args.peekString()) : null; if (tag != null) { args.get(); } @@ -129,8 +130,8 @@ public class WaypointsCommand extends Command { if (tag == null) { throw new CommandInvalidStateException(String.format("'%s' is not a tag ", args.consumedString())); } - String name = args.has() ? args.getString() : ""; - BetterBlockPos pos = args.has() + String name = args.hasAny() ? args.getString() : ""; + BetterBlockPos pos = args.hasAny() ? args.getDatatypePost(RelativeBlockPos.class, ctx.playerFeet()) : ctx.playerFeet(); args.requireMax(0); @@ -151,7 +152,7 @@ public class WaypointsCommand extends Command { } else { IWaypoint[] waypoints = args.getDatatypeFor(ForWaypoints.class); IWaypoint waypoint = null; - if (args.has() && args.peekString().equals("@")) { + if (args.hasAny() && args.peekString().equals("@")) { args.requireExactly(2); args.get(); long timestamp = args.getAs(Long.class); @@ -241,8 +242,8 @@ public class WaypointsCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { - if (args.has()) { + protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + if (args.hasAny()) { if (args.hasExactlyOne()) { return new TabCompleteHelper() .append(Action.getAllNames()) From ea4f34cb0ff4e57725649a97f67d31a75954d0aa Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 21 Sep 2019 02:07:10 -0500 Subject: [PATCH 653/682] No more passing Settings to execute and tabComplete --- .../baritone/api/utils/command/Command.java | 9 ++++--- .../command/execution/CommandExecution.java | 6 ++--- .../utils/command/defaults/AxisCommand.java | 4 +-- .../command/defaults/BlacklistCommand.java | 4 +-- .../utils/command/defaults/BuildCommand.java | 4 +-- .../utils/command/defaults/CancelCommand.java | 4 +-- .../utils/command/defaults/ChestsCommand.java | 4 +-- .../command/defaults/ClearareaCommand.java | 4 +-- .../utils/command/defaults/ClickCommand.java | 4 +-- .../utils/command/defaults/ComeCommand.java | 4 +-- .../utils/command/defaults/CommandAlias.java | 4 +-- .../command/defaults/ExploreCommand.java | 4 +-- .../defaults/ExploreFilterCommand.java | 4 +-- .../utils/command/defaults/FarmCommand.java | 4 +-- .../utils/command/defaults/FindCommand.java | 4 +-- .../utils/command/defaults/FollowCommand.java | 4 +-- .../command/defaults/ForceCancelCommand.java | 4 +-- .../utils/command/defaults/GcCommand.java | 4 +-- .../utils/command/defaults/GoalCommand.java | 4 +-- .../utils/command/defaults/HelpCommand.java | 4 +-- .../utils/command/defaults/InvertCommand.java | 4 +-- .../utils/command/defaults/MineCommand.java | 4 +-- .../utils/command/defaults/PathCommand.java | 4 +-- .../command/defaults/PauseResumeCommands.java | 14 +++++----- .../utils/command/defaults/ProcCommand.java | 4 +-- .../command/defaults/ReloadAllCommand.java | 4 +-- .../utils/command/defaults/RenderCommand.java | 4 +-- .../utils/command/defaults/RepackCommand.java | 4 +-- .../command/defaults/SaveAllCommand.java | 4 +-- .../command/defaults/SchematicaCommand.java | 4 +-- .../utils/command/defaults/SelCommand.java | 4 +-- .../utils/command/defaults/SetCommand.java | 27 ++++++++++--------- .../command/defaults/ThisWayCommand.java | 4 +-- .../utils/command/defaults/TunnelCommand.java | 4 +-- .../command/defaults/VersionCommand.java | 4 +-- .../command/defaults/WaypointsCommand.java | 4 +-- 36 files changed, 91 insertions(+), 93 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index 1d198c9a..6b922687 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -35,6 +35,7 @@ public abstract class Command implements Helper { protected IBaritone baritone; protected IPlayerContext ctx; + /** * The names of this command. This is what you put after the command prefix. */ @@ -63,7 +64,7 @@ public abstract class Command implements Helper { * @param execution The command execution to execute this command with */ public void execute(CommandExecution execution) throws CommandException { - executed(execution.label, execution.args, execution.settings); + executed(execution.label, execution.args); } /** @@ -74,7 +75,7 @@ public abstract class Command implements Helper { */ public Stream tabComplete(CommandExecution execution) { try { - return tabCompleted(execution.label, execution.args, execution.settings); + return tabCompleted(execution.label, execution.args); } catch (Throwable t) { return Stream.empty(); } @@ -83,13 +84,13 @@ public abstract class Command implements Helper { /** * Called when this command is executed. */ - protected abstract void executed(String label, ArgConsumer args, Settings settings) throws CommandException; + protected abstract void executed(String label, ArgConsumer args) throws CommandException; /** * Called when the command needs to tab complete. Return a Stream representing the entries to put in the completions * list. */ - protected abstract Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException; + protected abstract Stream tabCompleted(String label, ArgConsumer args) throws CommandException; /** * @return A single-line string containing a short description of this command's purpose. diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java index b82926e4..dc25d32c 100644 --- a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java +++ b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java @@ -36,18 +36,16 @@ public class CommandExecution { * The command itself */ private final Command command; + /** * The name this command was called with */ public final String label; + /** * The arg consumer */ public final ArgConsumer args; - /** - * The Baritone settings - */ - public final Settings settings = BaritoneAPI.getSettings(); public CommandExecution(Command command, String label, ArgConsumer args) { this.command = command; diff --git a/src/main/java/baritone/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java index 50525f2d..942c829e 100644 --- a/src/main/java/baritone/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -36,7 +36,7 @@ public class AxisCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); Goal goal = new GoalAxis(); baritone.getCustomGoalProcess().setGoal(goal); @@ -44,7 +44,7 @@ public class AxisCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index e680e4fa..915f5b51 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -36,7 +36,7 @@ public class BlacklistCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); IGetToBlockProcess proc = baritone.getGetToBlockProcess(); if (!proc.isActive()) { @@ -50,7 +50,7 @@ public class BlacklistCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index 85f51da1..72c065c7 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -43,7 +43,7 @@ public class BuildCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { File file = args.getDatatypePost(RelativeFile.class, schematicsDir).getAbsoluteFile(); if (!file.getName().toLowerCase(Locale.US).endsWith(".schematic")) { file = new File(file.getAbsolutePath() + ".schematic"); @@ -65,7 +65,7 @@ public class BuildCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return RelativeFile.tabComplete(args, schematicsDir); } else if (args.has(2)) { diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index 55c172b8..45e0854a 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -34,14 +34,14 @@ public class CancelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); baritone.getPathingBehavior().cancelEverything(); logDirect("ok canceled"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index 8e2cee79..5c0bc354 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -42,7 +42,7 @@ public class ChestsCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); Set> entries = ctx.worldData().getContainerMemory().getRememberedInventories().entrySet(); @@ -63,7 +63,7 @@ public class ChestsCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index 99f39307..5e404180 100644 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -39,7 +39,7 @@ public class ClearareaCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { BetterBlockPos pos1 = ctx.playerFeet(); BetterBlockPos pos2; if (args.hasAny()) { @@ -59,7 +59,7 @@ public class ClearareaCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return args.tabCompleteDatatype(RelativeBlockPos.class); } diff --git a/src/main/java/baritone/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java index 49324d88..23ded82f 100644 --- a/src/main/java/baritone/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -34,14 +34,14 @@ public class ClickCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); baritone.openClick(); logDirect("aight dude"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index bf02d75d..399317e5 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -38,7 +38,7 @@ public class ComeCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); Entity entity = mc.getRenderViewEntity(); if (entity == null) { @@ -49,7 +49,7 @@ public class ComeCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/CommandAlias.java b/src/main/java/baritone/utils/command/defaults/CommandAlias.java index aba934b2..91dc2a07 100644 --- a/src/main/java/baritone/utils/command/defaults/CommandAlias.java +++ b/src/main/java/baritone/utils/command/defaults/CommandAlias.java @@ -45,12 +45,12 @@ public class CommandAlias extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) { + protected void executed(String label, ArgConsumer args) { CommandManager.execute(String.format("%s %s", target, args.rawRest())); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return CommandManager.tabComplete(String.format("%s %s", target, args.rawRest())); } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index 57b95d59..6f844476 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -36,7 +36,7 @@ public class ExploreCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { if (args.hasAny()) { args.requireExactly(2); } else { @@ -50,7 +50,7 @@ public class ExploreCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { if (args.hasAtMost(2)) { return args.tabCompleteDatatype(RelativeGoalXZ.class); } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index 338a622c..6deffd22 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -40,7 +40,7 @@ public class ExploreFilterCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(2); File file = args.getDatatypePost(RelativeFile.class, mc.gameDir.getAbsoluteFile().getParentFile()); boolean invert = false; @@ -64,7 +64,7 @@ public class ExploreFilterCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return RelativeFile.tabComplete(args, RelativeFile.gameDir()); } diff --git a/src/main/java/baritone/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java index af3efa2c..6ff746d4 100644 --- a/src/main/java/baritone/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -34,14 +34,14 @@ public class FarmCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); baritone.getFarmProcess().farm(); logDirect("Farming"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index 552985a4..c5a808dd 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -38,7 +38,7 @@ public class FindCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { List toFind = new ArrayList<>(); while (args.hasAny()) { toFind.add(args.getDatatypeFor(BlockById.class)); @@ -60,7 +60,7 @@ public class FindCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return args.tabCompleteDatatype(BlockById.class); } diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index 46f89d75..b22613b9 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -44,7 +44,7 @@ public class FollowCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMin(1); FollowGroup group; FollowList list; @@ -91,7 +91,7 @@ public class FollowCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper() .append(FollowGroup.class) diff --git a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index 6596749d..5672f9b3 100644 --- a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -35,7 +35,7 @@ public class ForceCancelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); IPathingBehavior pathingBehavior = baritone.getPathingBehavior(); pathingBehavior.cancelEverything(); @@ -44,7 +44,7 @@ public class ForceCancelCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index aa29d667..23bea821 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -34,14 +34,14 @@ public class GcCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); System.gc(); logDirect("ok called System.gc()"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index bd50e33e..23065deb 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -40,7 +40,7 @@ public class GoalCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { ICustomGoalProcess goalProcess = baritone.getCustomGoalProcess(); if (args.hasAny() && Arrays.asList("reset", "clear", "none").contains(args.peekString())) { args.requireMax(1); @@ -60,7 +60,7 @@ public class GoalCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { TabCompleteHelper helper = new TabCompleteHelper(); if (args.hasExactlyOne()) { helper.append(Stream.of("reset", "clear", "none", "~")); diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index 6b02fa30..8cdcab71 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -47,7 +47,7 @@ public class HelpCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(1); if (!args.hasAny() || args.is(Integer.class)) { Paginator.paginate( @@ -100,7 +100,7 @@ public class HelpCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper().addCommands().filterPrefix(args.getString()).stream(); } diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index 6a8d3f06..60723de2 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -38,7 +38,7 @@ public class InvertCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; @@ -55,7 +55,7 @@ public class InvertCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index 473296c9..e1b1f67b 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -39,7 +39,7 @@ public class MineCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { int quantity = args.getAsOrDefault(Integer.class, 0); args.requireMin(1); List boms = new ArrayList<>(); @@ -52,7 +52,7 @@ public class MineCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return args.tabCompleteDatatype(BlockById.class); } diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index b5972e6b..d1da5957 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -41,7 +41,7 @@ public class PathCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; if (args.hasAny()) { @@ -57,7 +57,7 @@ public class PathCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { if (args.hasAny() && !args.has(4)) { while (args.has(2)) { if (args.peekDatatypeOrNull(RelativeCoordinate.class) == null) { diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index 06e91377..ee15fde6 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -40,13 +40,11 @@ import java.util.stream.Stream; */ public class PauseResumeCommands { - private final IBaritone baritone; Command pauseCommand; Command resumeCommand; Command pausedCommand; public PauseResumeCommands(IBaritone baritone) { - this.baritone = baritone; // array for mutability, non-field so reflection can't touch it final boolean[] paused = {false}; baritone.getPathingControlManager().registerProcess( @@ -82,7 +80,7 @@ public class PauseResumeCommands { ); pauseCommand = new Command(baritone, "pause") { @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); if (paused[0]) { throw new CommandInvalidStateException("Already paused"); @@ -92,7 +90,7 @@ public class PauseResumeCommands { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } @@ -115,7 +113,7 @@ public class PauseResumeCommands { }; resumeCommand = new Command(baritone, "resume") { @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); if (!paused[0]) { throw new CommandInvalidStateException("Not paused"); @@ -125,7 +123,7 @@ public class PauseResumeCommands { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } @@ -146,13 +144,13 @@ public class PauseResumeCommands { }; pausedCommand = new Command(baritone, "paused") { @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); logDirect(String.format("Baritone is %spaused", paused[0] ? "" : "not ")); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index 09c0b0c4..063df9be 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -38,7 +38,7 @@ public class ProcCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); IPathingControlManager pathingControlManager = baritone.getPathingControlManager(); IBaritoneProcess process = pathingControlManager.mostRecentInControl().orElse(null); @@ -63,7 +63,7 @@ public class ProcCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index 877be0b6..0a860ede 100644 --- a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -34,14 +34,14 @@ public class ReloadAllCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); ctx.worldData().getCachedWorld().reloadAllFromDisk(); logDirect("Reloaded"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index 92aedc43..75cf0a44 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -35,7 +35,7 @@ public class RenderCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); BetterBlockPos origin = ctx.playerFeet(); int renderDistance = (mc.gameSettings.renderDistanceChunks + 1) * 16; @@ -51,7 +51,7 @@ public class RenderCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java index 90c131e9..08503531 100644 --- a/src/main/java/baritone/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -35,13 +35,13 @@ public class RepackCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); logDirect(String.format("Queued %d chunks for repacking", WorldScanner.INSTANCE.repack(ctx))); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index 6729e968..a505dda1 100644 --- a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -34,14 +34,14 @@ public class SaveAllCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); ctx.worldData().getCachedWorld().save(); logDirect("Saved"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index 53ba4c1d..2a984dd2 100644 --- a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -34,13 +34,13 @@ public class SchematicaCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); baritone.getBuilderProcess().buildOpenSchematic(); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index 7895586b..362fd631 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -76,7 +76,7 @@ public class SelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { Action action = Action.getByName(args.getString()); if (action == null) { throw new CommandInvalidTypeException(args.consumed(), "an action"); @@ -187,7 +187,7 @@ public class SelCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper() .append(Action.getAllNames()) diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index 294fe0ce..f3baeeb2 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -17,6 +17,7 @@ package baritone.utils.command.defaults; +import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.utils.SettingsUtil; @@ -49,10 +50,10 @@ public class SetCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { String arg = args.hasAny() ? args.getString().toLowerCase(Locale.US) : "list"; if (Arrays.asList("s", "save").contains(arg)) { - SettingsUtil.save(settings); + SettingsUtil.save(Baritone.settings()); logDirect("Settings saved"); return; } @@ -63,7 +64,7 @@ public class SetCommand extends Command { String search = args.hasAny() && args.peekAsOrNull(Integer.class) == null ? args.getString() : ""; args.requireMax(1); List toPaginate = - (viewModified ? SettingsUtil.modifiedSettings(settings) : settings.allSettings).stream() + (viewModified ? SettingsUtil.modifiedSettings(Baritone.settings()) : Baritone.settings().allSettings).stream() .filter(s -> !s.getName().equals("logger")) .filter(s -> s.getName().toLowerCase(Locale.US).contains(search.toLowerCase(Locale.US))) .sorted((s1, s2) -> String.CASE_INSENSITIVE_ORDER.compare(s1.getName(), s2.getName())) @@ -87,7 +88,7 @@ public class SetCommand extends Command { hoverComponent.appendText(setting.getName()); hoverComponent.appendText(String.format("\nType: %s", settingTypeToString(setting))); hoverComponent.appendText(String.format("\n\nValue:\n%s", settingValueToString(setting))); - String commandSuggestion = settings.prefix.value + String.format("set %s ", setting.getName()); + String commandSuggestion = Baritone.settings().prefix.value + String.format("set %s ", setting.getName()); ITextComponent component = new TextComponentString(setting.getName()); component.getStyle().setColor(TextFormatting.GRAY); component.appendSibling(typeComponent); @@ -110,9 +111,9 @@ public class SetCommand extends Command { logDirect("ALL settings will be reset. Use the 'set modified' or 'modified' commands to see what will be reset."); logDirect("Specify a setting name instead of 'all' to only reset one setting"); } else if (args.peekString().equalsIgnoreCase("all")) { - SettingsUtil.modifiedSettings(settings).forEach(Settings.Setting::reset); + SettingsUtil.modifiedSettings(Baritone.settings()).forEach(Settings.Setting::reset); logDirect("All settings have been reset to their default values"); - SettingsUtil.save(settings); + SettingsUtil.save(Baritone.settings()); return; } } @@ -120,7 +121,7 @@ public class SetCommand extends Command { args.requireMin(1); } String settingName = doingSomething ? args.getString() : arg; - Settings.Setting setting = settings.allSettings.stream() + Settings.Setting setting = Baritone.settings().allSettings.stream() .filter(s -> s.getName().equalsIgnoreCase(settingName)) .findFirst() .orElse(null); @@ -148,7 +149,7 @@ public class SetCommand extends Command { } else { String newValue = args.getString(); try { - SettingsUtil.parseAndApply(settings, arg, newValue); + SettingsUtil.parseAndApply(Baritone.settings(), arg, newValue); } catch (Throwable t) { t.printStackTrace(); throw new CommandInvalidTypeException(args.consumed(), "a valid value", t); @@ -174,18 +175,18 @@ public class SetCommand extends Command { FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue) )); logDirect(oldValueComponent); - if ((setting.getName().equals("chatControl") && !(Boolean) setting.value && !settings.chatControlAnyway.value) || - setting.getName().equals("chatControlAnyway") && !(Boolean) setting.value && !settings.chatControl.value) { + if ((setting.getName().equals("chatControl") && !(Boolean) setting.value && !Baritone.settings().chatControlAnyway.value) || + setting.getName().equals("chatControlAnyway") && !(Boolean) setting.value && !Baritone.settings().chatControl.value) { logDirect("Warning: Chat commands will no longer work. If you want to revert this change, use prefix control (if enabled) or click the old value listed above.", TextFormatting.RED); } else if (setting.getName().equals("prefixControl") && !(Boolean) setting.value) { logDirect("Warning: Prefixed commands will no longer work. If you want to revert this change, use chat control (if enabled) or click the old value listed above.", TextFormatting.RED); } } - SettingsUtil.save(settings); + SettingsUtil.save(Baritone.settings()); } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { if (args.hasAny()) { String arg = args.getString(); if (args.hasExactlyOne() && !Arrays.asList("s", "save").contains(args.peekString().toLowerCase(Locale.US))) { @@ -201,7 +202,7 @@ public class SetCommand extends Command { .filterPrefix(args.getString()) .stream(); } - Settings.Setting setting = settings.byLowerName.get(arg.toLowerCase(Locale.US)); + Settings.Setting setting = Baritone.settings().byLowerName.get(arg.toLowerCase(Locale.US)); if (setting != null) { if (setting.getType() == Boolean.class) { TabCompleteHelper helper = new TabCompleteHelper(); diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index 2cbde830..384a52cb 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -35,7 +35,7 @@ public class ThisWayCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireExactly(1); GoalXZ goal = GoalXZ.fromDirection( ctx.playerFeetAsVec(), @@ -47,7 +47,7 @@ public class ThisWayCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index 5f1dca55..5ac21b7a 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -36,7 +36,7 @@ public class TunnelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); Goal goal = new GoalStrictDirection( ctx.playerFeet(), @@ -47,7 +47,7 @@ public class TunnelCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index 80170a42..de09e943 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -35,7 +35,7 @@ public class VersionCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(0); String version = getClass().getPackage().getImplementationVersion(); if (version == null) { @@ -46,7 +46,7 @@ public class VersionCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) { + protected Stream tabCompleted(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 3af2ebd9..6344117a 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -53,7 +53,7 @@ public class WaypointsCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args, Settings settings) throws CommandException { + protected void executed(String label, ArgConsumer args) throws CommandException { Action action = args.hasAny() ? Action.getByName(args.getString()) : Action.LIST; if (action == null) { throw new CommandInvalidTypeException(args.consumed(), "an action"); @@ -242,7 +242,7 @@ public class WaypointsCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args, Settings settings) throws CommandException { + protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { if (args.hasAny()) { if (args.hasExactlyOne()) { return new TabCompleteHelper() From 9d2f83d8d6d0cdf6f4d354b1f8251cd4e6025a2c Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 21 Sep 2019 02:11:46 -0500 Subject: [PATCH 654/682] Fix unused imports --- .../baritone/api/utils/command/execution/CommandExecution.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java index dc25d32c..9b436035 100644 --- a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java +++ b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java @@ -17,8 +17,6 @@ package baritone.api.utils.command.execution; -import baritone.api.BaritoneAPI; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.exception.CommandException; From b88af1d682e30f7b01f32872b4f299e20908d894 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 21 Sep 2019 02:40:03 -0500 Subject: [PATCH 655/682] CommandManager is now Baritone instance dependent --- src/api/java/baritone/api/IBaritone.java | 7 +++ .../utils/command/BaritoneChatControl.java | 15 +++-- .../command/execution/CommandExecution.java | 14 ++--- .../tabcomplete/TabCompleteHelper.java | 17 +++--- .../command/manager/ICommandManager.java | 52 +++++++++++++++++ src/main/java/baritone/Baritone.java | 8 +++ src/main/java/baritone/BaritoneProvider.java | 11 ++-- .../utils/command/defaults/CommandAlias.java | 6 +- .../utils/command/defaults/HelpCommand.java | 12 ++-- .../utils/command/manager/CommandManager.java | 56 ++++++++++++------- 10 files changed, 140 insertions(+), 58 deletions(-) create mode 100644 src/api/java/baritone/api/utils/command/manager/ICommandManager.java rename src/{api/java/baritone/api => main/java/baritone}/utils/command/manager/CommandManager.java (57%) diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index fa8c5465..8c5de47a 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -26,6 +26,7 @@ import baritone.api.process.*; import baritone.api.selection.ISelectionManager; import baritone.api.utils.IInputOverrideHandler; import baritone.api.utils.IPlayerContext; +import baritone.api.utils.command.manager.ICommandManager; /** * @author Brady @@ -126,6 +127,12 @@ public interface IBaritone { */ ISelectionManager getSelectionManager(); + /** + * @return The {@link ICommandManager} instance + * @see ICommandManager + */ + ICommandManager getCommandManager(); + /** * Open click */ diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index 7724e1bf..4fbd93ab 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -33,7 +33,6 @@ import baritone.api.utils.command.exception.CommandNotFoundException; import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; -import baritone.api.utils.command.manager.CommandManager; import com.mojang.realmsclient.util.Pair; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; @@ -130,9 +129,9 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (setting != null) { logRanCommand(command, rest); if (setting.getValueClass() == Boolean.class) { - CommandManager.execute(String.format("set toggle %s", setting.getName())); + this.baritone.getCommandManager().execute(String.format("set toggle %s", setting.getName())); } else { - CommandManager.execute(String.format("set %s", setting.getName())); + this.baritone.getCommandManager().execute(String.format("set %s", setting.getName())); } return true; } @@ -144,18 +143,18 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (setting.getName().equalsIgnoreCase(pair.first())) { logRanCommand(command, rest); try { - CommandManager.execute(String.format("set %s %s", setting.getName(), argc.getString())); + this.baritone.getCommandManager().execute(String.format("set %s %s", setting.getName(), argc.getString())); } catch (CommandNotEnoughArgumentsException ignored) {} // The operation is safe return true; } } } - CommandExecution execution = CommandExecution.from(pair); + CommandExecution execution = CommandExecution.from(this.baritone.getCommandManager(), pair); if (execution == null) { return false; } logRanCommand(command, rest); - CommandManager.execute(execution); + this.baritone.getCommandManager().execute(execution); return true; } @@ -185,7 +184,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (argc.hasAtMost(2)) { if (argc.hasExactly(1)) { return new TabCompleteHelper() - .addCommands() + .addCommands(this.baritone.getCommandManager()) .addSettings() .filterPrefix(argc.getString()) .stream(); @@ -205,7 +204,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } } } - return CommandManager.tabComplete(msg); + return this.baritone.getCommandManager().tabComplete(msg); } catch (CommandNotEnoughArgumentsException ignored) { // Shouldn't happen, the operation is safe return Stream.empty(); } diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java index 9b436035..26370fe8 100644 --- a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java +++ b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java @@ -22,7 +22,7 @@ import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandUnhandledException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; -import baritone.api.utils.command.manager.CommandManager; +import baritone.api.utils.command.manager.ICommandManager; import com.mojang.realmsclient.util.Pair; import java.util.List; @@ -80,8 +80,8 @@ public class CommandExecution { return command.tabComplete(this); } - public static CommandExecution from(String label, ArgConsumer args) { - Command command = CommandManager.getCommand(label); + public static CommandExecution from(ICommandManager manager, String label, ArgConsumer args) { + Command command = manager.getCommand(label); if (command == null) { return null; } @@ -92,11 +92,11 @@ public class CommandExecution { ); } - public static CommandExecution from(Pair> pair) { - return from(pair.first(), new ArgConsumer(pair.second())); + public static CommandExecution from(ICommandManager manager, Pair> pair) { + return from(manager, pair.first(), new ArgConsumer(pair.second())); } - public static CommandExecution from(String string) { - return from(expand(string)); + public static CommandExecution from(ICommandManager manager, String string) { + return from(manager, expand(string)); } } diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index 98b88667..b5a5eba3 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -23,7 +23,7 @@ import baritone.api.event.events.TabCompleteEvent; import baritone.api.utils.SettingsUtil; import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; -import baritone.api.utils.command.manager.CommandManager; +import baritone.api.utils.command.manager.ICommandManager; import net.minecraft.util.ResourceLocation; import java.util.Arrays; @@ -46,7 +46,7 @@ import java.util.stream.Stream; * {@link #filterPrefix(String)} *

  • Get the stream using {@link #stream()}
  • *
  • Pass it up to whatever's calling your tab complete function (i.e. - * {@link CommandManager#tabComplete(CommandExecution)} or {@link ArgConsumer#tabCompleteDatatype(Class)})
  • + * {@link ICommandManager#tabComplete(CommandExecution)} or {@link ArgConsumer#tabCompleteDatatype(Class)}) * *

    * For advanced users: if you're intercepting {@link TabCompleteEvent}s directly, use {@link #build()} instead for an @@ -253,15 +253,16 @@ public class TabCompleteHelper { } /** - * Appends every command in the {@link CommandManager#REGISTRY} to this {@link TabCompleteHelper} + * Appends every command in the specified {@link ICommandManager} to this {@link TabCompleteHelper} + * + * @param manager A command manager * * @return This {@link TabCompleteHelper} */ - public TabCompleteHelper addCommands() { - return append( - CommandManager.REGISTRY.descendingStream() - .flatMap(command -> command.names.stream()) - .distinct() + public TabCompleteHelper addCommands(ICommandManager manager) { + return append(manager.getRegistry().descendingStream() + .flatMap(command -> command.names.stream()) + .distinct() ); } diff --git a/src/api/java/baritone/api/utils/command/manager/ICommandManager.java b/src/api/java/baritone/api/utils/command/manager/ICommandManager.java new file mode 100644 index 00000000..82b085fa --- /dev/null +++ b/src/api/java/baritone/api/utils/command/manager/ICommandManager.java @@ -0,0 +1,52 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils.command.manager; + +import baritone.api.utils.command.Command; +import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.execution.CommandExecution; +import baritone.api.utils.command.registry.Registry; +import com.mojang.realmsclient.util.Pair; + +import java.util.List; +import java.util.stream.Stream; + +/** + * @author Brady + * @since 9/21/2019 + */ +public interface ICommandManager { + + Registry getRegistry(); + + /** + * @param name The command name to search for. + * @return The command, if found. + */ + Command getCommand(String name); + + void execute(CommandExecution execution); + + boolean execute(String string); + + Stream tabComplete(CommandExecution execution); + + Stream tabComplete(Pair> pair); + + Stream tabComplete(String prefix); +} diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index e9c3990f..cfd658b1 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -29,6 +29,7 @@ import baritone.event.GameEventHandler; import baritone.process.*; import baritone.selection.SelectionManager; import baritone.utils.*; +import baritone.utils.command.manager.CommandManager; import baritone.utils.player.PrimaryPlayerContext; import net.minecraft.client.Minecraft; @@ -79,6 +80,7 @@ public class Baritone implements IBaritone { private PathingControlManager pathingControlManager; private SelectionManager selectionManager; + private CommandManager commandManager; private IPlayerContext playerContext; private WorldProvider worldProvider; @@ -114,6 +116,7 @@ public class Baritone implements IBaritone { this.worldProvider = new WorldProvider(); this.selectionManager = new SelectionManager(this); + this.commandManager = new CommandManager(this); if (BaritoneAutoTest.ENABLE_AUTO_TEST) { this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE); @@ -205,6 +208,11 @@ public class Baritone implements IBaritone { return this.gameEventHandler; } + @Override + public CommandManager getCommandManager() { + return this.commandManager; + } + @Override public void openClick() { new Thread(() -> { diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index 6293ca51..e07969d6 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -21,9 +21,7 @@ import baritone.api.IBaritone; import baritone.api.IBaritoneProvider; import baritone.api.cache.IWorldScanner; import baritone.api.utils.command.BaritoneChatControl; -import baritone.api.utils.command.manager.CommandManager; import baritone.cache.WorldScanner; -import baritone.utils.command.defaults.DefaultCommands; import java.util.Collections; import java.util.List; @@ -38,10 +36,11 @@ public final class BaritoneProvider implements IBaritoneProvider { private final List all; { - primary = new Baritone(); - all = Collections.singletonList(primary); - DefaultCommands.commands(primary).forEach(CommandManager.REGISTRY::register); - new BaritoneChatControl(primary); + this.primary = new Baritone(); + this.all = Collections.singletonList(this.primary); + + // Setup chat control, just for the primary instance + new BaritoneChatControl(this.primary); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/CommandAlias.java b/src/main/java/baritone/utils/command/defaults/CommandAlias.java index 91dc2a07..cbd8ac77 100644 --- a/src/main/java/baritone/utils/command/defaults/CommandAlias.java +++ b/src/main/java/baritone/utils/command/defaults/CommandAlias.java @@ -18,10 +18,8 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.helpers.arguments.ArgConsumer; -import baritone.api.utils.command.manager.CommandManager; import java.util.Collections; import java.util.List; @@ -46,12 +44,12 @@ public class CommandAlias extends Command { @Override protected void executed(String label, ArgConsumer args) { - CommandManager.execute(String.format("%s %s", target, args.rawRest())); + this.baritone.getCommandManager().execute(String.format("%s %s", target, args.rawRest())); } @Override protected Stream tabCompleted(String label, ArgConsumer args) { - return CommandManager.tabComplete(String.format("%s %s", target, args.rawRest())); + return this.baritone.getCommandManager().tabComplete(String.format("%s %s", target, args.rawRest())); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index 8cdcab71..de2a74f0 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -18,14 +18,12 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandNotFoundException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.pagination.Paginator; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; -import baritone.api.utils.command.manager.CommandManager; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; @@ -38,7 +36,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; -import static baritone.api.utils.command.manager.CommandManager.getCommand; public class HelpCommand extends Command { @@ -52,7 +49,7 @@ public class HelpCommand extends Command { if (!args.hasAny() || args.is(Integer.class)) { Paginator.paginate( args, new Paginator<>( - CommandManager.REGISTRY.descendingStream() + this.baritone.getCommandManager().getRegistry().descendingStream() .filter(command -> !command.hiddenFromHelp()) .collect(Collectors.toList()) ), @@ -82,7 +79,7 @@ public class HelpCommand extends Command { ); } else { String commandName = args.getString().toLowerCase(); - Command command = getCommand(commandName); + Command command = this.baritone.getCommandManager().getCommand(commandName); if (command == null) { throw new CommandNotFoundException(commandName); } @@ -102,7 +99,10 @@ public class HelpCommand extends Command { @Override protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { - return new TabCompleteHelper().addCommands().filterPrefix(args.getString()).stream(); + return new TabCompleteHelper() + .addCommands(this.baritone.getCommandManager()) + .filterPrefix(args.getString()) + .stream(); } return Stream.empty(); } diff --git a/src/api/java/baritone/api/utils/command/manager/CommandManager.java b/src/main/java/baritone/utils/command/manager/CommandManager.java similarity index 57% rename from src/api/java/baritone/api/utils/command/manager/CommandManager.java rename to src/main/java/baritone/utils/command/manager/CommandManager.java index 8203ce45..6c016b46 100644 --- a/src/api/java/baritone/api/utils/command/manager/CommandManager.java +++ b/src/main/java/baritone/utils/command/manager/CommandManager.java @@ -15,31 +15,44 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.manager; +package baritone.utils.command.manager; +import baritone.Baritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import baritone.api.utils.command.manager.ICommandManager; import baritone.api.utils.command.registry.Registry; +import baritone.utils.command.defaults.DefaultCommands; import com.mojang.realmsclient.util.Pair; import java.util.List; import java.util.Locale; import java.util.stream.Stream; -import static java.util.Objects.isNull; +/** + * @author Brady + * @since 9/21/2019 + */ +public class CommandManager implements ICommandManager { -public class CommandManager { + private final Registry registry = new Registry<>(); + private final Baritone baritone; - public static final Registry REGISTRY = new Registry<>(); + public CommandManager(Baritone baritone) { + this.baritone = baritone; + DefaultCommands.commands(baritone).forEach(this.registry::register); + } - /** - * @param name The command name to search for. - * @return The command, if found. - */ - public static Command getCommand(String name) { - for (Command command : REGISTRY.entries) { + @Override + public Registry getRegistry() { + return this.registry; + } + + @Override + public Command getCommand(String name) { + for (Command command : this.registry.entries) { if (command.names.contains(name.toLowerCase(Locale.US))) { return command; } @@ -47,34 +60,39 @@ public class CommandManager { return null; } - public static void execute(CommandExecution execution) { + @Override + public void execute(CommandExecution execution) { execution.execute(); } - public static boolean execute(String string) { - CommandExecution execution = CommandExecution.from(string); + @Override + public boolean execute(String string) { + CommandExecution execution = CommandExecution.from(this, string); if (execution != null) { execution.execute(); } return execution != null; } - public static Stream tabComplete(CommandExecution execution) { + @Override + public Stream tabComplete(CommandExecution execution) { return execution.tabComplete(); } - public static Stream tabComplete(Pair> pair) { - CommandExecution execution = CommandExecution.from(pair); - return isNull(execution) ? Stream.empty() : tabComplete(execution); + @Override + public Stream tabComplete(Pair> pair) { + CommandExecution execution = CommandExecution.from(this, pair); + return execution == null ? Stream.empty() : tabComplete(execution); } - public static Stream tabComplete(String prefix) { + @Override + public Stream tabComplete(String prefix) { Pair> pair = CommandExecution.expand(prefix, true); String label = pair.first(); List args = pair.second(); if (args.isEmpty()) { return new TabCompleteHelper() - .addCommands() + .addCommands(this.baritone.getCommandManager()) .filterPrefix(label) .stream(); } else { From e4353e489fccb7b8592442c53445fb3eb6891bd6 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 21 Sep 2019 17:11:15 -0500 Subject: [PATCH 656/682] Get rid of default implementation of IArgParser --- .../utils/command/argparser/ArgParser.java | 54 ------- .../command/argparser/ArgParserManager.java | 32 ++-- .../command/argparser/DefaultArgParsers.java | 49 +++--- .../utils/command/argparser/IArgParser.java | 4 +- .../command/argument/CommandArgument.java | 11 +- .../utils/command/datatypes/IDatatype.java | 4 +- .../helpers/arguments/ArgConsumer.java | 140 +++++++++--------- 7 files changed, 120 insertions(+), 174 deletions(-) delete mode 100644 src/api/java/baritone/api/utils/command/argparser/ArgParser.java diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParser.java b/src/api/java/baritone/api/utils/command/argparser/ArgParser.java deleted file mode 100644 index 6fcd5468..00000000 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParser.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.api.utils.command.argparser; - -public abstract class ArgParser implements IArgParser { - - private final Class target; - - private ArgParser(Class target) { - this.target = target; - } - - @Override - public Class getTarget() { - return target; - } - - public static abstract class Stateless extends ArgParser implements IArgParser.Stateless { - - public Stateless(Class target) { - super(target); - } - } - - public static abstract class Stated extends ArgParser implements IArgParser.Stated { - - private final Class stateType; - - protected Stated(Class target, Class stateType) { - super(target); - this.stateType = stateType; - } - - @Override - public Class getStateType() { - return stateType; - } - } -} diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index 447e8f1b..24f5fec0 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -25,7 +25,7 @@ import baritone.api.utils.command.registry.Registry; public class ArgParserManager { - public static final Registry REGISTRY = new Registry<>(); + public static final Registry REGISTRY = new Registry<>(); static { DefaultArgParsers.ALL.forEach(REGISTRY::register); @@ -35,11 +35,11 @@ public class ArgParserManager { * @param type The type trying to be parsed * @return A parser that can parse arguments into this class, if found. */ - public static ArgParser.Stateless getParserStateless(Class type) { + public static IArgParser.Stateless getParserStateless(Class type) { //noinspection unchecked return REGISTRY.descendingStream() - .filter(ArgParser.Stateless.class::isInstance) - .map(ArgParser.Stateless.class::cast) + .filter(IArgParser.Stateless.class::isInstance) + .map(IArgParser.Stateless.class::cast) .filter(parser -> parser.getTarget().isAssignableFrom(type)) .findFirst() .orElse(null); @@ -49,20 +49,20 @@ public class ArgParserManager { * @param type The type trying to be parsed * @return A parser that can parse arguments into this class, if found. */ - public static ArgParser.Stated getParserStated(Class type, Class stateKlass) { + public static IArgParser.Stated getParserStated(Class type, Class stateKlass) { //noinspection unchecked return REGISTRY.descendingStream() - .filter(ArgParser.Stated.class::isInstance) - .map(ArgParser.Stated.class::cast) + .filter(IArgParser.Stated.class::isInstance) + .map(IArgParser.Stated.class::cast) .filter(parser -> parser.getTarget().isAssignableFrom(type)) .filter(parser -> parser.getStateType().isAssignableFrom(stateKlass)) - .map(ArgParser.Stated.class::cast) + .map(IArgParser.Stated.class::cast) .findFirst() .orElse(null); } /** - * Attempt to parse the specified argument with a stateless {@link ArgParser} that outputs the specified class. + * Attempt to parse the specified argument with a stateless {@link IArgParser} that outputs the specified class. * * @param type The type to try and parse the argument into. * @param arg The argument to parse. @@ -70,37 +70,37 @@ public class ArgParserManager { * @throws CommandInvalidTypeException If the parsing failed */ public static T parseStateless(Class type, CommandArgument arg) throws CommandInvalidTypeException { - ArgParser.Stateless parser = getParserStateless(type); + IArgParser.Stateless parser = getParserStateless(type); if (parser == null) { // TODO: Fix this scuff lol throw new CommandUnhandledException(new CommandNoParserForTypeException(type)); } try { return parser.parseArg(arg); - } catch (RuntimeException exc) { + } catch (Exception exc) { throw new CommandInvalidTypeException(arg, type.getSimpleName()); } } /** - * Attempt to parse the specified argument with a stated {@link ArgParser} that outputs the specified class. + * Attempt to parse the specified argument with a stated {@link IArgParser} that outputs the specified class. * * @param type The type to try and parse the argument into. * @param arg The argument to parse. - * @param state The state to pass to the {@link ArgParser.Stated}. + * @param state The state to pass to the {@link IArgParser.Stated}. * @return An instance of the specified class. * @throws CommandInvalidTypeException If the parsing failed - * @see ArgParser.Stated + * @see IArgParser.Stated */ public static T parseStated(Class type, Class stateKlass, CommandArgument arg, S state) throws CommandInvalidTypeException { - ArgParser.Stated parser = getParserStated(type, stateKlass); + IArgParser.Stated parser = getParserStated(type, stateKlass); if (parser == null) { // TODO: Fix this scuff lol throw new CommandUnhandledException(new CommandNoParserForTypeException(type)); } try { return parser.parseArg(arg, state); - } catch (RuntimeException exc) { + } catch (Exception exc) { throw new CommandInvalidTypeException(arg, type.getSimpleName()); } } diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index 35110999..c33f61fb 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -25,12 +25,12 @@ import java.util.Locale; public class DefaultArgParsers { - public static class IntArgumentParser extends ArgParser.Stateless { + public enum IntArgumentParser implements IArgParser.Stateless { + INSTANCE; - public static final IntArgumentParser INSTANCE = new IntArgumentParser(); - - public IntArgumentParser() { - super(Integer.class); + @Override + public Class getTarget() { + return Integer.class; } @Override @@ -39,12 +39,12 @@ public class DefaultArgParsers { } } - public static class LongArgumentParser extends ArgParser.Stateless { + public enum LongArgumentParser implements IArgParser.Stateless { + INSTANCE; - public static final LongArgumentParser INSTANCE = new LongArgumentParser(); - - public LongArgumentParser() { - super(Long.class); + @Override + public Class getTarget() { + return Long.class; } @Override @@ -53,12 +53,12 @@ public class DefaultArgParsers { } } - public static class FloatArgumentParser extends ArgParser.Stateless { + public enum FloatArgumentParser implements IArgParser.Stateless { + INSTANCE; - public static final FloatArgumentParser INSTANCE = new FloatArgumentParser(); - - public FloatArgumentParser() { - super(Float.class); + @Override + public Class getTarget() { + return Float.class; } @Override @@ -71,12 +71,12 @@ public class DefaultArgParsers { } } - public static class DoubleArgumentParser extends ArgParser.Stateless { + public enum DoubleArgumentParser implements IArgParser.Stateless { + INSTANCE; - public static final DoubleArgumentParser INSTANCE = new DoubleArgumentParser(); - - public DoubleArgumentParser() { - super(Double.class); + @Override + public Class getTarget() { + return Double.class; } @Override @@ -89,14 +89,15 @@ public class DefaultArgParsers { } } - public static class BooleanArgumentParser extends ArgParser.Stateless { + public static class BooleanArgumentParser implements IArgParser.Stateless { public static final BooleanArgumentParser INSTANCE = new BooleanArgumentParser(); public static final List TRUTHY_VALUES = Arrays.asList("1", "true", "yes", "t", "y", "on", "enable"); public static final List FALSY_VALUES = Arrays.asList("0", "false", "no", "f", "n", "off", "disable"); - public BooleanArgumentParser() { - super(Boolean.class); + @Override + public Class getTarget() { + return Boolean.class; } @Override @@ -112,7 +113,7 @@ public class DefaultArgParsers { } } - public static final List> ALL = Arrays.asList( + public static final List> ALL = Arrays.asList( IntArgumentParser.INSTANCE, LongArgumentParser.INSTANCE, FloatArgumentParser.INSTANCE, diff --git a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java index 568955af..09e2aa2e 100644 --- a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java +++ b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java @@ -39,7 +39,7 @@ public interface IArgParser { * @throws RuntimeException if you want the parsing to fail. The exception will be caught and turned into an * appropriate error. */ - T parseArg(CommandArgument arg) throws RuntimeException; + T parseArg(CommandArgument arg) throws Exception; } /** @@ -59,6 +59,6 @@ public interface IArgParser { * @throws RuntimeException if you want the parsing to fail. The exception will be caught and turned into an * appropriate error. */ - T parseArg(CommandArgument arg, S state) throws RuntimeException; + T parseArg(CommandArgument arg, S state) throws Exception; } } diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index 2914f707..ccffadf5 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -17,11 +17,10 @@ package baritone.api.utils.command.argument; -import baritone.api.utils.command.argparser.ArgParser; import baritone.api.utils.command.argparser.ArgParserManager; +import baritone.api.utils.command.argparser.IArgParser; import baritone.api.utils.command.exception.CommandInvalidArgumentException; import baritone.api.utils.command.exception.CommandInvalidTypeException; -import baritone.api.utils.command.exception.CommandNoParserForTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.util.EnumFacing; @@ -74,7 +73,7 @@ public class CommandArgument { } /** - * Tries to use a stateless {@link ArgParser} to parse this argument into the specified class + * Tries to use a stateless {@link IArgParser} to parse this argument into the specified class * * @param type The class to parse this argument into * @return An instance of the specified type @@ -85,7 +84,7 @@ public class CommandArgument { } /** - * Tries to use a stateless {@link ArgParser} to parse this argument into the specified class + * Tries to use a stateless {@link IArgParser} to parse this argument into the specified class * * @param type The class to parse this argument into * @return If the parser succeeded @@ -100,7 +99,7 @@ public class CommandArgument { } /** - * Tries to use a stated {@link ArgParser} to parse this argument into the specified class + * Tries to use a stated {@link IArgParser} to parse this argument into the specified class * * @param type The class to parse this argument into * @return An instance of the specified type @@ -112,7 +111,7 @@ public class CommandArgument { } /** - * Tries to use a stated {@link ArgParser} to parse this argument into the specified class + * Tries to use a stated {@link IArgParser} to parse this argument into the specified class * * @param type The class to parse this argument into * @return If the parser succeeded diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java index a3cf07a4..0ed74d7d 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java @@ -17,7 +17,7 @@ package baritone.api.utils.command.datatypes; -import baritone.api.utils.command.argparser.ArgParser; +import baritone.api.utils.command.argparser.IArgParser; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidArgumentException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; @@ -34,7 +34,7 @@ import java.util.stream.Stream; public interface IDatatype { /** - * One benefit over datatypes over {@link ArgParser}s is that instead of each command trying to guess what values + * One benefit over datatypes over {@link IArgParser}s is that instead of each command trying to guess what values * the datatype will accept, or simply not tab completing at all, datatypes that support tab completion can provide * accurate information using the same methods used to parse arguments in the first place. *

    diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index 55df9866..a8c55721 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -19,7 +19,7 @@ package baritone.api.utils.command.helpers.arguments; import baritone.api.utils.Helper; import baritone.api.utils.command.Command; -import baritone.api.utils.command.argparser.ArgParser; +import baritone.api.utils.command.argparser.IArgParser; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.datatypes.IDatatype; import baritone.api.utils.command.datatypes.IDatatypeFor; @@ -269,18 +269,18 @@ public class ArgConsumer { } /** - * Tries to use a stateless {@link ArgParser} to parse the argument at the specified index into the specified + * Tries to use a stateless {@link IArgParser} to parse the argument at the specified index into the specified * class *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param type The type to peek as * @param index The index to peek * @return An instance of the specified type * @throws CommandInvalidTypeException If the parsing failed - * @see ArgParser + * @see IArgParser * @see #peekAs(Class) * @see #peekAsOrDefault(Class, Object, int) * @see #peekAsOrNull(Class, int) @@ -290,16 +290,16 @@ public class ArgConsumer { } /** - * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param type The type to peek as * @return An instance of the specified type * @throws CommandInvalidTypeException If the parsing failed - * @see ArgParser + * @see IArgParser * @see #peekAs(Class, int) * @see #peekAsOrDefault(Class, Object) * @see #peekAsOrNull(Class) @@ -309,18 +309,18 @@ public class ArgConsumer { } /** - * Tries to use a stateless {@link ArgParser} to parse the argument at the specified index into the specified + * Tries to use a stateless {@link IArgParser} to parse the argument at the specified index into the specified * class *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param type The type to peek as * @param def The value to return if the argument can't be parsed * @param index The index to peek * @return An instance of the specified type, or {@code def} if it couldn't be parsed - * @see ArgParser + * @see IArgParser * @see #peekAsOrDefault(Class, Object) * @see #peekAs(Class, int) * @see #peekAsOrNull(Class, int) @@ -334,16 +334,16 @@ public class ArgConsumer { } /** - * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param type The type to peek as * @param def The value to return if the argument can't be parsed * @return An instance of the specified type, or {@code def} if it couldn't be parsed - * @see ArgParser + * @see IArgParser * @see #peekAsOrDefault(Class, Object, int) * @see #peekAs(Class) * @see #peekAsOrNull(Class) @@ -353,17 +353,17 @@ public class ArgConsumer { } /** - * Tries to use a stateless {@link ArgParser} to parse the argument at the specified index into the specified + * Tries to use a stateless {@link IArgParser} to parse the argument at the specified index into the specified * class *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param type The type to peek as * @param index The index to peek * @return An instance of the specified type, or {@code null} if it couldn't be parsed - * @see ArgParser + * @see IArgParser * @see #peekAsOrNull(Class) * @see #peekAs(Class, int) * @see #peekAsOrDefault(Class, Object, int) @@ -373,15 +373,15 @@ public class ArgConsumer { } /** - * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param type The type to peek as * @return An instance of the specified type, or {@code null} if it couldn't be parsed - * @see ArgParser + * @see IArgParser * @see #peekAsOrNull(Class, int) * @see #peekAs(Class) * @see #peekAsOrDefault(Class, Object) @@ -393,8 +393,8 @@ public class ArgConsumer { /** * Attempts to get the specified datatype from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. @@ -410,8 +410,8 @@ public class ArgConsumer { /** * Attempts to get the specified datatype from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. @@ -427,8 +427,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. @@ -445,8 +445,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. @@ -464,8 +464,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. @@ -482,8 +482,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. @@ -500,8 +500,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. @@ -519,8 +519,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. @@ -619,16 +619,16 @@ public class ArgConsumer { } /** - * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param type The type to peek as * @return An instance of the specified type * @throws CommandInvalidTypeException If the parsing failed - * @see ArgParser + * @see IArgParser * @see #get() * @see #getAsOrDefault(Class, Object) * @see #getAsOrNull(Class) @@ -641,16 +641,16 @@ public class ArgConsumer { } /** - * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param type The type to peek as * @param def The default value * @return An instance of the specified type, or {@code def} if it couldn't be parsed - * @see ArgParser + * @see IArgParser * @see #get() * @see #getAs(Class) * @see #getAsOrNull(Class) @@ -669,15 +669,15 @@ public class ArgConsumer { } /** - * Tries to use a stateless {@link ArgParser} to parse the next argument into the specified class + * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param type The type to peek as * @return An instance of the specified type, or {@code null} if it couldn't be parsed - * @see ArgParser + * @see IArgParser * @see #get() * @see #getAs(Class) * @see #getAsOrDefault(Class, Object) @@ -692,8 +692,8 @@ public class ArgConsumer { /** * Attempts to get the specified datatype from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param datatype The datatype to get @@ -713,8 +713,8 @@ public class ArgConsumer { /** * Attempts to get the specified datatype from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. @@ -740,8 +740,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param datatype The datatype to get @@ -756,8 +756,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. @@ -785,8 +785,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. @@ -803,8 +803,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. * * @param datatype The datatype to get @@ -819,8 +819,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. @@ -848,8 +848,8 @@ public class ArgConsumer { /** * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer *

    - * A critical difference between {@link IDatatype}s and {@link ArgParser}s is how many arguments they can take. - * While {@link ArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire + * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. + * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire * {@link ArgConsumer}. *

    * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. @@ -864,7 +864,7 @@ public class ArgConsumer { } /** - * One benefit over datatypes over {@link ArgParser}s is that instead of each command trying to guess what values + * One benefit over datatypes over {@link IArgParser}s is that instead of each command trying to guess what values * the datatype will accept, or simply not tab completing at all, datatypes that support tab completion can provide * accurate information using the same methods used to parse arguments in the first place. *

    From 204f9d2e31ccd3014f4737b2b6ca8296fb0a6eaf Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 21 Sep 2019 17:25:20 -0500 Subject: [PATCH 657/682] Fix redundant Stream.of usage --- .../java/baritone/api/utils/command/BaritoneChatControl.java | 4 ++-- .../java/baritone/utils/command/defaults/GoalCommand.java | 2 +- src/main/java/baritone/utils/command/defaults/SetCommand.java | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index 4fbd93ab..5a54d4eb 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -194,9 +194,9 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (setting.getValueClass() == Boolean.class) { TabCompleteHelper helper = new TabCompleteHelper(); if ((Boolean) setting.value) { - helper.append(Stream.of("true", "false")); + helper.append("true", "false"); } else { - helper.append(Stream.of("false", "true")); + helper.append("false", "true"); } return helper.filterPrefix(argc.getString()).stream(); } else { diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index 23065deb..6ba7a995 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -63,7 +63,7 @@ public class GoalCommand extends Command { protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { TabCompleteHelper helper = new TabCompleteHelper(); if (args.hasExactlyOne()) { - helper.append(Stream.of("reset", "clear", "none", "~")); + helper.append("reset", "clear", "none", "~"); } else { if (args.hasAtMost(3)) { while (args.has(2)) { diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index f3baeeb2..f55b213b 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -207,9 +207,9 @@ public class SetCommand extends Command { if (setting.getType() == Boolean.class) { TabCompleteHelper helper = new TabCompleteHelper(); if ((Boolean) setting.value) { - helper.append(Stream.of("true", "false")); + helper.append("true", "false"); } else { - helper.append(Stream.of("false", "true")); + helper.append("false", "true"); } return helper.filterPrefix(args.getString()).stream(); } else { From 376c93bd3bb6993515caf7110c4d7db8660dc5aa Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 21 Sep 2019 17:37:13 -0500 Subject: [PATCH 658/682] Consistent Stream.of usage over Arrays.stream --- .../api/utils/BlockOptionalMetaLookup.java | 5 +++-- .../command/argument/CommandArgument.java | 3 ++- .../command/datatypes/ForEnumFacing.java | 2 +- .../utils/command/datatypes/ForWaypoints.java | 4 ++-- .../utils/command/datatypes/RelativeFile.java | 2 +- .../exception/CommandUnhandledException.java | 3 ++- .../tabcomplete/TabCompleteHelper.java | 21 +++---------------- 7 files changed, 14 insertions(+), 26 deletions(-) diff --git a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java index 705800b8..041c6162 100644 --- a/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java +++ b/src/api/java/baritone/api/utils/BlockOptionalMetaLookup.java @@ -23,6 +23,7 @@ import net.minecraft.item.ItemStack; import java.util.Arrays; import java.util.List; +import java.util.stream.Stream; public class BlockOptionalMetaLookup { @@ -33,7 +34,7 @@ public class BlockOptionalMetaLookup { } public BlockOptionalMetaLookup(Block... blocks) { - this.boms = Arrays.stream(blocks) + this.boms = Stream.of(blocks) .map(BlockOptionalMeta::new) .toArray(BlockOptionalMeta[]::new); } @@ -45,7 +46,7 @@ public class BlockOptionalMetaLookup { } public BlockOptionalMetaLookup(String... blocks) { - this.boms = Arrays.stream(blocks) + this.boms = Stream.of(blocks) .map(BlockOptionalMeta::new) .toArray(BlockOptionalMeta[]::new); } diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index ccffadf5..c86e8c42 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -29,6 +29,7 @@ import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Stream; /** * A {@link CommandArgument} is an immutable object representing one command argument. It contains data on the index of @@ -66,7 +67,7 @@ public class CommandArgument { * @see ArgConsumer#getEnumOrNull(Class) */ public > E getEnum(Class enumClass) throws CommandInvalidTypeException { - return Arrays.stream(enumClass.getEnumConstants()) + return Stream.of(enumClass.getEnumConstants()) .filter(e -> e.name().equalsIgnoreCase(value)) .findFirst() .orElseThrow(() -> new CommandInvalidTypeException(this, enumClass.getSimpleName())); diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java index b8ee355a..aa11e21f 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java @@ -48,7 +48,7 @@ public class ForEnumFacing implements IDatatypeFor { public Stream tabComplete(ArgConsumer consumer) throws CommandException { return new TabCompleteHelper() .append( - Arrays.stream(EnumFacing.values()) + Stream.of(EnumFacing.values()) .map(EnumFacing::getName) .map(String::toLowerCase) ) diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java index 04717952..747614a5 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -76,7 +76,7 @@ public class ForWaypoints implements IDatatypeFor { } public static String[] getWaypointNames() { - return Arrays.stream(getWaypoints()) + return Stream.of(getWaypoints()) .map(IWaypoint::getName) .filter(name -> !name.isEmpty()) .toArray(String[]::new); @@ -89,7 +89,7 @@ public class ForWaypoints implements IDatatypeFor { } public static IWaypoint[] getWaypointsByName(String name) { - return Arrays.stream(getWaypoints()) + return Stream.of(getWaypoints()) .filter(waypoint -> waypoint.getName().equalsIgnoreCase(name)) .toArray(IWaypoint[]::new); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index a02f1fc5..22efc984 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -82,7 +82,7 @@ public class RelativeFile implements IDatatypePost { Path basePath = currentPath.isAbsolute() ? currentPath.getRoot() : base.toPath(); boolean useParent = !currentPathStringThing.isEmpty() && !currentPathStringThing.endsWith(File.separator); File currentFile = currentPath.isAbsolute() ? currentPath.toFile() : new File(base, currentPathStringThing); - return Arrays.stream(Objects.requireNonNull(getCanonicalFileUnchecked( + return Stream.of(Objects.requireNonNull(getCanonicalFileUnchecked( useParent ? currentFile.getParentFile() : currentFile diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java index 0ff822ad..08f39ecd 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -22,6 +22,7 @@ import java.io.StringWriter; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +import java.util.stream.Stream; public class CommandUnhandledException extends RuntimeException implements ICommandException { @@ -39,7 +40,7 @@ public class CommandUnhandledException extends RuntimeException implements IComm } private static String getBaritoneStackTrace(String stackTrace) { - List lines = Arrays.stream(stackTrace.split("\n")) + List lines = Stream.of(stackTrace.split("\n")) .collect(Collectors.toList()); int lastBaritoneLine = 0; for (int i = 0; i < lines.size(); i++) { diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index b5a5eba3..c76cc609 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -57,7 +57,7 @@ public class TabCompleteHelper { private Stream stream; public TabCompleteHelper(String[] base) { - stream = Arrays.stream(base); + stream = Stream.of(base); } public TabCompleteHelper(List base) { @@ -75,9 +75,6 @@ public class TabCompleteHelper { * @return This {@link TabCompleteHelper} after having appended the stream * @see #append(String...) * @see #append(Class) - * @see #prepend(Stream) - * @see #prepend(String...) - * @see #prepend(Class) */ public TabCompleteHelper append(Stream source) { stream = Stream.concat(stream, source); @@ -91,9 +88,6 @@ public class TabCompleteHelper { * @return This {@link TabCompleteHelper} after having appended the strings * @see #append(Stream) * @see #append(Class) - * @see #prepend(Stream) - * @see #prepend(String...) - * @see #prepend(Class) */ public TabCompleteHelper append(String... source) { return append(Stream.of(source)); @@ -106,13 +100,10 @@ public class TabCompleteHelper { * @return This {@link TabCompleteHelper} after having appended the values * @see #append(Stream) * @see #append(String...) - * @see #prepend(Stream) - * @see #prepend(String...) - * @see #prepend(Class) */ public TabCompleteHelper append(Class> num) { return append( - Arrays.stream(num.getEnumConstants()) + Stream.of(num.getEnumConstants()) .map(Enum::name) .map(String::toLowerCase) ); @@ -123,9 +114,6 @@ public class TabCompleteHelper { * * @param source The stream to prepend * @return This {@link TabCompleteHelper} after having prepended the stream - * @see #append(Stream) - * @see #append(String...) - * @see #append(Class) * @see #prepend(String...) * @see #prepend(Class) */ @@ -154,15 +142,12 @@ public class TabCompleteHelper { * * @param num The enum to prepend the values of * @return This {@link TabCompleteHelper} after having prepended the values - * @see #append(Stream) - * @see #append(String...) - * @see #append(Class) * @see #prepend(Stream) * @see #prepend(String...) */ public TabCompleteHelper prepend(Class> num) { return prepend( - Arrays.stream(num.getEnumConstants()) + Stream.of(num.getEnumConstants()) .map(Enum::name) .map(String::toLowerCase) ); From 9ffca6ad66e0f5c6ab11d775d6c5f140c6ae13b9 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 21 Sep 2019 17:45:53 -0500 Subject: [PATCH 659/682] Minor javadoc tidy up --- .../utils/command/helpers/tabcomplete/TabCompleteHelper.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index c76cc609..784b53f5 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -127,9 +127,6 @@ public class TabCompleteHelper { * * @param source The stream to prepend * @return This {@link TabCompleteHelper} after having prepended the strings - * @see #append(Stream) - * @see #append(String...) - * @see #append(Class) * @see #prepend(Stream) * @see #prepend(Class) */ From 7292245b554a49e2098d5517f9934d309ad3e14f Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 22 Sep 2019 14:41:30 -0500 Subject: [PATCH 660/682] Rename PlayerByUsername to NearbyPlayer --- .../{PlayerByUsername.java => NearbyPlayer.java} | 11 ++++++++--- .../utils/command/defaults/FollowCommand.java | 5 ++--- 2 files changed, 10 insertions(+), 6 deletions(-) rename src/api/java/baritone/api/utils/command/datatypes/{PlayerByUsername.java => NearbyPlayer.java} (86%) diff --git a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java b/src/api/java/baritone/api/utils/command/datatypes/NearbyPlayer.java similarity index 86% rename from src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java rename to src/api/java/baritone/api/utils/command/datatypes/NearbyPlayer.java index 0912c74d..b3411587 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/PlayerByUsername.java +++ b/src/api/java/baritone/api/utils/command/datatypes/NearbyPlayer.java @@ -18,6 +18,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; @@ -26,17 +27,21 @@ import net.minecraft.entity.player.EntityPlayer; import java.util.List; import java.util.stream.Stream; -public class PlayerByUsername implements IDatatypeFor { +/** + * An {@link IDatatype} used to resolve nearby players, those within + * render distance of the target {@link IBaritone} instance. + */ +public class NearbyPlayer implements IDatatypeFor { private final List players = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().playerEntities; public final EntityPlayer player; - public PlayerByUsername() { + public NearbyPlayer() { player = null; } - public PlayerByUsername(ArgConsumer consumer) throws CommandException { + public NearbyPlayer(ArgConsumer consumer) throws CommandException { String username = consumer.getString(); player = players .stream() diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index b22613b9..6f3dc0b6 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -18,12 +18,11 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.EntityClassById; import baritone.api.utils.command.datatypes.IDatatype; import baritone.api.utils.command.datatypes.IDatatypeFor; -import baritone.api.utils.command.datatypes.PlayerByUsername; +import baritone.api.utils.command.datatypes.NearbyPlayer; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; @@ -147,7 +146,7 @@ public class FollowCommand extends Command { private enum FollowList { ENTITY(EntityClassById.class), - PLAYER(PlayerByUsername.class); + PLAYER(NearbyPlayer.class); final Class datatype; FollowList(Class datatype) { From 9f271b1f442c70425a136031bad2f32dc0048874 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 25 Sep 2019 18:27:47 -0500 Subject: [PATCH 661/682] Future-compatibility for multiple Baritone instances --- .../baritone/api/utils/IPlayerController.java | 18 +++++--- .../java/baritone/utils/BlockBreakHelper.java | 43 ++++++++----------- .../java/baritone/utils/BlockPlaceHelper.java | 2 +- .../utils/player/PrimaryPlayerController.java | 27 +++++++++--- 4 files changed, 52 insertions(+), 38 deletions(-) diff --git a/src/api/java/baritone/api/utils/IPlayerController.java b/src/api/java/baritone/api/utils/IPlayerController.java index 14334d5e..05199fca 100644 --- a/src/api/java/baritone/api/utils/IPlayerController.java +++ b/src/api/java/baritone/api/utils/IPlayerController.java @@ -35,21 +35,27 @@ import net.minecraft.world.World; */ public interface IPlayerController { + void syncHeldItem(); + + boolean hasBrokenBlock(); + boolean onPlayerDamageBlock(BlockPos pos, EnumFacing side); void resetBlockRemoving(); ItemStack windowClick(int windowId, int slotId, int mouseButton, ClickType type, EntityPlayer player); - void setGameType(GameType type); - GameType getGameType(); - default double getBlockReachDistance() { - return this.getGameType().isCreative() ? 5.0F : 4.5F; - } - EnumActionResult processRightClickBlock(EntityPlayerSP player, World world, BlockPos pos, EnumFacing direction, Vec3d vec, EnumHand hand); EnumActionResult processRightClick(EntityPlayerSP player, World world, EnumHand hand); + + boolean clickBlock(BlockPos loc, EnumFacing face); + + void setHittingBlock(boolean hittingBlock); + + default double getBlockReachDistance() { + return this.getGameType().isCreative() ? 5.0F : 4.5F; + } } diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index 7f8ada84..d1f3509e 100644 --- a/src/main/java/baritone/utils/BlockBreakHelper.java +++ b/src/main/java/baritone/utils/BlockBreakHelper.java @@ -19,11 +19,7 @@ package baritone.utils; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; -import baritone.utils.accessor.IPlayerControllerMP; -import net.minecraft.client.Minecraft; -import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; /** @@ -32,49 +28,46 @@ import net.minecraft.util.math.RayTraceResult; */ public final class BlockBreakHelper implements Helper { + private final IPlayerContext ctx; private boolean didBreakLastTick; - private final IPlayerContext playerContext; - - public BlockBreakHelper(IPlayerContext playerContext) { - this.playerContext = playerContext; - } - - private void tryBreakBlock(BlockPos pos, EnumFacing side) { - if (playerContext.playerController().onPlayerDamageBlock(pos, side)) { - playerContext.player().swingArm(EnumHand.MAIN_HAND); - } + BlockBreakHelper(IPlayerContext ctx) { + this.ctx = ctx; } public void stopBreakingBlock() { // The player controller will never be null, but the player can be - if (playerContext.player() != null && didBreakLastTick) { - if (((IPlayerControllerMP) mc.playerController).getCurrentBlock().getY() != -1) { + if (ctx.player() != null && didBreakLastTick) { + if (!ctx.playerController().hasBrokenBlock()) { // insane bypass to check breaking succeeded - ((IPlayerControllerMP) mc.playerController).setIsHittingBlock(true); + ctx.playerController().setHittingBlock(true); } - playerContext.playerController().resetBlockRemoving(); + ctx.playerController().resetBlockRemoving(); didBreakLastTick = false; } } - public void tick(boolean isLeftClick) { - RayTraceResult trace = playerContext.objectMouseOver(); + RayTraceResult trace = ctx.objectMouseOver(); boolean isBlockTrace = trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK; if (isLeftClick && isBlockTrace) { if (!didBreakLastTick) { - ((IPlayerControllerMP) Minecraft.getMinecraft().playerController).callSyncCurrentPlayItem(); - Minecraft.getMinecraft().playerController.clickBlock(trace.getBlockPos(), trace.sideHit); - playerContext.player().swingArm(EnumHand.MAIN_HAND); + ctx.playerController().syncHeldItem(); + ctx.playerController().clickBlock(trace.getBlockPos(), trace.sideHit); + ctx.player().swingArm(EnumHand.MAIN_HAND); } - tryBreakBlock(trace.getBlockPos(), trace.sideHit); + + // Attempt to break the block + if (ctx.playerController().onPlayerDamageBlock(trace.getBlockPos(), trace.sideHit)) { + ctx.player().swingArm(EnumHand.MAIN_HAND); + } + didBreakLastTick = true; } else if (didBreakLastTick) { stopBreakingBlock(); didBreakLastTick = false; } - ((IPlayerControllerMP) Minecraft.getMinecraft().playerController).setIsHittingBlock(false); + ctx.playerController().setHittingBlock(false); } } diff --git a/src/main/java/baritone/utils/BlockPlaceHelper.java b/src/main/java/baritone/utils/BlockPlaceHelper.java index ee8f2b73..06588c12 100644 --- a/src/main/java/baritone/utils/BlockPlaceHelper.java +++ b/src/main/java/baritone/utils/BlockPlaceHelper.java @@ -28,7 +28,7 @@ public class BlockPlaceHelper implements Helper { private final IPlayerContext ctx; private int rightClickTimer; - public BlockPlaceHelper(IPlayerContext playerContext) { + BlockPlaceHelper(IPlayerContext playerContext) { this.ctx = playerContext; } diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerController.java b/src/main/java/baritone/utils/player/PrimaryPlayerController.java index 120f996c..b013f916 100644 --- a/src/main/java/baritone/utils/player/PrimaryPlayerController.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerController.java @@ -19,6 +19,7 @@ package baritone.utils.player; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerController; +import baritone.utils.accessor.IPlayerControllerMP; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; @@ -42,6 +43,16 @@ public enum PrimaryPlayerController implements IPlayerController, Helper { INSTANCE; + @Override + public void syncHeldItem() { + ((IPlayerControllerMP) mc.playerController).callSyncCurrentPlayItem(); + } + + @Override + public boolean hasBrokenBlock() { + return ((IPlayerControllerMP) mc.playerController).getCurrentBlock().getY() == -1; + } + @Override public boolean onPlayerDamageBlock(BlockPos pos, EnumFacing side) { return mc.playerController.onPlayerDamageBlock(pos, side); @@ -57,11 +68,6 @@ public enum PrimaryPlayerController implements IPlayerController, Helper { return mc.playerController.windowClick(windowId, slotId, mouseButton, type, player); } - @Override - public void setGameType(GameType type) { - mc.playerController.setGameType(type); - } - @Override public GameType getGameType() { return mc.playerController.getCurrentGameType(); @@ -69,7 +75,6 @@ public enum PrimaryPlayerController implements IPlayerController, Helper { @Override public EnumActionResult processRightClickBlock(EntityPlayerSP player, World world, BlockPos pos, EnumFacing direction, Vec3d vec, EnumHand hand) { - // primaryplayercontroller is always in a WorldClient so this is ok return mc.playerController.processRightClickBlock(player, (WorldClient) world, pos, direction, vec, hand); } @@ -77,4 +82,14 @@ public enum PrimaryPlayerController implements IPlayerController, Helper { public EnumActionResult processRightClick(EntityPlayerSP player, World world, EnumHand hand) { return mc.playerController.processRightClick(player, world, hand); } + + @Override + public boolean clickBlock(BlockPos loc, EnumFacing face) { + return mc.playerController.clickBlock(loc, face); + } + + @Override + public void setHittingBlock(boolean hittingBlock) { + ((IPlayerControllerMP) mc.playerController).setIsHittingBlock(hittingBlock); + } } From 595f5a35e04b554d66aa7b8582ecc220d2962d76 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 26 Sep 2019 18:49:26 -0500 Subject: [PATCH 662/682] Datatype Singletons --- .../baritone/api/utils/BetterBlockPos.java | 2 + .../utils/command/BaritoneChatControl.java | 28 +- .../utils/command/datatypes/BlockById.java | 25 +- .../command/datatypes/EntityClassById.java | 29 +- .../datatypes/ForBlockOptionalMeta.java | 24 +- .../command/datatypes/ForEnumFacing.java | 31 +- .../utils/command/datatypes/ForWaypoints.java | 63 ++- .../utils/command/datatypes/IDatatype.java | 15 +- .../command/datatypes/IDatatypeContext.java | 47 +++ .../utils/command/datatypes/IDatatypeFor.java | 4 +- .../command/datatypes/IDatatypePost.java | 13 +- .../datatypes/IDatatypePostFunction.java | 29 ++ .../utils/command/datatypes/NearbyPlayer.java | 46 +- .../command/datatypes/RelativeBlockPos.java | 39 +- .../command/datatypes/RelativeCoordinate.java | 38 +- .../utils/command/datatypes/RelativeFile.java | 27 +- .../utils/command/datatypes/RelativeGoal.java | 56 +-- .../command/datatypes/RelativeGoalBlock.java | 33 +- .../command/datatypes/RelativeGoalXZ.java | 29 +- .../command/datatypes/RelativeGoalYLevel.java | 27 +- .../command/execution/CommandExecution.java | 2 +- .../helpers/arguments/ArgConsumer.java | 395 +++++------------- .../command/manager/ICommandManager.java | 3 + .../utils/command/defaults/BuildCommand.java | 6 +- .../command/defaults/ClearareaCommand.java | 4 +- .../command/defaults/ExploreCommand.java | 4 +- .../defaults/ExploreFilterCommand.java | 2 +- .../utils/command/defaults/FindCommand.java | 4 +- .../utils/command/defaults/FollowCommand.java | 12 +- .../utils/command/defaults/GoalCommand.java | 4 +- .../utils/command/defaults/MineCommand.java | 5 +- .../utils/command/defaults/PathCommand.java | 4 +- .../utils/command/defaults/SelCommand.java | 16 +- .../command/defaults/WaypointsCommand.java | 20 +- .../utils/command/manager/CommandManager.java | 6 + 35 files changed, 447 insertions(+), 645 deletions(-) create mode 100644 src/api/java/baritone/api/utils/command/datatypes/IDatatypeContext.java create mode 100644 src/api/java/baritone/api/utils/command/datatypes/IDatatypePostFunction.java diff --git a/src/api/java/baritone/api/utils/BetterBlockPos.java b/src/api/java/baritone/api/utils/BetterBlockPos.java index dd986dee..a9b02445 100644 --- a/src/api/java/baritone/api/utils/BetterBlockPos.java +++ b/src/api/java/baritone/api/utils/BetterBlockPos.java @@ -35,6 +35,8 @@ import javax.annotation.Nonnull; */ public final class BetterBlockPos extends BlockPos { + public static final BetterBlockPos ORIGIN = new BetterBlockPos(0, 0, 0); + public final int x; public final int y; public final int z; diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java index 5a54d4eb..0c1b9fb9 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/api/java/baritone/api/utils/command/BaritoneChatControl.java @@ -25,7 +25,6 @@ import baritone.api.event.events.ChatEvent; import baritone.api.event.events.TabCompleteEvent; import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.utils.Helper; -import baritone.api.utils.IPlayerContext; import baritone.api.utils.SettingsUtil; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; @@ -33,6 +32,7 @@ import baritone.api.utils.command.exception.CommandNotFoundException; import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; +import baritone.api.utils.command.manager.ICommandManager; import com.mojang.realmsclient.util.Pair; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; @@ -49,9 +49,8 @@ import java.util.stream.Stream; public class BaritoneChatControl implements Helper, AbstractGameEventListener { - public final IBaritone baritone; - public final IPlayerContext ctx; - public final Settings settings = BaritoneAPI.getSettings(); + private static final Settings settings = BaritoneAPI.getSettings(); + private final ICommandManager manager; /** * In certain cases chat components need to execute commands for you. For example, the paginator automatically runs @@ -67,8 +66,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { public static String FORCE_COMMAND_PREFIX = String.format("<<%s>>", UUID.randomUUID().toString()); public BaritoneChatControl(IBaritone baritone) { - this.baritone = baritone; - this.ctx = baritone.getPlayerContext(); + this.manager = baritone.getCommandManager(); baritone.getGameEventHandler().registerEventListener(this); } @@ -123,15 +121,15 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { Pair> pair = CommandExecution.expand(msg); String command = pair.first(); String rest = msg.substring(pair.first().length()); - ArgConsumer argc = new ArgConsumer(pair.second()); + ArgConsumer argc = new ArgConsumer(this.manager, pair.second()); if (!argc.hasAny()) { Settings.Setting setting = settings.byLowerName.get(command.toLowerCase(Locale.US)); if (setting != null) { logRanCommand(command, rest); if (setting.getValueClass() == Boolean.class) { - this.baritone.getCommandManager().execute(String.format("set toggle %s", setting.getName())); + this.manager.execute(String.format("set toggle %s", setting.getName())); } else { - this.baritone.getCommandManager().execute(String.format("set %s", setting.getName())); + this.manager.execute(String.format("set %s", setting.getName())); } return true; } @@ -143,18 +141,18 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (setting.getName().equalsIgnoreCase(pair.first())) { logRanCommand(command, rest); try { - this.baritone.getCommandManager().execute(String.format("set %s %s", setting.getName(), argc.getString())); + this.manager.execute(String.format("set %s %s", setting.getName(), argc.getString())); } catch (CommandNotEnoughArgumentsException ignored) {} // The operation is safe return true; } } } - CommandExecution execution = CommandExecution.from(this.baritone.getCommandManager(), pair); + CommandExecution execution = CommandExecution.from(this.manager, pair); if (execution == null) { return false; } logRanCommand(command, rest); - this.baritone.getCommandManager().execute(execution); + this.manager.execute(execution); return true; } @@ -180,11 +178,11 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { public Stream tabComplete(String msg) { try { List args = CommandArgument.from(msg, true); - ArgConsumer argc = new ArgConsumer(args); + ArgConsumer argc = new ArgConsumer(this.manager, args); if (argc.hasAtMost(2)) { if (argc.hasExactly(1)) { return new TabCompleteHelper() - .addCommands(this.baritone.getCommandManager()) + .addCommands(this.manager) .addSettings() .filterPrefix(argc.getString()) .stream(); @@ -204,7 +202,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } } } - return this.baritone.getCommandManager().tabComplete(msg); + return this.manager.tabComplete(msg); } catch (CommandNotEnoughArgumentsException ignored) { // Shouldn't happen, the operation is safe return Stream.empty(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java index 4733c67d..ae659adc 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/BlockById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/BlockById.java @@ -18,8 +18,6 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.block.Block; import net.minecraft.init.Blocks; @@ -27,35 +25,28 @@ import net.minecraft.util.ResourceLocation; import java.util.stream.Stream; -public class BlockById implements IDatatypeFor { +public enum BlockById implements IDatatypeFor { + INSTANCE; - public final Block block; - - public BlockById() { - block = null; - } - - public BlockById(ArgConsumer consumer) throws CommandNotEnoughArgumentsException { - ResourceLocation id = new ResourceLocation(consumer.getString()); + @Override + public Block get(IDatatypeContext ctx) throws CommandException { + ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString()); + Block block; if ((block = Block.REGISTRY.getObject(id)) == Blocks.AIR) { throw new IllegalArgumentException("no block found by that id"); } - } - - @Override - public Block get() { return block; } @Override - public Stream tabComplete(ArgConsumer consumer) throws CommandException { + public Stream tabComplete(IDatatypeContext ctx) throws CommandException { return new TabCompleteHelper() .append( Block.REGISTRY.getKeys() .stream() .map(Object::toString) ) - .filterPrefixNamespaced(consumer.getString()) + .filterPrefixNamespaced(ctx.getConsumer().getString()) .sortAlphabetically() .stream(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java index 62a80ba7..321558e2 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java @@ -26,35 +26,24 @@ import net.minecraft.util.ResourceLocation; import java.util.stream.Stream; -public class EntityClassById implements IDatatypeFor> { +public enum EntityClassById implements IDatatypeFor> { + INSTANCE; - public final Class entity; - - public EntityClassById() { - entity = null; - } - - public EntityClassById(ArgConsumer consumer) throws CommandException { - ResourceLocation id = new ResourceLocation(consumer.getString()); + @Override + public Class get(IDatatypeContext ctx) throws CommandException { + ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString()); + Class entity; if ((entity = EntityList.REGISTRY.getObject(id)) == null) { throw new IllegalArgumentException("no entity found by that id"); } - } - - @Override - public Class get() { return entity; } @Override - public Stream tabComplete(ArgConsumer consumer) throws CommandException { + public Stream tabComplete(IDatatypeContext ctx) throws CommandException { return new TabCompleteHelper() - .append( - EntityList.getEntityNameList() - .stream() - .map(Object::toString) - ) - .filterPrefixNamespaced(consumer.getString()) + .append(EntityList.getEntityNameList().stream().map(Object::toString)) + .filterPrefixNamespaced(ctx.getConsumer().getString()) .sortAlphabetically() .stream(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java b/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java index 85f2ca61..f36826c6 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForBlockOptionalMeta.java @@ -19,29 +19,19 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; -public class ForBlockOptionalMeta implements IDatatypeFor { +public enum ForBlockOptionalMeta implements IDatatypeFor { + INSTANCE; - public final BlockOptionalMeta selector; - - public ForBlockOptionalMeta() { - selector = null; - } - - public ForBlockOptionalMeta(ArgConsumer consumer) throws CommandException { - selector = new BlockOptionalMeta(consumer.getString()); + @Override + public BlockOptionalMeta get(IDatatypeContext ctx) throws CommandException { + return new BlockOptionalMeta(ctx.getConsumer().getString()); } @Override - public BlockOptionalMeta get() { - return selector; - } - - @Override - public Stream tabComplete(ArgConsumer consumer) { - return consumer.tabCompleteDatatype(BlockById.class); + public Stream tabComplete(IDatatypeContext ctx) { + return ctx.getConsumer().tabCompleteDatatype(BlockById.INSTANCE); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java index aa11e21f..5cfe3918 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java @@ -23,36 +23,23 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.util.EnumFacing; -import java.util.Arrays; import java.util.Locale; import java.util.stream.Stream; -public class ForEnumFacing implements IDatatypeFor { +public enum ForEnumFacing implements IDatatypeFor { + INSTANCE; - private final EnumFacing facing; - - public ForEnumFacing() { - facing = null; - } - - public ForEnumFacing(ArgConsumer consumer) throws CommandNotEnoughArgumentsException { - facing = EnumFacing.valueOf(consumer.getString().toUpperCase(Locale.US)); + @Override + public EnumFacing get(IDatatypeContext ctx) throws CommandException { + return EnumFacing.valueOf(ctx.getConsumer().getString().toUpperCase(Locale.US)); } @Override - public EnumFacing get() { - return facing; - } - - @Override - public Stream tabComplete(ArgConsumer consumer) throws CommandException { + public Stream tabComplete(IDatatypeContext ctx) throws CommandException { return new TabCompleteHelper() - .append( - Stream.of(EnumFacing.values()) - .map(EnumFacing::getName) - .map(String::toLowerCase) - ) - .filterPrefix(consumer.getString()) + .append(Stream.of(EnumFacing.values()) + .map(EnumFacing::getName).map(String::toLowerCase)) + .filterPrefix(ctx.getConsumer().getString()) .stream(); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java index 747614a5..e60ff0c6 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForWaypoints.java @@ -17,79 +17,64 @@ package baritone.api.utils.command.datatypes; -import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; import baritone.api.cache.IWaypoint; import baritone.api.cache.IWaypointCollection; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; -import java.util.Arrays; import java.util.Comparator; import java.util.stream.Stream; -public class ForWaypoints implements IDatatypeFor { +public enum ForWaypoints implements IDatatypeFor { + INSTANCE; - private final IWaypoint[] waypoints; + @Override + public IWaypoint[] get(IDatatypeContext ctx) throws CommandException { + final String input = ctx.getConsumer().getString(); + final IWaypoint.Tag tag = IWaypoint.Tag.getByName(input); - public ForWaypoints() { - waypoints = null; - } - - public ForWaypoints(String arg) { - IWaypoint.Tag tag = IWaypoint.Tag.getByName(arg); - waypoints = tag == null ? getWaypointsByName(arg) : getWaypointsByTag(tag); - } - - public ForWaypoints(ArgConsumer consumer) throws CommandNotEnoughArgumentsException { - this(consumer.getString()); + // If the input doesn't resolve to a valid tag, resolve by name + return tag == null + ? getWaypointsByName(ctx.getBaritone(), input) + : getWaypointsByTag(ctx.getBaritone(), tag); } @Override - public IWaypoint[] get() { - return waypoints; - } - - @Override - public Stream tabComplete(ArgConsumer consumer) throws CommandException { + public Stream tabComplete(IDatatypeContext ctx) throws CommandException { return new TabCompleteHelper() - .append(getWaypointNames()) + .append(getWaypointNames(ctx.getBaritone())) .sortAlphabetically() .prepend(IWaypoint.Tag.getAllNames()) - .filterPrefix(consumer.getString()) + .filterPrefix(ctx.getConsumer().getString()) .stream(); } - public static IWaypointCollection waypoints() { - return BaritoneAPI.getProvider() - .getPrimaryBaritone() - .getWorldProvider() - .getCurrentWorld() - .getWaypoints(); + public static IWaypointCollection waypoints(IBaritone baritone) { + return baritone.getWorldProvider().getCurrentWorld().getWaypoints(); } - public static IWaypoint[] getWaypoints() { - return waypoints().getAllWaypoints().stream() + public static IWaypoint[] getWaypoints(IBaritone baritone) { + return waypoints(baritone).getAllWaypoints().stream() .sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed()) .toArray(IWaypoint[]::new); } - public static String[] getWaypointNames() { - return Stream.of(getWaypoints()) + public static String[] getWaypointNames(IBaritone baritone) { + return Stream.of(getWaypoints(baritone)) .map(IWaypoint::getName) .filter(name -> !name.isEmpty()) .toArray(String[]::new); } - public static IWaypoint[] getWaypointsByTag(IWaypoint.Tag tag) { - return waypoints().getByTag(tag).stream() + public static IWaypoint[] getWaypointsByTag(IBaritone baritone, IWaypoint.Tag tag) { + return waypoints(baritone).getByTag(tag).stream() .sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed()) .toArray(IWaypoint[]::new); } - public static IWaypoint[] getWaypointsByName(String name) { - return Stream.of(getWaypoints()) + public static IWaypoint[] getWaypointsByName(IBaritone baritone, String name) { + return Stream.of(getWaypoints(baritone)) .filter(waypoint -> waypoint.getName().equalsIgnoreCase(name)) .toArray(IWaypoint[]::new); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java index 0ed74d7d..2a0696f2 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java @@ -19,17 +19,14 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.argparser.IArgParser; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.exception.CommandInvalidArgumentException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; /** - * Since interfaces cannot enforce the presence of a constructor, it's on you to make sure there is a constructor that - * accepts a single {@link ArgConsumer} argument. The constructor will perform all needed validation, and {@link - * ArgConsumer#getDatatype(Class)} will handle RuntimeExceptions and translate them into {@link - * CommandInvalidArgumentException}s. There must always be a constructor with no arguments so that {@link ArgConsumer} - * can create an instance for tab completion. + * @see IDatatypeContext + * @see IDatatypeFor + * @see IDatatypePost */ public interface IDatatype { @@ -41,9 +38,9 @@ public interface IDatatype { * See {@link RelativeFile} for a very advanced example of tab completion. You wouldn't want this pasted into every * command that uses files - right? Right? * - * @param consumer The argument consumer to tab complete + * @param ctx The argument consumer to tab complete * @return A stream representing the strings that can be tab completed. DO NOT INCLUDE SPACES IN ANY STRINGS. - * @see ArgConsumer#tabCompleteDatatype(Class) + * @see ArgConsumer#tabCompleteDatatype(IDatatype) */ - Stream tabComplete(ArgConsumer consumer) throws CommandException; + Stream tabComplete(IDatatypeContext ctx) throws CommandException; } diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeContext.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeContext.java new file mode 100644 index 00000000..1452bf4a --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeContext.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.utils.command.datatypes; + +import baritone.api.IBaritone; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; + +/** + * Provides an {@link IDatatype} with contextual information so + * that it can perform the desired operation on the target level. + * + * @see IDatatype + * + * @author Brady + * @since 9/26/2019 + */ +public interface IDatatypeContext { + + /** + * Provides the {@link IBaritone} instance that is associated with the action relating to datatype handling. + * + * @return The context {@link IBaritone} instance. + */ + IBaritone getBaritone(); + + /** + * Provides the {@link ArgConsumer} to fetch input information from. + * + * @return The context {@link ArgConsumer}. + */ + ArgConsumer getConsumer(); +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java index 126e73b2..3168702a 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java @@ -17,7 +17,9 @@ package baritone.api.utils.command.datatypes; +import baritone.api.utils.command.exception.CommandException; + public interface IDatatypeFor extends IDatatype { - T get(); + T get(IDatatypeContext ctx) throws CommandException; } diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java index 6b6e10b1..3e1e70be 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java @@ -17,7 +17,18 @@ package baritone.api.utils.command.datatypes; +import baritone.api.utils.command.exception.CommandException; + public interface IDatatypePost extends IDatatype { - T apply(O original); + /** + * Takes the expected input and transforms it based on the value held by {@code original}. If {@code original} + * is null, it is expected that the implementation of this method has a case to handle it, such that a + * {@link NullPointerException} will never be thrown as a result. + * + * @param ctx The datatype context + * @param original The transformable value + * @return The transformed value + */ + T apply(IDatatypeContext ctx, O original) throws CommandException; } diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypePostFunction.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePostFunction.java new file mode 100644 index 00000000..a3de089e --- /dev/null +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePostFunction.java @@ -0,0 +1,29 @@ +/* + * 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.command.datatypes; + +import baritone.api.utils.command.exception.CommandException; + +/** + * @author Brady + * @since 9/26/2019 + */ +public interface IDatatypePostFunction { + + T apply(O original) throws CommandException; +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/NearbyPlayer.java b/src/api/java/baritone/api/utils/command/datatypes/NearbyPlayer.java index b3411587..78450e1a 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/NearbyPlayer.java +++ b/src/api/java/baritone/api/utils/command/datatypes/NearbyPlayer.java @@ -17,10 +17,8 @@ package baritone.api.utils.command.datatypes; -import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.entity.player.EntityPlayer; @@ -31,43 +29,27 @@ import java.util.stream.Stream; * An {@link IDatatype} used to resolve nearby players, those within * render distance of the target {@link IBaritone} instance. */ -public class NearbyPlayer implements IDatatypeFor { +public enum NearbyPlayer implements IDatatypeFor { + INSTANCE; - private final List players = - BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().playerEntities; - public final EntityPlayer player; - - public NearbyPlayer() { - player = null; - } - - public NearbyPlayer(ArgConsumer consumer) throws CommandException { - String username = consumer.getString(); - player = players - .stream() + @Override + public EntityPlayer get(IDatatypeContext ctx) throws CommandException { + final String username = ctx.getConsumer().getString(); + return getPlayers(ctx).stream() .filter(s -> s.getName().equalsIgnoreCase(username)) - .findFirst() - .orElse(null); - if (player == null) { - throw new IllegalArgumentException("no player found by that username"); - } + .findFirst().orElse(null); } @Override - public EntityPlayer get() { - return player; - } - - @Override - public Stream tabComplete(ArgConsumer consumer) throws CommandException { + public Stream tabComplete(IDatatypeContext ctx) throws CommandException { return new TabCompleteHelper() - .append( - players - .stream() - .map(EntityPlayer::getName) - ) - .filterPrefix(consumer.getString()) + .append(getPlayers(ctx).stream().map(EntityPlayer::getName)) + .filterPrefix(ctx.getConsumer().getString()) .sortAlphabetically() .stream(); } + + private static List getPlayers(IDatatypeContext ctx) { + return ctx.getBaritone().getPlayerContext().world().playerEntities; + } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java index 0f7ffb4f..8459db88 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java @@ -23,43 +23,34 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; -public class RelativeBlockPos implements IDatatypePost { - - final RelativeCoordinate x; - final RelativeCoordinate y; - final RelativeCoordinate z; - - public RelativeBlockPos() { - x = null; - y = null; - z = null; - } - - public RelativeBlockPos(ArgConsumer consumer) throws CommandException { - x = consumer.getDatatype(RelativeCoordinate.class); - y = consumer.getDatatype(RelativeCoordinate.class); - z = consumer.getDatatype(RelativeCoordinate.class); - } +public enum RelativeBlockPos implements IDatatypePost { + INSTANCE; @Override - public BetterBlockPos apply(BetterBlockPos origin) { + public BetterBlockPos apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException { + if (origin == null) { + origin = BetterBlockPos.ORIGIN; + } + + final ArgConsumer consumer = ctx.getConsumer(); return new BetterBlockPos( - x.apply((double) origin.x), - y.apply((double) origin.y), - z.apply((double) origin.z) + consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x), + consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y), + consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.z) ); } @Override - public Stream tabComplete(ArgConsumer consumer) throws CommandException { + public Stream tabComplete(IDatatypeContext ctx) throws CommandException { + final ArgConsumer consumer = ctx.getConsumer(); if (consumer.hasAny() && !consumer.has(4)) { while (consumer.has(2)) { - if (consumer.peekDatatypeOrNull(RelativeCoordinate.class) == null) { + if (consumer.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) == null) { break; } consumer.get(); } - return consumer.tabCompleteDatatype(RelativeCoordinate.class); + return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE); } return Stream.empty(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java index 7e234711..239c54a7 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java @@ -18,7 +18,6 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.util.math.MathHelper; @@ -26,40 +25,37 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; -public class RelativeCoordinate implements IDatatypePost { +public enum RelativeCoordinate implements IDatatypePost { + INSTANCE; - public static Pattern PATTERN = Pattern.compile("^(~?)([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$"); - final boolean isRelative; - final double offset; + private static Pattern PATTERN = Pattern.compile("^(~?)([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$"); - public RelativeCoordinate() { - isRelative = true; - offset = 0; - } + @Override + public Double apply(IDatatypeContext ctx, Double origin) throws CommandException { + if (origin == null) { + origin = 0.0D; + } - public RelativeCoordinate(ArgConsumer consumer) throws CommandNotEnoughArgumentsException { - Matcher matcher = PATTERN.matcher(consumer.getString()); + System.out.println(ctx.getConsumer().args); + new Throwable().printStackTrace(); + + Matcher matcher = PATTERN.matcher(ctx.getConsumer().getString()); if (!matcher.matches()) { throw new IllegalArgumentException("pattern doesn't match"); } - isRelative = !matcher.group(1).isEmpty(); - offset = matcher.group(2).isEmpty() ? 0 : Double.parseDouble(matcher.group(2)); - } - @Override - public Double apply(Double origin) { + boolean isRelative = !matcher.group(1).isEmpty(); + double offset = matcher.group(2).isEmpty() ? 0 : Double.parseDouble(matcher.group(2)); + if (isRelative) { return origin + offset; } return offset; } - public int applyFloor(double origin) { - return MathHelper.floor(apply(origin)); - } - @Override - public Stream tabComplete(ArgConsumer consumer) throws CommandException { + public Stream tabComplete(IDatatypeContext ctx) throws CommandException { + final ArgConsumer consumer = ctx.getConsumer(); if (!consumer.has(2) && consumer.getString().matches("^(~|$)")) { return Stream.of("~"); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index 22efc984..71a9ca58 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -18,7 +18,6 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.io.File; @@ -27,31 +26,32 @@ import java.io.UncheckedIOException; import java.nio.file.FileSystems; import java.nio.file.InvalidPathException; import java.nio.file.Path; -import java.util.Arrays; import java.util.Locale; import java.util.Objects; import java.util.stream.Stream; import static baritone.api.utils.Helper.HELPER; -public class RelativeFile implements IDatatypePost { +public enum RelativeFile implements IDatatypePost { + INSTANCE; - private final Path path; + @Override + public File apply(IDatatypeContext ctx, File original) throws CommandException { + if (original == null) { + original = new File("./"); + } - public RelativeFile() { - path = null; - } - - public RelativeFile(ArgConsumer consumer) throws CommandNotEnoughArgumentsException { + Path path; try { - path = FileSystems.getDefault().getPath(consumer.getString()); + path = FileSystems.getDefault().getPath(ctx.getConsumer().getString()); } catch (InvalidPathException e) { throw new IllegalArgumentException("invalid path"); } + return getCanonicalFileUnchecked(original.toPath().resolve(path).toFile()); } @Override - public Stream tabComplete(ArgConsumer consumer) { + public Stream tabComplete(IDatatypeContext ctx) { return Stream.empty(); } @@ -93,11 +93,6 @@ public class RelativeFile implements IDatatypePost { .filter(s -> !s.contains(" ")); } - @Override - public File apply(File original) { - return getCanonicalFileUnchecked(original.toPath().resolve(path).toFile()); - } - public static File gameDir() { File gameDir = HELPER.mc.gameDir.getAbsoluteFile(); if (gameDir.getName().equals(".")) { diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java index 943c0732..d47e05ce 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java @@ -24,56 +24,56 @@ import baritone.api.pathing.goals.GoalYLevel; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.util.math.MathHelper; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; -public class RelativeGoal implements IDatatypePost { - - final RelativeCoordinate[] coords; - - public RelativeGoal() { - coords = new RelativeCoordinate[0]; - } - - public RelativeGoal(ArgConsumer consumer) throws CommandException { - List coordsList = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - if (consumer.peekDatatypeOrNull(RelativeCoordinate.class) != null) { - coordsList.add(consumer.getDatatype(RelativeCoordinate.class)); - } - } - coords = coordsList.toArray(new RelativeCoordinate[0]); - } +public enum RelativeGoal implements IDatatypePost { + INSTANCE; @Override - public Goal apply(BetterBlockPos origin) { - switch (coords.length) { + public Goal apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException { + if (origin == null) { + origin = BetterBlockPos.ORIGIN; + } + final ArgConsumer consumer = ctx.getConsumer(); + + List> coords = new ArrayList<>(); + final ArgConsumer copy = consumer.copy(); // This is a hack and should be fixed in the future probably + for (int i = 0; i < 3; i++) { + if (copy.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) != null) { + coords.add(o -> consumer.getDatatypePost(RelativeCoordinate.INSTANCE, o)); + copy.get(); // Consume so we actually decrement the remaining arguments + } + } + + switch (coords.size()) { case 0: return new GoalBlock(origin); case 1: return new GoalYLevel( - coords[0].applyFloor(origin.y) + MathHelper.floor(coords.get(0).apply((double) origin.y)) ); case 2: return new GoalXZ( - coords[0].applyFloor(origin.x), - coords[1].applyFloor(origin.z) + MathHelper.floor(coords.get(0).apply((double) origin.x)), + MathHelper.floor(coords.get(1).apply((double) origin.z)) ); case 3: return new GoalBlock( - coords[0].applyFloor(origin.x), - coords[1].applyFloor(origin.y), - coords[2].applyFloor(origin.z) + MathHelper.floor(coords.get(0).apply((double) origin.x)), + MathHelper.floor(coords.get(1).apply((double) origin.y)), + MathHelper.floor(coords.get(2).apply((double) origin.z)) ); default: - throw new IllegalStateException("Unexpected coords size: " + coords.length); + throw new IllegalStateException("Unexpected coords size: " + coords.size()); } } @Override - public Stream tabComplete(ArgConsumer consumer) { - return consumer.tabCompleteDatatype(RelativeCoordinate.class); + public Stream tabComplete(IDatatypeContext ctx) { + return ctx.getConsumer().tabCompleteDatatype(RelativeCoordinate.INSTANCE); } } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java index f368d62e..a1ca7cf4 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java @@ -20,40 +20,29 @@ package baritone.api.utils.command.datatypes; import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.util.math.MathHelper; import java.util.stream.Stream; -public class RelativeGoalBlock implements IDatatypePost { - - final RelativeCoordinate[] coords; - - public RelativeGoalBlock() { - coords = new RelativeCoordinate[0]; - } - - public RelativeGoalBlock(ArgConsumer consumer) throws CommandException { - coords = new RelativeCoordinate[]{ - consumer.getDatatype(RelativeCoordinate.class), - consumer.getDatatype(RelativeCoordinate.class), - consumer.getDatatype(RelativeCoordinate.class) - }; - } +public enum RelativeGoalBlock implements IDatatypePost { + INSTANCE; @Override - public GoalBlock apply(BetterBlockPos origin) { + public GoalBlock apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException { + final ArgConsumer consumer = ctx.getConsumer(); return new GoalBlock( - coords[0].applyFloor(origin.x), - coords[1].applyFloor(origin.y), - coords[2].applyFloor(origin.z) + MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x)), + MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y)), + MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.z)) ); } @Override - public Stream tabComplete(ArgConsumer consumer) { + public Stream tabComplete(IDatatypeContext ctx) { + final ArgConsumer consumer = ctx.getConsumer(); if (consumer.hasAtMost(3)) { - return consumer.tabCompleteDatatype(RelativeCoordinate.class); + return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE); } return Stream.empty(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java index dd672f64..1c82a6e1 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java @@ -21,36 +21,27 @@ import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.util.math.MathHelper; import java.util.stream.Stream; -public class RelativeGoalXZ implements IDatatypePost { - - final RelativeCoordinate[] coords; - - public RelativeGoalXZ() { - coords = new RelativeCoordinate[0]; - } - - public RelativeGoalXZ(ArgConsumer consumer) throws CommandException { - coords = new RelativeCoordinate[]{ - consumer.getDatatype(RelativeCoordinate.class), - consumer.getDatatype(RelativeCoordinate.class) - }; - } +public enum RelativeGoalXZ implements IDatatypePost { + INSTANCE; @Override - public GoalXZ apply(BetterBlockPos origin) { + public GoalXZ apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException { + final ArgConsumer consumer = ctx.getConsumer(); return new GoalXZ( - coords[0].applyFloor(origin.x), - coords[1].applyFloor(origin.z) + MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x)), + MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y)) ); } @Override - public Stream tabComplete(ArgConsumer consumer) { + public Stream tabComplete(IDatatypeContext ctx) { + final ArgConsumer consumer = ctx.getConsumer(); if (consumer.hasAtMost(2)) { - return consumer.tabCompleteDatatype(RelativeCoordinate.class); + return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE); } return Stream.empty(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java index 126565da..e383f181 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java @@ -21,30 +21,25 @@ import baritone.api.pathing.goals.GoalYLevel; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.util.math.MathHelper; import java.util.stream.Stream; -public class RelativeGoalYLevel implements IDatatypePost { +public enum RelativeGoalYLevel implements IDatatypePost { + INSTANCE; - final RelativeCoordinate coord; - - public RelativeGoalYLevel() { - coord = null; - } - - public RelativeGoalYLevel(ArgConsumer consumer) throws CommandException { - coord = consumer.getDatatype(RelativeCoordinate.class); + @Override + public GoalYLevel apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException { + return new GoalYLevel( + MathHelper.floor(ctx.getConsumer().getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y)) + ); } @Override - public GoalYLevel apply(BetterBlockPos origin) { - return new GoalYLevel(coord.applyFloor(origin.y)); - } - - @Override - public Stream tabComplete(ArgConsumer consumer) { + public Stream tabComplete(IDatatypeContext ctx) { + final ArgConsumer consumer = ctx.getConsumer(); if (consumer.hasAtMost(1)) { - return consumer.tabCompleteDatatype(RelativeCoordinate.class); + return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE); } return Stream.empty(); } diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java index 26370fe8..8a23757d 100644 --- a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java +++ b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java @@ -93,7 +93,7 @@ public class CommandExecution { } public static CommandExecution from(ICommandManager manager, Pair> pair) { - return from(manager, pair.first(), new ArgConsumer(pair.second())); + return from(manager, pair.first(), new ArgConsumer(manager, pair.second())); } public static CommandExecution from(ICommandManager manager, String string) { diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index a8c55721..f9aef7be 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -17,15 +17,14 @@ package baritone.api.utils.command.helpers.arguments; +import baritone.api.IBaritone; import baritone.api.utils.Helper; import baritone.api.utils.command.Command; import baritone.api.utils.command.argparser.IArgParser; import baritone.api.utils.command.argument.CommandArgument; -import baritone.api.utils.command.datatypes.IDatatype; -import baritone.api.utils.command.datatypes.IDatatypeFor; -import baritone.api.utils.command.datatypes.IDatatypePost; -import baritone.api.utils.command.datatypes.RelativeFile; +import baritone.api.utils.command.datatypes.*; import baritone.api.utils.command.exception.*; +import baritone.api.utils.command.manager.ICommandManager; import net.minecraft.util.EnumFacing; import java.lang.reflect.InvocationTargetException; @@ -56,22 +55,39 @@ import java.util.stream.Stream; */ public class ArgConsumer { + /** + * The parent {@link ICommandManager} for this {@link ArgConsumer}. Used by {@link #context}. + */ + private final ICommandManager manager; + + /** + * The {@link IDatatypeContext} instance for this {@link ArgConsumer}, passed to + * datatypes when an operation is performed upon them. + * + * @see IDatatype + * @see IDatatypeContext + */ + private final IDatatypeContext context; + /** * The list of arguments in this ArgConsumer */ public final LinkedList args; + /** * The list of consumed arguments for this ArgConsumer. The most recently consumed argument is the last one */ public final Deque consumed; - private ArgConsumer(Deque args, Deque consumed) { + private ArgConsumer(ICommandManager manager, Deque args, Deque consumed) { + this.manager = manager; + this.context = this.new Context(); this.args = new LinkedList<>(args); this.consumed = new LinkedList<>(consumed); } - public ArgConsumer(List args) { - this(new LinkedList<>(args), new LinkedList<>()); + public ArgConsumer(ICommandManager manager, List args) { + this(manager, new LinkedList<>(args), new LinkedList<>()); } /** @@ -156,9 +172,6 @@ public class ArgConsumer { * @see #peek(int) * @see #peekString() * @see #peekAs(Class) - * @see #peekDatatype(Class) - * @see #peekDatatypeFor(Class) - * @see #peekDatatypePost(Class, Object) * @see #get() */ public CommandArgument peek() throws CommandNotEnoughArgumentsException { @@ -390,92 +403,35 @@ public class ArgConsumer { return peekAsOrNull(type, 0); } - /** - * Attempts to get the specified datatype from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - *

    - * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. - * - * @param datatype The datatype to get - * @return The datatype instance - * @see IDatatype - */ - public T peekDatatype(Class datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return copy().getDatatype(datatype); + public T peekDatatype(IDatatypeFor datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return copy().getDatatypeFor(datatype); } - /** - * Attempts to get the specified datatype from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - *

    - * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. - * - * @param datatype The datatype to get - * @return The datatype instance, or {@code null} if it throws an exception - * @see IDatatype - */ - public T peekDatatypeOrNull(Class datatype) throws CommandNotEnoughArgumentsException { - return copy().getDatatypeOrNull(datatype); + public T peekDatatype(IDatatypePost datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return this.peekDatatype(datatype, null); } - /** - * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - *

    - * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. - * - * @param datatype The datatype to get - * @return The datatype instance - * @see IDatatype - * @see IDatatypePost - */ - public > T peekDatatypePost(Class datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + public T peekDatatype(IDatatypePost datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { return copy().getDatatypePost(datatype, original); } - /** - * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - *

    - * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. - * - * @param datatype The datatype to get - * @param def The default value - * @return The datatype instance, or {@code def} if it throws an exception - * @see IDatatype - * @see IDatatypePost - */ - public > T peekDatatypePostOrDefault(Class datatype, O original, T def) { + public T peekDatatypeOrNull(IDatatypeFor datatype) { + return copy().getDatatypeForOrNull(datatype); + } + + public T peekDatatypeOrNull(IDatatypePost datatype) { + return copy().getDatatypePostOrNull(datatype, null); + } + + public > T peekDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return copy().getDatatypePost(datatype, original); + } + + public > T peekDatatypePostOrDefault(D datatype, O original, T def) { return copy().getDatatypePostOrDefault(datatype, original, def); } - /** - * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - *

    - * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. - * - * @param datatype The datatype to get - * @return The datatype instance, or {@code null} if it throws an exception - * @see IDatatype - * @see IDatatypePost - */ - public > T peekDatatypePostOrNull(Class datatype, O original) { + public > T peekDatatypePostOrNull(D datatype, O original) { return peekDatatypePostOrDefault(datatype, original, null); } @@ -689,198 +645,65 @@ public class ArgConsumer { return getAsOrDefault(type, null); } - /** - * Attempts to get the specified datatype from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - * - * @param datatype The datatype to get - * @return The datatype instance - * @see IDatatype - */ - public T getDatatype(Class datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + public > T getDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { try { - return datatype.getConstructor(ArgConsumer.class).newInstance(this); - } catch (InvocationTargetException e) { - throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getSimpleName()); - } catch (NoSuchMethodException | IllegalAccessException | InstantiationException e) { - throw new CommandUnhandledException(e); - } - } - - /** - * Attempts to get the specified datatype from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - *

    - * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. - * - * @param datatype The datatype to get - * @return The datatype instance, or {@code null} if it throws an exception - * @see IDatatype - */ - public T getDatatypeOrNull(Class datatype) throws CommandNotEnoughArgumentsException { - List argsSnapshot = new ArrayList<>(args); - List consumedSnapshot = new ArrayList<>(consumed); - try { - return getDatatype(datatype); - } catch (CommandInvalidTypeException e) { - args.clear(); - args.addAll(argsSnapshot); - consumed.clear(); - consumed.addAll(consumedSnapshot); - return null; - } - } - - /** - * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - * - * @param datatype The datatype to get - * @return The datatype instance - * @see IDatatype - * @see IDatatypePost - */ - public > T getDatatypePost(Class datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return getDatatype(datatype).apply(original); - } - - /** - * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - *

    - * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. - * - * @param datatype The datatype to get - * @param def The default value - * @return The datatype instance, or {@code def} if it throws an exception - * @see IDatatype - * @see IDatatypePost - */ - public > T getDatatypePostOrDefault(Class datatype, O original, T def) { - List argsSnapshot = new ArrayList<>(args); - List consumedSnapshot = new ArrayList<>(consumed); - try { - return getDatatypePost(datatype, original); - } catch (CommandException e) { - args.clear(); - args.addAll(argsSnapshot); - consumed.clear(); - consumed.addAll(consumedSnapshot); - return def; - } - } - - /** - * Attempts to get the specified {@link IDatatypePost} from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - *

    - * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. - * - * @param datatype The datatype to get - * @return The datatype instance, or {@code null} if it throws an exception - * @see IDatatype - * @see IDatatypePost - */ - public > T getDatatypePostOrNull(Class datatype, O original) { - return getDatatypePostOrDefault(datatype, original, null); - } - - /** - * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - * - * @param datatype The datatype to get - * @return The datatype instance - * @see IDatatype - * @see IDatatypeFor - */ - public > T getDatatypeFor(Class datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return getDatatype(datatype).get(); - } - - /** - * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - *

    - * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. - * - * @param datatype The datatype to get - * @param def The default value - * @return The datatype instance, or {@code def} if it throws an exception - * @see IDatatype - * @see IDatatypeFor - */ - public > T getDatatypeForOrDefault(Class datatype, T def) throws CommandNotEnoughArgumentsException { - List argsSnapshot = new ArrayList<>(args); - List consumedSnapshot = new ArrayList<>(consumed); - try { - return getDatatypeFor(datatype); - } catch (CommandInvalidTypeException e) { - args.clear(); - args.addAll(argsSnapshot); - consumed.clear(); - consumed.addAll(consumedSnapshot); - return def; - } - } - - /** - * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer - *

    - * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. - * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. - *

    - * The state of this {@link ArgConsumer} is restored if the datatype could not be gotten. - * - * @param datatype The datatype to get - * @return The datatype instance, or {@code null} if it throws an exception - * @see IDatatype - * @see IDatatypeFor - */ - public > T getDatatypeForOrNull(Class datatype) throws CommandNotEnoughArgumentsException { - return getDatatypeForOrDefault(datatype, null); - } - - /** - * One benefit over datatypes over {@link IArgParser}s is that instead of each command trying to guess what values - * the datatype will accept, or simply not tab completing at all, datatypes that support tab completion can provide - * accurate information using the same methods used to parse arguments in the first place. - *

    - * See {@link RelativeFile} for a very advanced example of tab completion. You wouldn't want this pasted into every - * command that uses files - right? Right? - * - * @param datatype The datatype to get tab completions from - * @return A stream representing the strings that can be tab completed. DO NOT INCLUDE SPACES IN ANY STRINGS. - * @see IDatatype#tabComplete(ArgConsumer) - */ - public Stream tabCompleteDatatype(Class datatype) { - try { - return datatype.getConstructor().newInstance().tabComplete(this); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + return datatype.apply(this.context, original); + } catch (Exception e) { e.printStackTrace(); - } catch (CommandException ignored) {} + throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName()); + } + } + + public > T getDatatypePostOrDefault(D datatype, O original, T _default) { + final List argsSnapshot = new ArrayList<>(this.args); + final List consumedSnapshot = new ArrayList<>(this.consumed); + try { + return this.getDatatypePost(datatype, original); + } catch (Exception e) { + this.args.clear(); + this.args.addAll(argsSnapshot); + this.consumed.clear(); + this.consumed.addAll(consumedSnapshot); + return _default; + } + } + + public > T getDatatypePostOrNull(D datatype, O original) { + return this.getDatatypePostOrDefault(datatype, original, null); + } + + public > T getDatatypeFor(D datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + try { + return datatype.get(this.context); + } catch (Exception e) { + throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName()); + } + } + + public > T getDatatypeForOrDefault(D datatype, T def) { + final List argsSnapshot = new ArrayList<>(this.args); + final List consumedSnapshot = new ArrayList<>(this.consumed); + try { + return this.getDatatypeFor(datatype); + } catch (Exception e) { + this.args.clear(); + this.args.addAll(argsSnapshot); + this.consumed.clear(); + this.consumed.addAll(consumedSnapshot); + return def; + } + } + + public > T getDatatypeForOrNull(D datatype) { + return this.getDatatypeForOrDefault(datatype, null); + } + + public Stream tabCompleteDatatype(T datatype) { + try { + return datatype.tabComplete(this.context); + } catch (Exception e) { + e.printStackTrace(); + } return Stream.empty(); } @@ -972,15 +795,19 @@ public class ArgConsumer { * affect or mutate this instance. Useful for the various {@code peek} functions */ public ArgConsumer copy() { - return new ArgConsumer(args, consumed); + return new ArgConsumer(manager, args, consumed); } - /** - * @param string The string to split - * @return A new {@link ArgConsumer} constructed from the specified string - * @see CommandArgument#from(String) - */ - public static ArgConsumer from(String string) { - return new ArgConsumer(CommandArgument.from(string)); + private final class Context implements IDatatypeContext { + + @Override + public final IBaritone getBaritone() { + return ArgConsumer.this.manager.getBaritone(); + } + + @Override + public final ArgConsumer getConsumer() { + return ArgConsumer.this; + } } } diff --git a/src/api/java/baritone/api/utils/command/manager/ICommandManager.java b/src/api/java/baritone/api/utils/command/manager/ICommandManager.java index 82b085fa..2ed87a64 100644 --- a/src/api/java/baritone/api/utils/command/manager/ICommandManager.java +++ b/src/api/java/baritone/api/utils/command/manager/ICommandManager.java @@ -17,6 +17,7 @@ package baritone.api.utils.command.manager; +import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.execution.CommandExecution; @@ -32,6 +33,8 @@ import java.util.stream.Stream; */ public interface ICommandManager { + IBaritone getBaritone(); + Registry getRegistry(); /** diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index 72c065c7..e9803b02 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -44,7 +44,7 @@ public class BuildCommand extends Command { @Override protected void executed(String label, ArgConsumer args) throws CommandException { - File file = args.getDatatypePost(RelativeFile.class, schematicsDir).getAbsoluteFile(); + File file = args.getDatatypePost(RelativeFile.INSTANCE, schematicsDir).getAbsoluteFile(); if (!file.getName().toLowerCase(Locale.US).endsWith(".schematic")) { file = new File(file.getAbsolutePath() + ".schematic"); } @@ -52,7 +52,7 @@ public class BuildCommand extends Command { BetterBlockPos buildOrigin; if (args.hasAny()) { args.requireMax(3); - buildOrigin = args.getDatatype(RelativeBlockPos.class).apply(origin); + buildOrigin = args.getDatatypePost(RelativeBlockPos.INSTANCE, origin); } else { args.requireMax(0); buildOrigin = origin; @@ -70,7 +70,7 @@ public class BuildCommand extends Command { return RelativeFile.tabComplete(args, schematicsDir); } else if (args.has(2)) { args.get(); - return args.tabCompleteDatatype(RelativeBlockPos.class); + return args.tabCompleteDatatype(RelativeBlockPos.INSTANCE); } return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index 5e404180..831df5ec 100644 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -44,7 +44,7 @@ public class ClearareaCommand extends Command { BetterBlockPos pos2; if (args.hasAny()) { args.requireMax(3); - pos2 = args.getDatatype(RelativeBlockPos.class).apply(pos1); + pos2 = args.getDatatypePost(RelativeBlockPos.INSTANCE, pos1); } else { args.requireMax(0); Goal goal = baritone.getCustomGoalProcess().getGoal(); @@ -60,7 +60,7 @@ public class ClearareaCommand extends Command { @Override protected Stream tabCompleted(String label, ArgConsumer args) { - return args.tabCompleteDatatype(RelativeBlockPos.class); + return args.tabCompleteDatatype(RelativeBlockPos.INSTANCE); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index 6f844476..d3103a00 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -43,7 +43,7 @@ public class ExploreCommand extends Command { args.requireMax(0); } GoalXZ goal = args.hasAny() - ? args.getDatatypePost(RelativeGoalXZ.class, ctx.playerFeet()) + ? args.getDatatypePost(RelativeGoalXZ.INSTANCE, ctx.playerFeet()) : new GoalXZ(ctx.playerFeet()); baritone.getExploreProcess().explore(goal.getX(), goal.getZ()); logDirect(String.format("Exploring from %s", goal.toString())); @@ -52,7 +52,7 @@ public class ExploreCommand extends Command { @Override protected Stream tabCompleted(String label, ArgConsumer args) { if (args.hasAtMost(2)) { - return args.tabCompleteDatatype(RelativeGoalXZ.class); + return args.tabCompleteDatatype(RelativeGoalXZ.INSTANCE); } return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index 6deffd22..e47aec50 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -42,7 +42,7 @@ public class ExploreFilterCommand extends Command { @Override protected void executed(String label, ArgConsumer args) throws CommandException { args.requireMax(2); - File file = args.getDatatypePost(RelativeFile.class, mc.gameDir.getAbsoluteFile().getParentFile()); + File file = args.getDatatypePost(RelativeFile.INSTANCE, mc.gameDir.getAbsoluteFile().getParentFile()); boolean invert = false; if (args.hasAny()) { if (args.getString().equalsIgnoreCase("invert")) { diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index c5a808dd..b6dc3564 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -41,7 +41,7 @@ public class FindCommand extends Command { protected void executed(String label, ArgConsumer args) throws CommandException { List toFind = new ArrayList<>(); while (args.hasAny()) { - toFind.add(args.getDatatypeFor(BlockById.class)); + toFind.add(args.getDatatypeFor(BlockById.INSTANCE)); } BetterBlockPos origin = ctx.playerFeet(); toFind.stream() @@ -61,7 +61,7 @@ public class FindCommand extends Command { @Override protected Stream tabCompleted(String label, ArgConsumer args) { - return args.tabCompleteDatatype(BlockById.class); + return args.tabCompleteDatatype(BlockById.INSTANCE); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index 6f3dc0b6..28e0b91c 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -56,7 +56,6 @@ public class FollowCommand extends Command { group = null; list = args.getEnum(FollowList.class); while (args.hasAny()) { - //noinspection unchecked Object gotten = args.getDatatypeFor(list.datatype); if (gotten instanceof Class) { //noinspection unchecked @@ -98,7 +97,7 @@ public class FollowCommand extends Command { .filterPrefix(args.getString()) .stream(); } else { - Class followType; + IDatatypeFor followType; try { followType = args.getEnum(FollowList.class).datatype; } catch (NullPointerException e) { @@ -145,11 +144,12 @@ public class FollowCommand extends Command { } private enum FollowList { - ENTITY(EntityClassById.class), - PLAYER(NearbyPlayer.class); - final Class datatype; + ENTITY(EntityClassById.INSTANCE), + PLAYER(NearbyPlayer.INSTANCE); - FollowList(Class datatype) { + final IDatatypeFor datatype; + + FollowList(IDatatypeFor datatype) { this.datatype = datatype; } } diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index 6ba7a995..5484fec1 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -53,7 +53,7 @@ public class GoalCommand extends Command { } else { args.requireMax(3); BetterBlockPos origin = baritone.getPlayerContext().playerFeet(); - Goal goal = args.getDatatype(RelativeGoal.class).apply(origin); + Goal goal = args.getDatatypePost(RelativeGoal.INSTANCE, origin); goalProcess.setGoal(goal); logDirect(String.format("Goal: %s", goal.toString())); } @@ -67,7 +67,7 @@ public class GoalCommand extends Command { } else { if (args.hasAtMost(3)) { while (args.has(2)) { - if (args.peekDatatypeOrNull(RelativeCoordinate.class) == null) { + if (args.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) == null) { break; } args.get(); diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index e1b1f67b..e77c3bd7 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.BlockById; @@ -44,7 +43,7 @@ public class MineCommand extends Command { args.requireMin(1); List boms = new ArrayList<>(); while (args.hasAny()) { - boms.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); + boms.add(args.getDatatypeFor(ForBlockOptionalMeta.INSTANCE)); } WorldScanner.INSTANCE.repack(ctx); logDirect(String.format("Mining %s", boms.toString())); @@ -53,7 +52,7 @@ public class MineCommand extends Command { @Override protected Stream tabCompleted(String label, ArgConsumer args) { - return args.tabCompleteDatatype(BlockById.class); + return args.tabCompleteDatatype(BlockById.INSTANCE); } @Override diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index d1da5957..c775c231 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -46,7 +46,7 @@ public class PathCommand extends Command { Goal goal; if (args.hasAny()) { args.requireMax(3); - goal = args.getDatatype(RelativeGoal.class).apply(ctx.playerFeet()); + goal = args.getDatatypePost(RelativeGoal.INSTANCE, ctx.playerFeet()); } else if ((goal = customGoalProcess.getGoal()) == null) { throw new CommandInvalidStateException("No goal"); } @@ -60,7 +60,7 @@ public class PathCommand extends Command { protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { if (args.hasAny() && !args.has(4)) { while (args.has(2)) { - if (args.peekDatatypeOrNull(RelativeCoordinate.class) == null) { + if (args.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) == null) { break; } args.get(); diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index 362fd631..23a2b764 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -86,7 +86,7 @@ public class SelCommand extends Command { throw new CommandInvalidStateException("Set pos1 first before using pos2"); } BetterBlockPos playerPos = mc.getRenderViewEntity() != null ? BetterBlockPos.from(new BlockPos(mc.getRenderViewEntity())) : ctx.playerFeet(); - BetterBlockPos pos = args.hasAny() ? args.getDatatypePost(RelativeBlockPos.class, playerPos) : playerPos; + BetterBlockPos pos = args.hasAny() ? args.getDatatypePost(RelativeBlockPos.INSTANCE, playerPos) : playerPos; args.requireMax(0); if (action == Action.POS1) { pos1 = pos; @@ -117,16 +117,16 @@ public class SelCommand extends Command { } else if (action == Action.SET || action == Action.WALLS || action == Action.SHELL || action == Action.CLEARAREA || action == Action.REPLACE) { BlockOptionalMeta type = action == Action.CLEARAREA ? new BlockOptionalMeta(Blocks.AIR) - : args.getDatatypeFor(ForBlockOptionalMeta.class); + : args.getDatatypeFor(ForBlockOptionalMeta.INSTANCE); BlockOptionalMetaLookup replaces = null; if (action == Action.REPLACE) { args.requireMin(1); List replacesList = new ArrayList<>(); replacesList.add(type); while (args.has(2)) { - replacesList.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); + replacesList.add(args.getDatatypeFor(ForBlockOptionalMeta.INSTANCE)); } - type = args.getDatatypeFor(ForBlockOptionalMeta.class); + type = args.getDatatypeFor(ForBlockOptionalMeta.INSTANCE); replaces = new BlockOptionalMetaLookup(replacesList.toArray(new BlockOptionalMeta[0])); } else { args.requireMax(0); @@ -166,7 +166,7 @@ public class SelCommand extends Command { if (transformTarget == null) { throw new CommandInvalidStateException("Invalid transform type"); } - EnumFacing direction = args.getDatatypeFor(ForEnumFacing.class); + EnumFacing direction = args.getDatatypeFor(ForEnumFacing.INSTANCE); int blocks = args.getAs(Integer.class); ISelection[] selections = manager.getSelections(); if (selections.length < 1) { @@ -199,14 +199,14 @@ public class SelCommand extends Command { if (action != null) { if (action == Action.POS1 || action == Action.POS2) { if (args.hasAtMost(3)) { - return args.tabCompleteDatatype(RelativeBlockPos.class); + return args.tabCompleteDatatype(RelativeBlockPos.INSTANCE); } } else if (action == Action.SET || action == Action.WALLS || action == Action.CLEARAREA || action == Action.REPLACE) { if (args.hasExactlyOne() || action == Action.REPLACE) { while (args.has(2)) { args.get(); } - return args.tabCompleteDatatype(ForBlockOptionalMeta.class); + return args.tabCompleteDatatype(ForBlockOptionalMeta.INSTANCE); } } else if (action == Action.EXPAND || action == Action.CONTRACT || action == Action.SHIFT) { if (args.hasExactlyOne()) { @@ -218,7 +218,7 @@ public class SelCommand extends Command { } else { TransformTarget target = TransformTarget.getByName(args.getString()); if (target != null && args.hasExactlyOne()) { - return args.tabCompleteDatatype(ForEnumFacing.class); + return args.tabCompleteDatatype(ForEnumFacing.INSTANCE); } } } diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 6344117a..732682d4 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -96,8 +96,8 @@ public class WaypointsCommand extends Command { args.get(); } IWaypoint[] waypoints = tag != null - ? ForWaypoints.getWaypointsByTag(tag) - : ForWaypoints.getWaypoints(); + ? ForWaypoints.getWaypointsByTag(this.baritone, tag) + : ForWaypoints.getWaypoints(this.baritone); if (waypoints.length > 0) { args.requireMax(1); Paginator.paginate( @@ -132,11 +132,11 @@ public class WaypointsCommand extends Command { } String name = args.hasAny() ? args.getString() : ""; BetterBlockPos pos = args.hasAny() - ? args.getDatatypePost(RelativeBlockPos.class, ctx.playerFeet()) + ? args.getDatatypePost(RelativeBlockPos.INSTANCE, ctx.playerFeet()) : ctx.playerFeet(); args.requireMax(0); IWaypoint waypoint = new Waypoint(name, tag, pos); - ForWaypoints.waypoints().addWaypoint(waypoint); + ForWaypoints.waypoints(this.baritone).addWaypoint(waypoint); ITextComponent component = new TextComponentString("Waypoint added: "); component.getStyle().setColor(TextFormatting.GRAY); component.appendSibling(toComponent.apply(waypoint, Action.INFO)); @@ -144,13 +144,13 @@ public class WaypointsCommand extends Command { } else if (action == Action.CLEAR) { args.requireMax(1); IWaypoint.Tag tag = IWaypoint.Tag.getByName(args.getString()); - IWaypoint[] waypoints = ForWaypoints.getWaypointsByTag(tag); + IWaypoint[] waypoints = ForWaypoints.getWaypointsByTag(this.baritone, tag); for (IWaypoint waypoint : waypoints) { - ForWaypoints.waypoints().removeWaypoint(waypoint); + ForWaypoints.waypoints(this.baritone).removeWaypoint(waypoint); } logDirect(String.format("Cleared %d waypoints", waypoints.length)); } else { - IWaypoint[] waypoints = args.getDatatypeFor(ForWaypoints.class); + IWaypoint[] waypoints = args.getDatatypeFor(ForWaypoints.INSTANCE); IWaypoint waypoint = null; if (args.hasAny() && args.peekString().equals("@")) { args.requireExactly(2); @@ -230,7 +230,7 @@ public class WaypointsCommand extends Command { logDirect(goalComponent); logDirect(backComponent); } else if (action == Action.DELETE) { - ForWaypoints.waypoints().removeWaypoint(waypoint); + ForWaypoints.waypoints(this.baritone).removeWaypoint(waypoint); logDirect("That waypoint has successfully been deleted"); } else if (action == Action.GOAL) { Goal goal = new GoalBlock(waypoint.getLocation()); @@ -260,12 +260,12 @@ public class WaypointsCommand extends Command { .filterPrefix(args.getString()) .stream(); } else { - return args.tabCompleteDatatype(ForWaypoints.class); + return args.tabCompleteDatatype(ForWaypoints.INSTANCE); } } else if (args.has(3) && action == Action.SAVE) { args.get(); args.get(); - return args.tabCompleteDatatype(RelativeBlockPos.class); + return args.tabCompleteDatatype(RelativeBlockPos.INSTANCE); } } } diff --git a/src/main/java/baritone/utils/command/manager/CommandManager.java b/src/main/java/baritone/utils/command/manager/CommandManager.java index 6c016b46..7cdcea29 100644 --- a/src/main/java/baritone/utils/command/manager/CommandManager.java +++ b/src/main/java/baritone/utils/command/manager/CommandManager.java @@ -18,6 +18,7 @@ package baritone.utils.command.manager; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.execution.CommandExecution; @@ -45,6 +46,11 @@ public class CommandManager implements ICommandManager { DefaultCommands.commands(baritone).forEach(this.registry::register); } + @Override + public IBaritone getBaritone() { + return this.baritone; + } + @Override public Registry getRegistry() { return this.registry; From f8f214ca90f5065a60ac8c435f293d1b1e2bee95 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 26 Sep 2019 18:52:29 -0500 Subject: [PATCH 663/682] Fix some null substitutions --- .../api/utils/command/datatypes/RelativeGoalBlock.java | 4 ++++ .../baritone/api/utils/command/datatypes/RelativeGoalXZ.java | 4 ++++ .../api/utils/command/datatypes/RelativeGoalYLevel.java | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java index a1ca7cf4..cd1c0be1 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java @@ -30,6 +30,10 @@ public enum RelativeGoalBlock implements IDatatypePost { @Override public GoalXZ apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException { + if (origin == null) { + origin = BetterBlockPos.ORIGIN; + } + final ArgConsumer consumer = ctx.getConsumer(); return new GoalXZ( MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x)), diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java index e383f181..a8a9b232 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java @@ -30,6 +30,10 @@ public enum RelativeGoalYLevel implements IDatatypePost Date: Thu, 26 Sep 2019 18:55:15 -0500 Subject: [PATCH 664/682] Remove the special command system exclusions from proguard config --- scripts/proguard.pro | 5 ----- 1 file changed, 5 deletions(-) diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 53ab195d..4ac0f723 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -17,11 +17,6 @@ -keep class baritone.api.** { *; } # this is the keep api -# Proguard does not know the commands framework better than I do -# It needs its empty constructors and simple names to work correctly --keep class baritone.api.utils.command.** { *; } --keepclasseswithmembernames class baritone.api.utils.command.** { *; } - # service provider needs these class names -keep class baritone.BaritoneProvider -keep class baritone.api.IBaritoneProvider From 2f480fcec281e7a56bc4a343512474377f54e817 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 26 Sep 2019 18:57:08 -0500 Subject: [PATCH 665/682] BaritoneChatControl -> main --- src/main/java/baritone/BaritoneProvider.java | 2 +- src/main/java/baritone/utils/GuiClick.java | 2 +- .../java/baritone}/utils/command/BaritoneChatControl.java | 2 +- src/main/java/baritone/utils/command/defaults/HelpCommand.java | 2 +- src/main/java/baritone/utils/command/defaults/SetCommand.java | 2 +- .../java/baritone/utils/command/defaults/WaypointsCommand.java | 3 +-- 6 files changed, 6 insertions(+), 7 deletions(-) rename src/{api/java/baritone/api => main/java/baritone}/utils/command/BaritoneChatControl.java (99%) diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index e07969d6..416f1cae 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -20,7 +20,7 @@ package baritone; import baritone.api.IBaritone; import baritone.api.IBaritoneProvider; import baritone.api.cache.IWorldScanner; -import baritone.api.utils.command.BaritoneChatControl; +import baritone.utils.command.BaritoneChatControl; import baritone.cache.WorldScanner; import java.util.Collections; diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index ec8ade72..20f34fcf 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -23,7 +23,7 @@ import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Helper; -import baritone.api.utils.command.BaritoneChatControl; +import baritone.utils.command.BaritoneChatControl; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; diff --git a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java b/src/main/java/baritone/utils/command/BaritoneChatControl.java similarity index 99% rename from src/api/java/baritone/api/utils/command/BaritoneChatControl.java rename to src/main/java/baritone/utils/command/BaritoneChatControl.java index 0c1b9fb9..d62eaebf 100644 --- a/src/api/java/baritone/api/utils/command/BaritoneChatControl.java +++ b/src/main/java/baritone/utils/command/BaritoneChatControl.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command; +package baritone.utils.command; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index de2a74f0..43d9829c 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -35,7 +35,7 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; -import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; +import static baritone.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; public class HelpCommand extends Command { diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index f55b213b..822e042a 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -41,7 +41,7 @@ import java.util.stream.Stream; import static baritone.api.utils.SettingsUtil.settingTypeToString; import static baritone.api.utils.SettingsUtil.settingValueToString; -import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; +import static baritone.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; public class SetCommand extends Command { diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 732682d4..b205048b 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.cache.IWaypoint; import baritone.api.cache.Waypoint; import baritone.api.pathing.goals.Goal; @@ -44,7 +43,7 @@ import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; -import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; +import static baritone.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; public class WaypointsCommand extends Command { From 0b39b3e7b4024b430242b9155b0a184a5be97483 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 26 Sep 2019 18:59:29 -0500 Subject: [PATCH 666/682] FORCE_COMMAND_PREFIX should be exposed to the API --- .../utils/command/IBaritoneChatControl.java | 42 +++++++++++++++++++ src/main/java/baritone/utils/GuiClick.java | 4 +- .../utils/command/BaritoneChatControl.java | 16 +------ .../utils/command/defaults/HelpCommand.java | 2 +- .../utils/command/defaults/SetCommand.java | 2 +- .../command/defaults/WaypointsCommand.java | 2 +- 6 files changed, 49 insertions(+), 19 deletions(-) create mode 100644 src/api/java/baritone/api/utils/command/IBaritoneChatControl.java diff --git a/src/api/java/baritone/api/utils/command/IBaritoneChatControl.java b/src/api/java/baritone/api/utils/command/IBaritoneChatControl.java new file mode 100644 index 00000000..63b6a445 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/IBaritoneChatControl.java @@ -0,0 +1,42 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils.command; + +import baritone.api.Settings; + +import java.util.UUID; + +/** + * @author Brady + * @since 9/26/2019 + */ +public interface IBaritoneChatControl { + + /** + * In certain cases chat components need to execute commands for you. For example, the paginator automatically runs + * commands when you click the forward and back arrows to show you the previous/next page. + *

    + * If the prefix is changed in the meantime, then the command will go to chat. That's no good. So here's a permanent + * prefix that forces a command to run, regardless of the current prefix, chat/prefix control being enabled, etc. + *

    + * If used right (by both developers and users), it should be impossible to expose a command accidentally to the + * server. As a rule of thumb, if you have a clickable chat component, always use this prefix. If you're suggesting + * a command (a component that puts text into your text box, or something else), use {@link Settings#prefix}. + */ + String FORCE_COMMAND_PREFIX = String.format("<<%s>>", UUID.randomUUID().toString()); +} diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index 20f34fcf..fc97605f 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -23,7 +23,6 @@ import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Helper; -import baritone.utils.command.BaritoneChatControl; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; @@ -45,6 +44,7 @@ import java.nio.IntBuffer; import java.util.Collections; import static org.lwjgl.opengl.GL11.*; +import static baritone.api.utils.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX; public class GuiClick extends GuiScreen { @@ -88,7 +88,7 @@ public class GuiClick extends GuiScreen { .setColor(TextFormatting.WHITE) .setClickEvent(new ClickEvent( ClickEvent.Action.RUN_COMMAND, - BaritoneChatControl.FORCE_COMMAND_PREFIX + "help sel" + FORCE_COMMAND_PREFIX + "help sel" )); Helper.HELPER.logDirect(component); clickStart = null; diff --git a/src/main/java/baritone/utils/command/BaritoneChatControl.java b/src/main/java/baritone/utils/command/BaritoneChatControl.java index d62eaebf..352aff1c 100644 --- a/src/main/java/baritone/utils/command/BaritoneChatControl.java +++ b/src/main/java/baritone/utils/command/BaritoneChatControl.java @@ -44,27 +44,15 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Locale; -import java.util.UUID; import java.util.stream.Stream; +import static baritone.api.utils.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX; + public class BaritoneChatControl implements Helper, AbstractGameEventListener { private static final Settings settings = BaritoneAPI.getSettings(); private final ICommandManager manager; - /** - * In certain cases chat components need to execute commands for you. For example, the paginator automatically runs - * commands when you click the forward and back arrows to show you the previous/next page. - *

    - * If the prefix is changed in the meantime, then the command will go to chat. That's no good. So here's a permanent - * prefix that forces a command to run, regardless of the current prefix, chat/prefix control being enabled, etc. - *

    - * If used right (by both developers and users), it should be impossible to expose a command accidentally to the - * server. As a rule of thumb, if you have a clickable chat component, always use this prefix. If you're suggesting - * a command (a component that puts text into your text box, or something else), use {@link Settings#prefix}. - */ - public static String FORCE_COMMAND_PREFIX = String.format("<<%s>>", UUID.randomUUID().toString()); - public BaritoneChatControl(IBaritone baritone) { this.manager = baritone.getCommandManager(); baritone.getGameEventHandler().registerEventListener(this); diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index 43d9829c..a9d0e104 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -35,7 +35,7 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; -import static baritone.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; +import static baritone.api.utils.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX; public class HelpCommand extends Command { diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index 822e042a..48c4580f 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -41,7 +41,7 @@ import java.util.stream.Stream; import static baritone.api.utils.SettingsUtil.settingTypeToString; import static baritone.api.utils.SettingsUtil.settingValueToString; -import static baritone.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; +import static baritone.api.utils.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX; public class SetCommand extends Command { diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index b205048b..01f5817e 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -43,7 +43,7 @@ import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; -import static baritone.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; +import static baritone.api.utils.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX; public class WaypointsCommand extends Command { From 3803bc631b8daf836b273477de73582a8cd91e27 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 26 Sep 2019 19:02:21 -0500 Subject: [PATCH 667/682] Basically game on the imports --- .../java/baritone/api/utils/command/Command.java | 1 - .../api/utils/command/argument/CommandArgument.java | 1 - .../utils/command/datatypes/EntityClassById.java | 1 - .../api/utils/command/datatypes/ForEnumFacing.java | 2 -- .../utils/command/datatypes/RelativeCoordinate.java | 1 - .../command/helpers/arguments/ArgConsumer.java | 13 +++++++++---- .../helpers/tabcomplete/TabCompleteHelper.java | 1 - .../utils/command/defaults/AxisCommand.java | 1 - .../utils/command/defaults/BlacklistCommand.java | 1 - .../utils/command/defaults/BuildCommand.java | 1 - .../utils/command/defaults/CancelCommand.java | 1 - .../utils/command/defaults/ChestsCommand.java | 1 - .../utils/command/defaults/ClearareaCommand.java | 1 - .../utils/command/defaults/ClickCommand.java | 1 - .../utils/command/defaults/ComeCommand.java | 1 - .../utils/command/defaults/ExploreCommand.java | 1 - .../command/defaults/ExploreFilterCommand.java | 1 - .../utils/command/defaults/FarmCommand.java | 1 - .../utils/command/defaults/FindCommand.java | 1 - .../utils/command/defaults/FollowCommand.java | 1 - .../utils/command/defaults/ForceCancelCommand.java | 1 - .../baritone/utils/command/defaults/GcCommand.java | 1 - .../utils/command/defaults/GoalCommand.java | 1 - .../utils/command/defaults/InvertCommand.java | 1 - .../utils/command/defaults/PathCommand.java | 1 - .../utils/command/defaults/PauseResumeCommands.java | 1 - .../utils/command/defaults/ProcCommand.java | 1 - .../utils/command/defaults/ReloadAllCommand.java | 1 - .../utils/command/defaults/RenderCommand.java | 1 - .../utils/command/defaults/RepackCommand.java | 1 - .../utils/command/defaults/SaveAllCommand.java | 1 - .../utils/command/defaults/SchematicaCommand.java | 1 - .../baritone/utils/command/defaults/SelCommand.java | 3 +-- .../utils/command/defaults/ThisWayCommand.java | 1 - .../utils/command/defaults/TunnelCommand.java | 1 - .../utils/command/defaults/VersionCommand.java | 1 - 36 files changed, 10 insertions(+), 41 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index 6b922687..28d42bfd 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -18,7 +18,6 @@ package baritone.api.utils.command; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.api.utils.command.exception.CommandException; diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index c86e8c42..e3083d39 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -25,7 +25,6 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import net.minecraft.util.EnumFacing; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java index 321558e2..3597141f 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java +++ b/src/api/java/baritone/api/utils/command/datatypes/EntityClassById.java @@ -18,7 +18,6 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; diff --git a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java index 5cfe3918..ed6dce31 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java +++ b/src/api/java/baritone/api/utils/command/datatypes/ForEnumFacing.java @@ -18,8 +18,6 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.util.EnumFacing; diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java index 239c54a7..5075d7bc 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java @@ -19,7 +19,6 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; -import net.minecraft.util.math.MathHelper; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java index f9aef7be..e92855d1 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java @@ -22,12 +22,17 @@ import baritone.api.utils.Helper; import baritone.api.utils.command.Command; import baritone.api.utils.command.argparser.IArgParser; import baritone.api.utils.command.argument.CommandArgument; -import baritone.api.utils.command.datatypes.*; -import baritone.api.utils.command.exception.*; +import baritone.api.utils.command.datatypes.IDatatype; +import baritone.api.utils.command.datatypes.IDatatypeContext; +import baritone.api.utils.command.datatypes.IDatatypeFor; +import baritone.api.utils.command.datatypes.IDatatypePost; +import baritone.api.utils.command.exception.CommandException; +import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; +import baritone.api.utils.command.exception.CommandTooManyArgumentsException; import baritone.api.utils.command.manager.ICommandManager; import net.minecraft.util.EnumFacing; -import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; @@ -45,7 +50,7 @@ import java.util.stream.Stream; * need to retrieve an argument after you've already consumed it - look no further than {@link #consumed()}! *

  • Easy retrieval of many different types. If you need to retrieve an instance of an int or float for example, * look no further than {@link #getAs(Class)}. If you need a more powerful way of retrieving data, try out the many - * {@link #getDatatype(Class)} methods.
  • + * {@code getDatatype...} methods. *
  • It's very easy to throw detailed exceptions. The {@link ArgConsumer} has many different methods that can * enforce the number of arguments, the type of arguments, and more, throwing different types of * {@link CommandException}s if something seems off. You're recommended to do all validation and store all needed diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index 784b53f5..8941df96 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -26,7 +26,6 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.manager.ICommandManager; import net.minecraft.util.ResourceLocation; -import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Locale; diff --git a/src/main/java/baritone/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java index 942c829e..ae52bfb2 100644 --- a/src/main/java/baritone/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalAxis; import baritone.api.utils.command.Command; diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index 915f5b51..21551782 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.process.IGetToBlockProcess; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index e9803b02..f4537113 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeBlockPos; diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index 45e0854a..a4ef4cc7 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index 5c0bc354..d4101a62 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.cache.IRememberedInventory; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java index 831df5ec..39f8809d 100644 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.BetterBlockPos; diff --git a/src/main/java/baritone/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java index 23ded82f..e5180b2f 100644 --- a/src/main/java/baritone/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index 399317e5..bbefeb43 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index d3103a00..dc156d0e 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeGoalXZ; diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index e47aec50..4d75d1b4 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeFile; import baritone.api.utils.command.exception.CommandException; diff --git a/src/main/java/baritone/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java index 6ff746d4..1f803ec6 100644 --- a/src/main/java/baritone/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index b6dc3564..8848db81 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.BlockById; diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index 28e0b91c..e3e0c3d1 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -20,7 +20,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.EntityClassById; -import baritone.api.utils.command.datatypes.IDatatype; import baritone.api.utils.command.datatypes.IDatatypeFor; import baritone.api.utils.command.datatypes.NearbyPlayer; import baritone.api.utils.command.exception.CommandException; diff --git a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index 5672f9b3..3de8a056 100644 --- a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.behavior.IPathingBehavior; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index 23bea821..c2e7952c 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index 5484fec1..3f760111 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.process.ICustomGoalProcess; import baritone.api.utils.BetterBlockPos; diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index 60723de2..f52e6226 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalInverted; import baritone.api.process.ICustomGoalProcess; diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index c775c231..4cd766ea 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.process.ICustomGoalProcess; import baritone.api.utils.command.Command; diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index ee15fde6..bc3c392a 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.process.IBaritoneProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index 063df9be..40d8e72b 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.pathing.calc.IPathingControlManager; import baritone.api.process.IBaritoneProcess; import baritone.api.process.PathingCommand; diff --git a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index 0a860ede..c16000f7 100644 --- a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index 75cf0a44..7c100c8e 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; diff --git a/src/main/java/baritone/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java index 08503531..bd918f09 100644 --- a/src/main/java/baritone/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index a505dda1..8343f753 100644 --- a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index 2a984dd2..91e31daa 100644 --- a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index 23a2b764..d9899f42 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -19,7 +19,6 @@ package baritone.utils.command.defaults; import baritone.Baritone; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.event.events.RenderEvent; import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.schematic.*; @@ -46,8 +45,8 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import java.awt.*; -import java.util.*; import java.util.List; +import java.util.*; import java.util.function.Function; import java.util.stream.Stream; diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index 384a52cb..4c6f3522 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index 5ac21b7a..588287d6 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalStrictDirection; import baritone.api.utils.command.Command; diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index de09e943..fe53f523 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -18,7 +18,6 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; -import baritone.api.Settings; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; From 1064a79e1dd62c680dbe44a693bdb606a2e85759 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 26 Sep 2019 22:59:15 -0500 Subject: [PATCH 668/682] Fix javadoc errors --- .../baritone/api/utils/command/argument/CommandArgument.java | 2 +- .../utils/command/helpers/tabcomplete/TabCompleteHelper.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java index e3083d39..a5b044c4 100644 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java @@ -34,7 +34,7 @@ import java.util.stream.Stream; * A {@link CommandArgument} is an immutable object representing one command argument. It contains data on the index of * that argument, its value, and the rest of the string that argument was found in *

    - * You're recommended to use {@link ArgConsumer}s to handle these. Check out {@link ArgConsumer#from(String)} + * You're recommended to use {@link ArgConsumer}s to handle these. */ public class CommandArgument { diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index 8941df96..11dee4e6 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -21,6 +21,7 @@ import baritone.api.BaritoneAPI; import baritone.api.Settings; import baritone.api.event.events.TabCompleteEvent; import baritone.api.utils.SettingsUtil; +import baritone.api.utils.command.datatypes.IDatatype; import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.manager.ICommandManager; @@ -45,7 +46,7 @@ import java.util.stream.Stream; * {@link #filterPrefix(String)}

  • *
  • Get the stream using {@link #stream()}
  • *
  • Pass it up to whatever's calling your tab complete function (i.e. - * {@link ICommandManager#tabComplete(CommandExecution)} or {@link ArgConsumer#tabCompleteDatatype(Class)})
  • + * {@link ICommandManager#tabComplete(CommandExecution)} or {@link ArgConsumer#tabCompleteDatatype(IDatatype)}) * *

    * For advanced users: if you're intercepting {@link TabCompleteEvent}s directly, use {@link #build()} instead for an From 5ba1e67ea02d5cbc374989389390784efd697896 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 26 Sep 2019 23:18:05 -0500 Subject: [PATCH 669/682] Don't print stack-traces to chat, just inform the user of the error --- src/api/java/baritone/api/utils/Helper.java | 3 + .../command/argparser/ArgParserManager.java | 4 +- .../exception/CommandUnhandledException.java | 56 +------------------ .../command/execution/CommandExecution.java | 1 - 4 files changed, 7 insertions(+), 57 deletions(-) diff --git a/src/api/java/baritone/api/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java index 7d962501..ae91957a 100755 --- a/src/api/java/baritone/api/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -37,8 +37,11 @@ public interface Helper { Helper HELPER = new Helper() {}; static ITextComponent getPrefix() { + // Inner text component ITextComponent baritone = new TextComponentString(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone"); baritone.getStyle().setColor(TextFormatting.LIGHT_PURPLE); + + // Outer brackets ITextComponent prefix = new TextComponentString(""); prefix.getStyle().setColor(TextFormatting.DARK_PURPLE); prefix.appendText("["); diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index 24f5fec0..b9b7bcc0 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -67,7 +67,7 @@ public class ArgParserManager { * @param type The type to try and parse the argument into. * @param arg The argument to parse. * @return An instance of the specified class. - * @throws CommandInvalidTypeException If the parsing failed + * @throws CommandInvalidTypeException If the parsing failed */ public static T parseStateless(Class type, CommandArgument arg) throws CommandInvalidTypeException { IArgParser.Stateless parser = getParserStateless(type); @@ -89,7 +89,7 @@ public class ArgParserManager { * @param arg The argument to parse. * @param state The state to pass to the {@link IArgParser.Stated}. * @return An instance of the specified class. - * @throws CommandInvalidTypeException If the parsing failed + * @throws CommandInvalidTypeException If the parsing failed * @see IArgParser.Stated */ public static T parseStated(Class type, Class stateKlass, CommandArgument arg, S state) throws CommandInvalidTypeException { diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java index 08f39ecd..5967eeb6 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -17,62 +17,10 @@ package baritone.api.utils.command.exception; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - public class CommandUnhandledException extends RuntimeException implements ICommandException { public CommandUnhandledException(Throwable cause) { - super(String.format( - "An unhandled exception has occurred:\n\n%s", - getFriendlierStackTrace(cause) - )); - } - - private static String getStackTrace(Throwable throwable) { - StringWriter sw = new StringWriter(); - throwable.printStackTrace(new PrintWriter(sw)); - return sw.toString(); - } - - private static String getBaritoneStackTrace(String stackTrace) { - List lines = Stream.of(stackTrace.split("\n")) - .collect(Collectors.toList()); - int lastBaritoneLine = 0; - for (int i = 0; i < lines.size(); i++) { - if (lines.get(i).startsWith("\tat baritone.") && lines.get(i).contains("BaritoneChatControl")) { - lastBaritoneLine = i; - } - } - return String.join("\n", lines.subList(0, lastBaritoneLine + 1)); - } - - private static String getBaritoneStackTrace(Throwable throwable) { - return getBaritoneStackTrace(getStackTrace(throwable)); - } - - private static String getFriendlierStackTrace(String stackTrace) { - List lines = Arrays.asList(stackTrace.split("\n")); - for (int i = 0; i < lines.size(); i++) { - String line = lines.get(i); - if (line.startsWith("\tat ")) { - if (line.startsWith("\tat baritone.")) { - line = line.replaceFirst("^\tat [a-z.]+?([A-Z])", "\tat $1"); - } - // line = line.replaceFirst("\\(([^)]+)\\)$", "\n\t . $1"); - line = line.replaceFirst("\\([^:]+:(\\d+)\\)$", ":$1"); - line = line.replaceFirst("\\(Unknown Source\\)$", ""); - lines.set(i, line); - } - } - return String.join("\n", lines); - } - - private static String getFriendlierStackTrace(Throwable throwable) { - return getFriendlierStackTrace(getBaritoneStackTrace(throwable)); + super("An unhandled exception occurred. The error is in your game's log, please report this at https://github.com/cabaletta/baritone/issues"); + cause.printStackTrace(); } } diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java index 8a23757d..eb69a609 100644 --- a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java +++ b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java @@ -71,7 +71,6 @@ public class CommandExecution { } catch (CommandException e) { e.handle(command, args.args); } catch (Throwable t) { - t.printStackTrace(); new CommandUnhandledException(t).handle(command, args.args); } } From 45bea50c91caa7013914fb17ede01fcaedca242b Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 26 Sep 2019 23:20:45 -0500 Subject: [PATCH 670/682] Fix remaining usages to be in-line with previous commit --- src/api/java/baritone/api/process/IMineProcess.java | 4 ++-- src/api/java/baritone/api/utils/Helper.java | 3 ++- src/api/java/baritone/api/utils/SettingsUtil.java | 6 +++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/process/IMineProcess.java b/src/api/java/baritone/api/process/IMineProcess.java index 27c9d8d2..9cd76a09 100644 --- a/src/api/java/baritone/api/process/IMineProcess.java +++ b/src/api/java/baritone/api/process/IMineProcess.java @@ -21,7 +21,7 @@ import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.BlockOptionalMetaLookup; import net.minecraft.block.Block; -import java.util.Arrays; +import java.util.stream.Stream; /** * @author Brady @@ -93,7 +93,7 @@ public interface IMineProcess extends IBaritoneProcess { */ default void mine(int quantity, Block... blocks) { mine(quantity, new BlockOptionalMetaLookup( - Arrays.stream(blocks) + Stream.of(blocks) .map(BlockOptionalMeta::new) .toArray(BlockOptionalMeta[]::new) )); diff --git a/src/api/java/baritone/api/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java index ae91957a..376dcf7f 100755 --- a/src/api/java/baritone/api/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -24,6 +24,7 @@ import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import java.util.Arrays; +import java.util.stream.Stream; /** * @author Brady @@ -88,7 +89,7 @@ public interface Helper { * @param color The color to print that message in */ default void logDirect(String message, TextFormatting color) { - Arrays.stream(message.split("\n")).forEach(line -> { + Stream.of(message.split("\n")).forEach(line -> { ITextComponent component = new TextComponentString(line.replace("\t", " ")); component.getStyle().setColor(color); logDirect(component); diff --git a/src/api/java/baritone/api/utils/SettingsUtil.java b/src/api/java/baritone/api/utils/SettingsUtil.java index 0035f2ea..f9cb7136 100644 --- a/src/api/java/baritone/api/utils/SettingsUtil.java +++ b/src/api/java/baritone/api/utils/SettingsUtil.java @@ -34,7 +34,6 @@ import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Consumer; @@ -42,6 +41,7 @@ import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import java.util.stream.Stream; import static net.minecraft.client.Minecraft.getMinecraft; @@ -242,7 +242,7 @@ public class SettingsUtil { Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0]; Parser parser = Parser.getParser(type); - return Arrays.stream(raw.split(",")) + return Stream.of(raw.split(",")) .map(s -> parser.parse(context, s)) .collect(Collectors.toList()); } @@ -301,7 +301,7 @@ public class SettingsUtil { } public static Parser getParser(Type type) { - return Arrays.stream(values()) + return Stream.of(values()) .filter(parser -> parser.accepts(type)) .findFirst().orElse(null); } From b75a78f3d3623588e4c48c036c6afdbaba8d9cc0 Mon Sep 17 00:00:00 2001 From: Brady Date: Thu, 26 Sep 2019 23:33:37 -0500 Subject: [PATCH 671/682] Fix the scuff --- src/api/java/baritone/api/utils/Helper.java | 7 ++++-- .../command/argparser/ArgParserManager.java | 6 ++--- .../CommandNoParserForTypeException.java | 5 +--- .../exception/CommandUnhandledException.java | 24 +++++++++++++++++-- .../command/execution/CommandExecution.java | 10 +++++--- 5 files changed, 37 insertions(+), 15 deletions(-) diff --git a/src/api/java/baritone/api/utils/Helper.java b/src/api/java/baritone/api/utils/Helper.java index 376dcf7f..91d7890f 100755 --- a/src/api/java/baritone/api/utils/Helper.java +++ b/src/api/java/baritone/api/utils/Helper.java @@ -37,6 +37,11 @@ public interface Helper { */ Helper HELPER = new Helper() {}; + /** + * Instance of the game + */ + Minecraft mc = Minecraft.getMinecraft(); + static ITextComponent getPrefix() { // Inner text component ITextComponent baritone = new TextComponentString(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone"); @@ -52,8 +57,6 @@ public interface Helper { return prefix; } - Minecraft mc = Minecraft.getMinecraft(); - /** * Send a message to chat only if chatDebug is on * diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index b9b7bcc0..1b0730c6 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -72,8 +72,7 @@ public class ArgParserManager { public static T parseStateless(Class type, CommandArgument arg) throws CommandInvalidTypeException { IArgParser.Stateless parser = getParserStateless(type); if (parser == null) { - // TODO: Fix this scuff lol - throw new CommandUnhandledException(new CommandNoParserForTypeException(type)); + throw new CommandNoParserForTypeException(type); } try { return parser.parseArg(arg); @@ -95,8 +94,7 @@ public class ArgParserManager { public static T parseStated(Class type, Class stateKlass, CommandArgument arg, S state) throws CommandInvalidTypeException { IArgParser.Stated parser = getParserStated(type, stateKlass); if (parser == null) { - // TODO: Fix this scuff lol - throw new CommandUnhandledException(new CommandNoParserForTypeException(type)); + throw new CommandNoParserForTypeException(type); } try { return parser.parseArg(arg, state); diff --git a/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java b/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java index 5a016cd4..f4f2d818 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandNoParserForTypeException.java @@ -17,12 +17,9 @@ package baritone.api.utils.command.exception; -public class CommandNoParserForTypeException extends CommandErrorMessageException { - - public final Class klass; +public class CommandNoParserForTypeException extends CommandUnhandledException { public CommandNoParserForTypeException(Class klass) { super(String.format("Could not find a handler for type %s", klass.getSimpleName())); - this.klass = klass; } } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java index 5967eeb6..6d647a20 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -17,10 +17,30 @@ package baritone.api.utils.command.exception; +import baritone.api.utils.command.Command; +import baritone.api.utils.command.argument.CommandArgument; +import net.minecraft.util.text.TextFormatting; + +import java.util.List; + +import static baritone.api.utils.Helper.HELPER; + public class CommandUnhandledException extends RuntimeException implements ICommandException { + public CommandUnhandledException(String message) { + super(message); + } + public CommandUnhandledException(Throwable cause) { - super("An unhandled exception occurred. The error is in your game's log, please report this at https://github.com/cabaletta/baritone/issues"); - cause.printStackTrace(); + super(cause); + } + + @Override + public void handle(Command command, List args) { + HELPER.logDirect("An unhandled exception occurred." + + "The error is in your game's log, please report this at https://github.com/cabaletta/baritone/issues", + TextFormatting.RED); + + this.printStackTrace(); } } diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java index eb69a609..181c0e6b 100644 --- a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java +++ b/src/api/java/baritone/api/utils/command/execution/CommandExecution.java @@ -21,6 +21,7 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandUnhandledException; +import baritone.api.utils.command.exception.ICommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.manager.ICommandManager; import com.mojang.realmsclient.util.Pair; @@ -68,10 +69,13 @@ public class CommandExecution { public void execute() { try { command.execute(this); - } catch (CommandException e) { - e.handle(command, args.args); } catch (Throwable t) { - new CommandUnhandledException(t).handle(command, args.args); + // Create a handleable exception, wrap if needed + ICommandException exception = t instanceof ICommandException + ? (ICommandException) t + : new CommandUnhandledException(t); + + exception.handle(command, args.args); } } From a04742085e03edfd6cb800074fd177f05824c85b Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 27 Sep 2019 09:54:55 -0500 Subject: [PATCH 672/682] Add documentation to datatypes --- .../utils/command/datatypes/IDatatype.java | 16 +++++++++++++--- .../utils/command/datatypes/IDatatypeFor.java | 19 +++++++++++++++++++ .../command/datatypes/IDatatypePost.java | 7 +++++++ 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java index 2a0696f2..8c155fb6 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java @@ -24,6 +24,16 @@ import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.stream.Stream; /** + * An {@link IDatatype} is similar to an {@link IArgParser} in the sense that it is capable of consuming an argument + * to transform it into a usable form as the code desires. + *

    + * A fundamental difference is that an {@link IDatatype} is capable of consuming multiple arguments. For example, + * {@link RelativeBlockPos} is an {@link IDatatypePost} which requires at least 3 {@link RelativeCoordinate} arguments + * to be specified. + *

    + * Another difference is that an {@link IDatatype} can be tab-completed, providing comprehensive auto completion + * that can substitute based on existing input or provide possibilities for the next piece of input. + * * @see IDatatypeContext * @see IDatatypeFor * @see IDatatypePost @@ -31,12 +41,12 @@ import java.util.stream.Stream; public interface IDatatype { /** + * Attempts to complete missing or partial input provided through the {@link ArgConsumer} provided by + * {@link IDatatypeContext#getConsumer()} in order to aide the user in executing commands. + *

    * One benefit over datatypes over {@link IArgParser}s is that instead of each command trying to guess what values * the datatype will accept, or simply not tab completing at all, datatypes that support tab completion can provide * accurate information using the same methods used to parse arguments in the first place. - *

    - * See {@link RelativeFile} for a very advanced example of tab completion. You wouldn't want this pasted into every - * command that uses files - right? Right? * * @param ctx The argument consumer to tab complete * @return A stream representing the strings that can be tab completed. DO NOT INCLUDE SPACES IN ANY STRINGS. diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java index 3168702a..4f0f4200 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeFor.java @@ -19,7 +19,26 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.exception.CommandException; +import java.util.function.Supplier; + +/** + * An {@link IDatatype} which acts as a {@link Supplier}, in essence. The only difference + * is that it requires an {@link IDatatypeContext} to be provided due to the expectation that + * implementations of {@link IDatatype} are singletons. + */ public interface IDatatypeFor extends IDatatype { + /** + * Consumes the desired amount of arguments from the specified {@link IDatatypeContext}, and + * then returns the parsed value. This method will more than likely return a {@link IllegalArgumentException} + * if the expected input does not conform to a parseable value. As far as a {@link CommandException} being + * thrown is concerned, see the note below for specifics. + * + * @see IDatatypeContext + * + * @param ctx The context + * @return The parsed data-type + * @throws CommandException If there was an issue parsing using another type or arguments could not be polled. + */ T get(IDatatypeContext ctx) throws CommandException; } diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java index 3e1e70be..2e4cc47a 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypePost.java @@ -19,6 +19,13 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.exception.CommandException; +import java.util.function.Function; + +/** + * An {@link IDatatype} which acts as a {@link Function}, in essence. The only difference + * is that it requires an {@link IDatatypeContext} to be provided due to the expectation that + * implementations of {@link IDatatype} are singletons. + */ public interface IDatatypePost extends IDatatype { /** From cf60a5f3bd97f8c416f7b283f9fddc756354b7e3 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 27 Sep 2019 10:18:46 -0500 Subject: [PATCH 673/682] Clean up some things with DefaultCommands --- .../command/defaults/DefaultCommands.java | 81 ++++++++++--------- .../utils/command/manager/CommandManager.java | 2 +- 2 files changed, 42 insertions(+), 41 deletions(-) diff --git a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java index 1245cef8..73ddda92 100644 --- a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java +++ b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java @@ -22,48 +22,49 @@ import baritone.api.utils.command.Command; import java.util.*; -public class DefaultCommands { +public final class DefaultCommands { - public static List commands(IBaritone baritone) { + private DefaultCommands() {} + + public static List createAll(IBaritone baritone) { Objects.requireNonNull(baritone); - List commands = new ArrayList<>(); - commands.addAll(Arrays.asList( - new HelpCommand(baritone), - new SetCommand(baritone), - new CommandAlias(baritone, Arrays.asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), - new CommandAlias(baritone, "reset", "Reset all settings or just one", "set reset"), - new GoalCommand(baritone), - new PathCommand(baritone), - new ProcCommand(baritone), - new VersionCommand(baritone), - new RepackCommand(baritone), - new BuildCommand(baritone), - new SchematicaCommand(baritone), - new ComeCommand(baritone), - new AxisCommand(baritone), - new CancelCommand(baritone), - new ForceCancelCommand(baritone), - new GcCommand(baritone), - new InvertCommand(baritone), - new ClearareaCommand(baritone), - new TunnelCommand(baritone), - new RenderCommand(baritone), - new FarmCommand(baritone), - new ChestsCommand(baritone), - new FollowCommand(baritone), - new ExploreFilterCommand(baritone), - new ReloadAllCommand(baritone), - new SaveAllCommand(baritone), - new ExploreCommand(baritone), - new BlacklistCommand(baritone), - new FindCommand(baritone), - new MineCommand(baritone), - new ClickCommand(baritone), - new ThisWayCommand(baritone), - new WaypointsCommand(baritone), - new CommandAlias(baritone, "sethome", "Sets your home waypoint", "waypoints save home"), - new CommandAlias(baritone, "home", "Set goal to your home waypoint", "waypoints goal home"), - new SelCommand(baritone) + List commands = new ArrayList<>(Arrays.asList( + new HelpCommand(baritone), + new SetCommand(baritone), + new CommandAlias(baritone, Arrays.asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), + new CommandAlias(baritone, "reset", "Reset all settings or just one", "set reset"), + new GoalCommand(baritone), + new PathCommand(baritone), + new ProcCommand(baritone), + new VersionCommand(baritone), + new RepackCommand(baritone), + new BuildCommand(baritone), + new SchematicaCommand(baritone), + new ComeCommand(baritone), + new AxisCommand(baritone), + new CancelCommand(baritone), + new ForceCancelCommand(baritone), + new GcCommand(baritone), + new InvertCommand(baritone), + new ClearareaCommand(baritone), + new TunnelCommand(baritone), + new RenderCommand(baritone), + new FarmCommand(baritone), + new ChestsCommand(baritone), + new FollowCommand(baritone), + new ExploreFilterCommand(baritone), + new ReloadAllCommand(baritone), + new SaveAllCommand(baritone), + new ExploreCommand(baritone), + new BlacklistCommand(baritone), + new FindCommand(baritone), + new MineCommand(baritone), + new ClickCommand(baritone), + new ThisWayCommand(baritone), + new WaypointsCommand(baritone), + new CommandAlias(baritone, "sethome", "Sets your home waypoint", "waypoints save home"), + new CommandAlias(baritone, "home", "Set goal to your home waypoint", "waypoints goal home"), + new SelCommand(baritone) )); PauseResumeCommands prc = new PauseResumeCommands(baritone); commands.add(prc.pauseCommand); diff --git a/src/main/java/baritone/utils/command/manager/CommandManager.java b/src/main/java/baritone/utils/command/manager/CommandManager.java index 7cdcea29..46e79825 100644 --- a/src/main/java/baritone/utils/command/manager/CommandManager.java +++ b/src/main/java/baritone/utils/command/manager/CommandManager.java @@ -43,7 +43,7 @@ public class CommandManager implements ICommandManager { public CommandManager(Baritone baritone) { this.baritone = baritone; - DefaultCommands.commands(baritone).forEach(this.registry::register); + DefaultCommands.createAll(baritone).forEach(this.registry::register); } @Override From 9981af67d5dca41435f37141019cd8c6fd89da67 Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 27 Sep 2019 11:10:57 -0500 Subject: [PATCH 674/682] Remove debug code --- .../api/utils/command/datatypes/RelativeCoordinate.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java index 5075d7bc..84a29f63 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java @@ -35,9 +35,6 @@ public enum RelativeCoordinate implements IDatatypePost { origin = 0.0D; } - System.out.println(ctx.getConsumer().args); - new Throwable().printStackTrace(); - Matcher matcher = PATTERN.matcher(ctx.getConsumer().getString()); if (!matcher.matches()) { throw new IllegalArgumentException("pattern doesn't match"); From a75b90fcef7f433bda848eb2b132760365f1a69f Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 27 Sep 2019 17:07:40 -0500 Subject: [PATCH 675/682] crucial performance optimization --- .../utils/command/helpers/tabcomplete/TabCompleteHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index 11dee4e6..e2cf5701 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -65,7 +65,7 @@ public class TabCompleteHelper { } public TabCompleteHelper() { - this(new String[0]); + stream = Stream.empty(); } /** From 6a90b57ced9dc95713bd49eeb9b73db488d0f258 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 28 Sep 2019 10:21:07 -0500 Subject: [PATCH 676/682] Some basic API/Main separation --- .../baritone/api/utils/command/Command.java | 14 ++-- .../command/execution/ICommandExecution.java | 68 +++++++++++++++++++ .../tabcomplete/TabCompleteHelper.java | 3 +- .../command/manager/ICommandManager.java | 9 +-- .../utils/command/BaritoneChatControl.java | 28 ++++---- .../command/execution/CommandExecution.java | 58 ++++++---------- .../utils/command/manager/CommandManager.java | 41 ++++++----- 7 files changed, 137 insertions(+), 84 deletions(-) create mode 100644 src/api/java/baritone/api/utils/command/execution/ICommandExecution.java rename src/{api/java/baritone/api => main/java/baritone}/utils/command/execution/CommandExecution.java (53%) diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index 28d42bfd..e83d6c50 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -21,7 +21,7 @@ import baritone.api.IBaritone; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.execution.CommandExecution; +import baritone.api.utils.command.execution.ICommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Collections; @@ -62,19 +62,21 @@ public abstract class Command implements Helper { * * @param execution The command execution to execute this command with */ - public void execute(CommandExecution execution) throws CommandException { - executed(execution.label, execution.args); + public final void execute(ICommandExecution execution) throws CommandException { + this.executed(execution.getLabel(), execution.getArguments()); } /** - * Tab completes this command with the specified arguments. This won't throw any exceptions ever. + * Tab completes this command with the specified arguments. Any exception that is thrown by + * {@link #tabCompleted(String, ArgConsumer)} will be caught by this method, and then {@link Stream#empty()} + * will be returned. * * @param execution The command execution to tab complete * @return The list of completions. */ - public Stream tabComplete(CommandExecution execution) { + public final Stream tabComplete(ICommandExecution execution) { try { - return tabCompleted(execution.label, execution.args); + return this.tabCompleted(execution.getLabel(), execution.getArguments()); } catch (Throwable t) { return Stream.empty(); } diff --git a/src/api/java/baritone/api/utils/command/execution/ICommandExecution.java b/src/api/java/baritone/api/utils/command/execution/ICommandExecution.java new file mode 100644 index 00000000..4ca5b193 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/execution/ICommandExecution.java @@ -0,0 +1,68 @@ +/* + * 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.command.execution; + +import baritone.api.utils.command.Command; +import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import net.minecraft.util.Tuple; + +import java.util.List; +import java.util.stream.Stream; + +/** + * @author Brady + * @since 9/28/2019 + */ +public interface ICommandExecution { + + /** + * @return The label that was used to target the {@link Command} + */ + String getLabel(); + + /** + * @return The arguments to be passed to the {@link Command} + */ + ArgConsumer getArguments(); + + /** + * Executes the target command for this {@link ICommandExecution}. This method should never + * {@code throw} any exception, anything that is thrown during the target command execution + * should be safely handled. + */ + void execute(); + + /** + * Forwards this {@link ICommandExecution} to the target {@link Command} to perform a tab-completion. + * If the tab-completion operation is a failure, then {@link Stream#empty()} will be returned. + * + * @return The tab-completed arguments, if possible. + */ + Stream tabComplete(); + + static Tuple> expand(String string, boolean preserveEmptyLast) { + String label = string.split("\\s", 2)[0]; + List args = CommandArgument.from(string.substring(label.length()), preserveEmptyLast); + return new Tuple<>(label, args); + } + + static Tuple> expand(String string) { + return expand(string, false); + } +} diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index e2cf5701..db63b2d5 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -22,7 +22,6 @@ import baritone.api.Settings; import baritone.api.event.events.TabCompleteEvent; import baritone.api.utils.SettingsUtil; import baritone.api.utils.command.datatypes.IDatatype; -import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.manager.ICommandManager; import net.minecraft.util.ResourceLocation; @@ -46,7 +45,7 @@ import java.util.stream.Stream; * {@link #filterPrefix(String)} *

  • Get the stream using {@link #stream()}
  • *
  • Pass it up to whatever's calling your tab complete function (i.e. - * {@link ICommandManager#tabComplete(CommandExecution)} or {@link ArgConsumer#tabCompleteDatatype(IDatatype)})
  • + * {@link ICommandManager#tabComplete(String)} or {@link ArgConsumer#tabCompleteDatatype(IDatatype)}) * *

    * For advanced users: if you're intercepting {@link TabCompleteEvent}s directly, use {@link #build()} instead for an diff --git a/src/api/java/baritone/api/utils/command/manager/ICommandManager.java b/src/api/java/baritone/api/utils/command/manager/ICommandManager.java index 2ed87a64..63682433 100644 --- a/src/api/java/baritone/api/utils/command/manager/ICommandManager.java +++ b/src/api/java/baritone/api/utils/command/manager/ICommandManager.java @@ -20,9 +20,8 @@ package baritone.api.utils.command.manager; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.argument.CommandArgument; -import baritone.api.utils.command.execution.CommandExecution; import baritone.api.utils.command.registry.Registry; -import com.mojang.realmsclient.util.Pair; +import net.minecraft.util.Tuple; import java.util.List; import java.util.stream.Stream; @@ -43,13 +42,11 @@ public interface ICommandManager { */ Command getCommand(String name); - void execute(CommandExecution execution); - boolean execute(String string); - Stream tabComplete(CommandExecution execution); + boolean execute(Tuple> expanded); - Stream tabComplete(Pair> pair); + Stream tabComplete(Tuple> expanded); Stream tabComplete(String prefix); } diff --git a/src/main/java/baritone/utils/command/BaritoneChatControl.java b/src/main/java/baritone/utils/command/BaritoneChatControl.java index 352aff1c..facc24da 100644 --- a/src/main/java/baritone/utils/command/BaritoneChatControl.java +++ b/src/main/java/baritone/utils/command/BaritoneChatControl.java @@ -29,11 +29,11 @@ import baritone.api.utils.SettingsUtil; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.exception.CommandNotFoundException; -import baritone.api.utils.command.execution.CommandExecution; +import baritone.api.utils.command.execution.ICommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.manager.ICommandManager; -import com.mojang.realmsclient.util.Pair; +import net.minecraft.util.Tuple; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; @@ -67,7 +67,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { event.cancel(); String commandStr = msg.substring(forceRun ? FORCE_COMMAND_PREFIX.length() : prefix.length()); if (!runCommand(commandStr) && !commandStr.trim().isEmpty()) { - new CommandNotFoundException(CommandExecution.expand(commandStr).first()).handle(null, null); + new CommandNotFoundException(ICommandExecution.expand(commandStr).getFirst()).handle(null, null); } } else if ((settings.chatControl.value || settings.chatControlAnyway.value) && runCommand(msg)) { event.cancel(); @@ -106,10 +106,10 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (msg.isEmpty()) { return this.runCommand("help"); } - Pair> pair = CommandExecution.expand(msg); - String command = pair.first(); - String rest = msg.substring(pair.first().length()); - ArgConsumer argc = new ArgConsumer(this.manager, pair.second()); + Tuple> pair = ICommandExecution.expand(msg); + String command = pair.getFirst(); + String rest = msg.substring(pair.getFirst().length()); + ArgConsumer argc = new ArgConsumer(this.manager, pair.getSecond()); if (!argc.hasAny()) { Settings.Setting setting = settings.byLowerName.get(command.toLowerCase(Locale.US)); if (setting != null) { @@ -126,7 +126,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (setting.getName().equals("logger")) { continue; } - if (setting.getName().equalsIgnoreCase(pair.first())) { + if (setting.getName().equalsIgnoreCase(pair.getFirst())) { logRanCommand(command, rest); try { this.manager.execute(String.format("set %s %s", setting.getName(), argc.getString())); @@ -135,13 +135,13 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { } } } - CommandExecution execution = CommandExecution.from(this.manager, pair); - if (execution == null) { - return false; + + // If the command exists, then handle echoing the input + if (this.manager.getCommand(pair.getFirst()) != null) { + logRanCommand(command, rest); } - logRanCommand(command, rest); - this.manager.execute(execution); - return true; + + return this.manager.execute(pair); } @Override diff --git a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java b/src/main/java/baritone/utils/command/execution/CommandExecution.java similarity index 53% rename from src/api/java/baritone/api/utils/command/execution/CommandExecution.java rename to src/main/java/baritone/utils/command/execution/CommandExecution.java index 181c0e6b..1e8fe838 100644 --- a/src/api/java/baritone/api/utils/command/execution/CommandExecution.java +++ b/src/main/java/baritone/utils/command/execution/CommandExecution.java @@ -15,21 +15,23 @@ * along with Baritone. If not, see . */ -package baritone.api.utils.command.execution; +package baritone.utils.command.execution; import baritone.api.utils.command.Command; -import baritone.api.utils.command.argument.CommandArgument; -import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandUnhandledException; import baritone.api.utils.command.exception.ICommandException; +import baritone.api.utils.command.execution.ICommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; -import baritone.api.utils.command.manager.ICommandManager; -import com.mojang.realmsclient.util.Pair; +import baritone.utils.command.manager.CommandManager; -import java.util.List; import java.util.stream.Stream; -public class CommandExecution { +/** + * The default, internal implementation of {@link ICommandExecution}, which is used by {@link CommandManager} + * + * @author LoganDark, Brady + */ +public class CommandExecution implements ICommandExecution { /** * The command itself @@ -39,12 +41,12 @@ public class CommandExecution { /** * The name this command was called with */ - public final String label; + private final String label; /** * The arg consumer */ - public final ArgConsumer args; + private final ArgConsumer args; public CommandExecution(Command command, String label, ArgConsumer args) { this.command = command; @@ -52,20 +54,17 @@ public class CommandExecution { this.args = args; } - public static String getLabel(String string) { - return string.split("\\s", 2)[0]; + @Override + public String getLabel() { + return this.label; } - public static Pair> expand(String string, boolean preserveEmptyLast) { - String label = getLabel(string); - List args = CommandArgument.from(string.substring(label.length()), preserveEmptyLast); - return Pair.of(label, args); - } - - public static Pair> expand(String string) { - return expand(string, false); + @Override + public ArgConsumer getArguments() { + return this.args; } + @Override public void execute() { try { command.execute(this); @@ -79,27 +78,8 @@ public class CommandExecution { } } + @Override public Stream tabComplete() { return command.tabComplete(this); } - - public static CommandExecution from(ICommandManager manager, String label, ArgConsumer args) { - Command command = manager.getCommand(label); - if (command == null) { - return null; - } - return new CommandExecution( - command, - label, - args - ); - } - - public static CommandExecution from(ICommandManager manager, Pair> pair) { - return from(manager, pair.first(), new ArgConsumer(manager, pair.second())); - } - - public static CommandExecution from(ICommandManager manager, String string) { - return from(manager, expand(string)); - } } diff --git a/src/main/java/baritone/utils/command/manager/CommandManager.java b/src/main/java/baritone/utils/command/manager/CommandManager.java index 46e79825..e5c5d035 100644 --- a/src/main/java/baritone/utils/command/manager/CommandManager.java +++ b/src/main/java/baritone/utils/command/manager/CommandManager.java @@ -21,18 +21,22 @@ import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.argument.CommandArgument; -import baritone.api.utils.command.execution.CommandExecution; +import baritone.api.utils.command.execution.ICommandExecution; +import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.manager.ICommandManager; import baritone.api.utils.command.registry.Registry; import baritone.utils.command.defaults.DefaultCommands; -import com.mojang.realmsclient.util.Pair; +import baritone.utils.command.execution.CommandExecution; +import net.minecraft.util.Tuple; import java.util.List; import java.util.Locale; import java.util.stream.Stream; /** + * The default, internal implementation of {@link ICommandManager} + * * @author Brady * @since 9/21/2019 */ @@ -67,13 +71,13 @@ public class CommandManager implements ICommandManager { } @Override - public void execute(CommandExecution execution) { - execution.execute(); + public boolean execute(String string) { + return this.execute(ICommandExecution.expand(string)); } @Override - public boolean execute(String string) { - CommandExecution execution = CommandExecution.from(this, string); + public boolean execute(Tuple> expanded) { + ICommandExecution execution = this.from(expanded); if (execution != null) { execution.execute(); } @@ -81,21 +85,16 @@ public class CommandManager implements ICommandManager { } @Override - public Stream tabComplete(CommandExecution execution) { - return execution.tabComplete(); - } - - @Override - public Stream tabComplete(Pair> pair) { - CommandExecution execution = CommandExecution.from(this, pair); - return execution == null ? Stream.empty() : tabComplete(execution); + public Stream tabComplete(Tuple> expanded) { + ICommandExecution execution = this.from(expanded); + return execution == null ? Stream.empty() : execution.tabComplete(); } @Override public Stream tabComplete(String prefix) { - Pair> pair = CommandExecution.expand(prefix, true); - String label = pair.first(); - List args = pair.second(); + Tuple> pair = ICommandExecution.expand(prefix, true); + String label = pair.getFirst(); + List args = pair.getSecond(); if (args.isEmpty()) { return new TabCompleteHelper() .addCommands(this.baritone.getCommandManager()) @@ -105,4 +104,12 @@ public class CommandManager implements ICommandManager { return tabComplete(pair); } } + + private ICommandExecution from(Tuple> expanded) { + String label = expanded.getFirst(); + ArgConsumer args = new ArgConsumer(this, expanded.getSecond()); + + Command command = this.getCommand(label); + return command == null ? null : new CommandExecution(command, label, args); + } } From 8a396db80ea6f06c51ee203acacd0d69c4367c5a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 28 Sep 2019 16:28:58 -0700 Subject: [PATCH 677/682] fix brainlet block breaking issue --- src/main/java/baritone/utils/BlockBreakHelper.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index d1f3509e..26e82cd7 100644 --- a/src/main/java/baritone/utils/BlockBreakHelper.java +++ b/src/main/java/baritone/utils/BlockBreakHelper.java @@ -63,11 +63,12 @@ public final class BlockBreakHelper implements Helper { ctx.player().swingArm(EnumHand.MAIN_HAND); } + ctx.playerController().setHittingBlock(false); + didBreakLastTick = true; } else if (didBreakLastTick) { stopBreakingBlock(); didBreakLastTick = false; } - ctx.playerController().setHittingBlock(false); } } From 47e6a039effb82723370a8cfc009a909d1d1c6ab Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 30 Sep 2019 17:04:33 -0700 Subject: [PATCH 678/682] delet --- USAGE.md | 5 ++ .../command/defaults/ClearareaCommand.java | 80 ------------------- .../command/defaults/DefaultCommands.java | 1 - 3 files changed, 5 insertions(+), 81 deletions(-) delete mode 100644 src/main/java/baritone/utils/command/defaults/ClearareaCommand.java diff --git a/USAGE.md b/USAGE.md index 70737b1c..25fef11e 100644 --- a/USAGE.md +++ b/USAGE.md @@ -39,6 +39,11 @@ Some common examples: - `damn` daniel +New commands: +- `sel` to manage selections +- some others + + For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/utils/ExampleBaritoneControl.java). All the settings and documentation are here. If you find HTML easier to read than Javadoc, you can look here. diff --git a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java b/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java deleted file mode 100644 index 39f8809d..00000000 --- a/src/main/java/baritone/utils/command/defaults/ClearareaCommand.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.utils.command.defaults; - -import baritone.api.IBaritone; -import baritone.api.pathing.goals.Goal; -import baritone.api.pathing.goals.GoalBlock; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.command.Command; -import baritone.api.utils.command.datatypes.RelativeBlockPos; -import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.exception.CommandInvalidStateException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Stream; - -public class ClearareaCommand extends Command { - - public ClearareaCommand(IBaritone baritone) { - super(baritone, "cleararea"); - } - - @Override - protected void executed(String label, ArgConsumer args) throws CommandException { - BetterBlockPos pos1 = ctx.playerFeet(); - BetterBlockPos pos2; - if (args.hasAny()) { - args.requireMax(3); - pos2 = args.getDatatypePost(RelativeBlockPos.INSTANCE, pos1); - } else { - args.requireMax(0); - Goal goal = baritone.getCustomGoalProcess().getGoal(); - if (!(goal instanceof GoalBlock)) { - throw new CommandInvalidStateException("Goal is not a GoalBlock"); - } else { - pos2 = new BetterBlockPos(((GoalBlock) goal).getGoalPos()); - } - } - baritone.getBuilderProcess().clearArea(pos1, pos2); - logDirect("Success"); - } - - @Override - protected Stream tabCompleted(String label, ArgConsumer args) { - return args.tabCompleteDatatype(RelativeBlockPos.INSTANCE); - } - - @Override - public String getShortDesc() { - return "Clear an area of all blocks"; - } - - @Override - public List getLongDesc() { - return Arrays.asList( - "Clear an area of all blocks.", - "", - "Usage:", - "> cleararea - Clears the area marked by your current position and the current GoalBlock", - "> cleararea - Custom second corner rather than your goal" - ); - } -} diff --git a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java index 73ddda92..3f8e3908 100644 --- a/src/main/java/baritone/utils/command/defaults/DefaultCommands.java +++ b/src/main/java/baritone/utils/command/defaults/DefaultCommands.java @@ -46,7 +46,6 @@ public final class DefaultCommands { new ForceCancelCommand(baritone), new GcCommand(baritone), new InvertCommand(baritone), - new ClearareaCommand(baritone), new TunnelCommand(baritone), new RenderCommand(baritone), new FarmCommand(baritone), From f1fb109d40c48e79ba6ac18361d738873a05f7f2 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 30 Sep 2019 21:41:30 -0500 Subject: [PATCH 679/682] Remove ICommandExecution due to redundancy --- .../baritone/api/utils/command/Command.java | 30 +------ .../command/execution/ICommandExecution.java | 68 --------------- .../utils/command/BaritoneChatControl.java | 6 +- .../utils/command/defaults/AxisCommand.java | 4 +- .../command/defaults/BlacklistCommand.java | 4 +- .../utils/command/defaults/BuildCommand.java | 4 +- .../utils/command/defaults/CancelCommand.java | 4 +- .../utils/command/defaults/ChestsCommand.java | 4 +- .../utils/command/defaults/ClickCommand.java | 4 +- .../utils/command/defaults/ComeCommand.java | 4 +- .../utils/command/defaults/CommandAlias.java | 4 +- .../command/defaults/ExploreCommand.java | 4 +- .../defaults/ExploreFilterCommand.java | 4 +- .../utils/command/defaults/FarmCommand.java | 4 +- .../utils/command/defaults/FindCommand.java | 4 +- .../utils/command/defaults/FollowCommand.java | 4 +- .../command/defaults/ForceCancelCommand.java | 4 +- .../utils/command/defaults/GcCommand.java | 4 +- .../utils/command/defaults/GoalCommand.java | 4 +- .../utils/command/defaults/HelpCommand.java | 4 +- .../utils/command/defaults/InvertCommand.java | 4 +- .../utils/command/defaults/MineCommand.java | 4 +- .../utils/command/defaults/PathCommand.java | 4 +- .../command/defaults/PauseResumeCommands.java | 12 +-- .../utils/command/defaults/ProcCommand.java | 4 +- .../command/defaults/ReloadAllCommand.java | 4 +- .../utils/command/defaults/RenderCommand.java | 4 +- .../utils/command/defaults/RepackCommand.java | 4 +- .../command/defaults/SaveAllCommand.java | 4 +- .../command/defaults/SchematicaCommand.java | 4 +- .../utils/command/defaults/SelCommand.java | 4 +- .../utils/command/defaults/SetCommand.java | 4 +- .../command/defaults/ThisWayCommand.java | 4 +- .../utils/command/defaults/TunnelCommand.java | 4 +- .../command/defaults/VersionCommand.java | 4 +- .../command/defaults/WaypointsCommand.java | 4 +- .../command/execution/CommandExecution.java | 85 ------------------- .../utils/command/manager/CommandManager.java | 59 +++++++++++-- 38 files changed, 126 insertions(+), 262 deletions(-) delete mode 100644 src/api/java/baritone/api/utils/command/execution/ICommandExecution.java delete mode 100644 src/main/java/baritone/utils/command/execution/CommandExecution.java diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index e83d6c50..280c5f03 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -21,7 +21,6 @@ import baritone.api.IBaritone; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.execution.ICommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import java.util.Collections; @@ -57,41 +56,16 @@ public abstract class Command implements Helper { this(baritone, Collections.singletonList(name)); } - /** - * Executes this command with the specified arguments. - * - * @param execution The command execution to execute this command with - */ - public final void execute(ICommandExecution execution) throws CommandException { - this.executed(execution.getLabel(), execution.getArguments()); - } - - /** - * Tab completes this command with the specified arguments. Any exception that is thrown by - * {@link #tabCompleted(String, ArgConsumer)} will be caught by this method, and then {@link Stream#empty()} - * will be returned. - * - * @param execution The command execution to tab complete - * @return The list of completions. - */ - public final Stream tabComplete(ICommandExecution execution) { - try { - return this.tabCompleted(execution.getLabel(), execution.getArguments()); - } catch (Throwable t) { - return Stream.empty(); - } - } - /** * Called when this command is executed. */ - protected abstract void executed(String label, ArgConsumer args) throws CommandException; + public abstract void execute(String label, ArgConsumer args) throws CommandException; /** * Called when the command needs to tab complete. Return a Stream representing the entries to put in the completions * list. */ - protected abstract Stream tabCompleted(String label, ArgConsumer args) throws CommandException; + public abstract Stream tabComplete(String label, ArgConsumer args) throws CommandException; /** * @return A single-line string containing a short description of this command's purpose. diff --git a/src/api/java/baritone/api/utils/command/execution/ICommandExecution.java b/src/api/java/baritone/api/utils/command/execution/ICommandExecution.java deleted file mode 100644 index 4ca5b193..00000000 --- a/src/api/java/baritone/api/utils/command/execution/ICommandExecution.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.api.utils.command.execution; - -import baritone.api.utils.command.Command; -import baritone.api.utils.command.argument.CommandArgument; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; -import net.minecraft.util.Tuple; - -import java.util.List; -import java.util.stream.Stream; - -/** - * @author Brady - * @since 9/28/2019 - */ -public interface ICommandExecution { - - /** - * @return The label that was used to target the {@link Command} - */ - String getLabel(); - - /** - * @return The arguments to be passed to the {@link Command} - */ - ArgConsumer getArguments(); - - /** - * Executes the target command for this {@link ICommandExecution}. This method should never - * {@code throw} any exception, anything that is thrown during the target command execution - * should be safely handled. - */ - void execute(); - - /** - * Forwards this {@link ICommandExecution} to the target {@link Command} to perform a tab-completion. - * If the tab-completion operation is a failure, then {@link Stream#empty()} will be returned. - * - * @return The tab-completed arguments, if possible. - */ - Stream tabComplete(); - - static Tuple> expand(String string, boolean preserveEmptyLast) { - String label = string.split("\\s", 2)[0]; - List args = CommandArgument.from(string.substring(label.length()), preserveEmptyLast); - return new Tuple<>(label, args); - } - - static Tuple> expand(String string) { - return expand(string, false); - } -} diff --git a/src/main/java/baritone/utils/command/BaritoneChatControl.java b/src/main/java/baritone/utils/command/BaritoneChatControl.java index facc24da..30ba9244 100644 --- a/src/main/java/baritone/utils/command/BaritoneChatControl.java +++ b/src/main/java/baritone/utils/command/BaritoneChatControl.java @@ -29,10 +29,10 @@ import baritone.api.utils.SettingsUtil; import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.exception.CommandNotFoundException; -import baritone.api.utils.command.execution.ICommandExecution; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.manager.ICommandManager; +import baritone.utils.command.manager.CommandManager; import net.minecraft.util.Tuple; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; @@ -67,7 +67,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { event.cancel(); String commandStr = msg.substring(forceRun ? FORCE_COMMAND_PREFIX.length() : prefix.length()); if (!runCommand(commandStr) && !commandStr.trim().isEmpty()) { - new CommandNotFoundException(ICommandExecution.expand(commandStr).getFirst()).handle(null, null); + new CommandNotFoundException(CommandManager.expand(commandStr).getFirst()).handle(null, null); } } else if ((settings.chatControl.value || settings.chatControlAnyway.value) && runCommand(msg)) { event.cancel(); @@ -106,7 +106,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (msg.isEmpty()) { return this.runCommand("help"); } - Tuple> pair = ICommandExecution.expand(msg); + Tuple> pair = CommandManager.expand(msg); String command = pair.getFirst(); String rest = msg.substring(pair.getFirst().length()); ArgConsumer argc = new ArgConsumer(this.manager, pair.getSecond()); diff --git a/src/main/java/baritone/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java index ae52bfb2..f80356ad 100644 --- a/src/main/java/baritone/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -35,7 +35,7 @@ public class AxisCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); Goal goal = new GoalAxis(); baritone.getCustomGoalProcess().setGoal(goal); @@ -43,7 +43,7 @@ public class AxisCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index 21551782..43aaa737 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -35,7 +35,7 @@ public class BlacklistCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); IGetToBlockProcess proc = baritone.getGetToBlockProcess(); if (!proc.isActive()) { @@ -49,7 +49,7 @@ public class BlacklistCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index f4537113..5d084d48 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -42,7 +42,7 @@ public class BuildCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { File file = args.getDatatypePost(RelativeFile.INSTANCE, schematicsDir).getAbsoluteFile(); if (!file.getName().toLowerCase(Locale.US).endsWith(".schematic")) { file = new File(file.getAbsolutePath() + ".schematic"); @@ -64,7 +64,7 @@ public class BuildCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return RelativeFile.tabComplete(args, schematicsDir); } else if (args.has(2)) { diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index a4ef4cc7..67cde8f4 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -33,14 +33,14 @@ public class CancelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); baritone.getPathingBehavior().cancelEverything(); logDirect("ok canceled"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index d4101a62..f65a18e5 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -41,7 +41,7 @@ public class ChestsCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); Set> entries = ctx.worldData().getContainerMemory().getRememberedInventories().entrySet(); @@ -62,7 +62,7 @@ public class ChestsCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java index e5180b2f..07bd4de9 100644 --- a/src/main/java/baritone/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -33,14 +33,14 @@ public class ClickCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); baritone.openClick(); logDirect("aight dude"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index bbefeb43..52a0cec6 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -37,7 +37,7 @@ public class ComeCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); Entity entity = mc.getRenderViewEntity(); if (entity == null) { @@ -48,7 +48,7 @@ public class ComeCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/CommandAlias.java b/src/main/java/baritone/utils/command/defaults/CommandAlias.java index cbd8ac77..0f28e48e 100644 --- a/src/main/java/baritone/utils/command/defaults/CommandAlias.java +++ b/src/main/java/baritone/utils/command/defaults/CommandAlias.java @@ -43,12 +43,12 @@ public class CommandAlias extends Command { } @Override - protected void executed(String label, ArgConsumer args) { + public void execute(String label, ArgConsumer args) { this.baritone.getCommandManager().execute(String.format("%s %s", target, args.rawRest())); } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return this.baritone.getCommandManager().tabComplete(String.format("%s %s", target, args.rawRest())); } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index dc156d0e..55e3d756 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -35,7 +35,7 @@ public class ExploreCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { if (args.hasAny()) { args.requireExactly(2); } else { @@ -49,7 +49,7 @@ public class ExploreCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { if (args.hasAtMost(2)) { return args.tabCompleteDatatype(RelativeGoalXZ.INSTANCE); } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index 4d75d1b4..29f34c86 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -39,7 +39,7 @@ public class ExploreFilterCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(2); File file = args.getDatatypePost(RelativeFile.INSTANCE, mc.gameDir.getAbsoluteFile().getParentFile()); boolean invert = false; @@ -63,7 +63,7 @@ public class ExploreFilterCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return RelativeFile.tabComplete(args, RelativeFile.gameDir()); } diff --git a/src/main/java/baritone/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java index 1f803ec6..a9dc7a8b 100644 --- a/src/main/java/baritone/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -33,14 +33,14 @@ public class FarmCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); baritone.getFarmProcess().farm(); logDirect("Farming"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index 8848db81..513d6539 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -37,7 +37,7 @@ public class FindCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { List toFind = new ArrayList<>(); while (args.hasAny()) { toFind.add(args.getDatatypeFor(BlockById.INSTANCE)); @@ -59,7 +59,7 @@ public class FindCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return args.tabCompleteDatatype(BlockById.INSTANCE); } diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index e3e0c3d1..d2e674c9 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -42,7 +42,7 @@ public class FollowCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMin(1); FollowGroup group; FollowList list; @@ -88,7 +88,7 @@ public class FollowCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper() .append(FollowGroup.class) diff --git a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index 3de8a056..05b62992 100644 --- a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -34,7 +34,7 @@ public class ForceCancelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); IPathingBehavior pathingBehavior = baritone.getPathingBehavior(); pathingBehavior.cancelEverything(); @@ -43,7 +43,7 @@ public class ForceCancelCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index c2e7952c..068b5136 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -33,14 +33,14 @@ public class GcCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); System.gc(); logDirect("ok called System.gc()"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index 3f760111..baac24b6 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -39,7 +39,7 @@ public class GoalCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { ICustomGoalProcess goalProcess = baritone.getCustomGoalProcess(); if (args.hasAny() && Arrays.asList("reset", "clear", "none").contains(args.peekString())) { args.requireMax(1); @@ -59,7 +59,7 @@ public class GoalCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, ArgConsumer args) throws CommandException { TabCompleteHelper helper = new TabCompleteHelper(); if (args.hasExactlyOne()) { helper.append("reset", "clear", "none", "~"); diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index a9d0e104..7db0d893 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -44,7 +44,7 @@ public class HelpCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(1); if (!args.hasAny() || args.is(Integer.class)) { Paginator.paginate( @@ -97,7 +97,7 @@ public class HelpCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper() .addCommands(this.baritone.getCommandManager()) diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index f52e6226..232ac0f3 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -37,7 +37,7 @@ public class InvertCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; @@ -54,7 +54,7 @@ public class InvertCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index e77c3bd7..da92b098 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -38,7 +38,7 @@ public class MineCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { int quantity = args.getAsOrDefault(Integer.class, 0); args.requireMin(1); List boms = new ArrayList<>(); @@ -51,7 +51,7 @@ public class MineCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return args.tabCompleteDatatype(BlockById.INSTANCE); } diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index 4cd766ea..6de33373 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -40,7 +40,7 @@ public class PathCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; if (args.hasAny()) { @@ -56,7 +56,7 @@ public class PathCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, ArgConsumer args) throws CommandException { if (args.hasAny() && !args.has(4)) { while (args.has(2)) { if (args.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) == null) { diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index bc3c392a..2c363ff4 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -79,7 +79,7 @@ public class PauseResumeCommands { ); pauseCommand = new Command(baritone, "pause") { @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); if (paused[0]) { throw new CommandInvalidStateException("Already paused"); @@ -89,7 +89,7 @@ public class PauseResumeCommands { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } @@ -112,7 +112,7 @@ public class PauseResumeCommands { }; resumeCommand = new Command(baritone, "resume") { @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); if (!paused[0]) { throw new CommandInvalidStateException("Not paused"); @@ -122,7 +122,7 @@ public class PauseResumeCommands { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } @@ -143,13 +143,13 @@ public class PauseResumeCommands { }; pausedCommand = new Command(baritone, "paused") { @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); logDirect(String.format("Baritone is %spaused", paused[0] ? "" : "not ")); } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index 40d8e72b..232a53a2 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -37,7 +37,7 @@ public class ProcCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); IPathingControlManager pathingControlManager = baritone.getPathingControlManager(); IBaritoneProcess process = pathingControlManager.mostRecentInControl().orElse(null); @@ -62,7 +62,7 @@ public class ProcCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index c16000f7..f13af77d 100644 --- a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -33,14 +33,14 @@ public class ReloadAllCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); ctx.worldData().getCachedWorld().reloadAllFromDisk(); logDirect("Reloaded"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index 7c100c8e..710df10f 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -34,7 +34,7 @@ public class RenderCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); BetterBlockPos origin = ctx.playerFeet(); int renderDistance = (mc.gameSettings.renderDistanceChunks + 1) * 16; @@ -50,7 +50,7 @@ public class RenderCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java index bd918f09..2f1a988d 100644 --- a/src/main/java/baritone/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -34,13 +34,13 @@ public class RepackCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); logDirect(String.format("Queued %d chunks for repacking", WorldScanner.INSTANCE.repack(ctx))); } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index 8343f753..21dbfb64 100644 --- a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -33,14 +33,14 @@ public class SaveAllCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); ctx.worldData().getCachedWorld().save(); logDirect("Saved"); } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index 91e31daa..ed695169 100644 --- a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -33,13 +33,13 @@ public class SchematicaCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); baritone.getBuilderProcess().buildOpenSchematic(); } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index d9899f42..8e2512d1 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -75,7 +75,7 @@ public class SelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { Action action = Action.getByName(args.getString()); if (action == null) { throw new CommandInvalidTypeException(args.consumed(), "an action"); @@ -186,7 +186,7 @@ public class SelCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, ArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper() .append(Action.getAllNames()) diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index 48c4580f..8add3fed 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -50,7 +50,7 @@ public class SetCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { String arg = args.hasAny() ? args.getString().toLowerCase(Locale.US) : "list"; if (Arrays.asList("s", "save").contains(arg)) { SettingsUtil.save(Baritone.settings()); @@ -186,7 +186,7 @@ public class SetCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, ArgConsumer args) throws CommandException { if (args.hasAny()) { String arg = args.getString(); if (args.hasExactlyOne() && !Arrays.asList("s", "save").contains(args.peekString().toLowerCase(Locale.US))) { diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index 4c6f3522..d11346cc 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -34,7 +34,7 @@ public class ThisWayCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireExactly(1); GoalXZ goal = GoalXZ.fromDirection( ctx.playerFeetAsVec(), @@ -46,7 +46,7 @@ public class ThisWayCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index 588287d6..b7e00fe6 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -35,7 +35,7 @@ public class TunnelCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); Goal goal = new GoalStrictDirection( ctx.playerFeet(), @@ -46,7 +46,7 @@ public class TunnelCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index fe53f523..89dc6576 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -34,7 +34,7 @@ public class VersionCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { args.requireMax(0); String version = getClass().getPackage().getImplementationVersion(); if (version == null) { @@ -45,7 +45,7 @@ public class VersionCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) { + public Stream tabComplete(String label, ArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 01f5817e..45bd7b50 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -52,7 +52,7 @@ public class WaypointsCommand extends Command { } @Override - protected void executed(String label, ArgConsumer args) throws CommandException { + public void execute(String label, ArgConsumer args) throws CommandException { Action action = args.hasAny() ? Action.getByName(args.getString()) : Action.LIST; if (action == null) { throw new CommandInvalidTypeException(args.consumed(), "an action"); @@ -241,7 +241,7 @@ public class WaypointsCommand extends Command { } @Override - protected Stream tabCompleted(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, ArgConsumer args) throws CommandException { if (args.hasAny()) { if (args.hasExactlyOne()) { return new TabCompleteHelper() diff --git a/src/main/java/baritone/utils/command/execution/CommandExecution.java b/src/main/java/baritone/utils/command/execution/CommandExecution.java deleted file mode 100644 index 1e8fe838..00000000 --- a/src/main/java/baritone/utils/command/execution/CommandExecution.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.utils.command.execution; - -import baritone.api.utils.command.Command; -import baritone.api.utils.command.exception.CommandUnhandledException; -import baritone.api.utils.command.exception.ICommandException; -import baritone.api.utils.command.execution.ICommandExecution; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; -import baritone.utils.command.manager.CommandManager; - -import java.util.stream.Stream; - -/** - * The default, internal implementation of {@link ICommandExecution}, which is used by {@link CommandManager} - * - * @author LoganDark, Brady - */ -public class CommandExecution implements ICommandExecution { - - /** - * The command itself - */ - private final Command command; - - /** - * The name this command was called with - */ - private final String label; - - /** - * The arg consumer - */ - private final ArgConsumer args; - - public CommandExecution(Command command, String label, ArgConsumer args) { - this.command = command; - this.label = label; - this.args = args; - } - - @Override - public String getLabel() { - return this.label; - } - - @Override - public ArgConsumer getArguments() { - return this.args; - } - - @Override - public void execute() { - try { - command.execute(this); - } catch (Throwable t) { - // Create a handleable exception, wrap if needed - ICommandException exception = t instanceof ICommandException - ? (ICommandException) t - : new CommandUnhandledException(t); - - exception.handle(command, args.args); - } - } - - @Override - public Stream tabComplete() { - return command.tabComplete(this); - } -} diff --git a/src/main/java/baritone/utils/command/manager/CommandManager.java b/src/main/java/baritone/utils/command/manager/CommandManager.java index e5c5d035..c9c51eb1 100644 --- a/src/main/java/baritone/utils/command/manager/CommandManager.java +++ b/src/main/java/baritone/utils/command/manager/CommandManager.java @@ -21,13 +21,13 @@ import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.argument.CommandArgument; -import baritone.api.utils.command.execution.ICommandExecution; +import baritone.api.utils.command.exception.CommandUnhandledException; +import baritone.api.utils.command.exception.ICommandException; import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.manager.ICommandManager; import baritone.api.utils.command.registry.Registry; import baritone.utils.command.defaults.DefaultCommands; -import baritone.utils.command.execution.CommandExecution; import net.minecraft.util.Tuple; import java.util.List; @@ -72,12 +72,12 @@ public class CommandManager implements ICommandManager { @Override public boolean execute(String string) { - return this.execute(ICommandExecution.expand(string)); + return this.execute(expand(string)); } @Override public boolean execute(Tuple> expanded) { - ICommandExecution execution = this.from(expanded); + ExecutionWrapper execution = this.from(expanded); if (execution != null) { execution.execute(); } @@ -86,13 +86,13 @@ public class CommandManager implements ICommandManager { @Override public Stream tabComplete(Tuple> expanded) { - ICommandExecution execution = this.from(expanded); + ExecutionWrapper execution = this.from(expanded); return execution == null ? Stream.empty() : execution.tabComplete(); } @Override public Stream tabComplete(String prefix) { - Tuple> pair = ICommandExecution.expand(prefix, true); + Tuple> pair = expand(prefix, true); String label = pair.getFirst(); List args = pair.getSecond(); if (args.isEmpty()) { @@ -105,11 +105,54 @@ public class CommandManager implements ICommandManager { } } - private ICommandExecution from(Tuple> expanded) { + private ExecutionWrapper from(Tuple> expanded) { String label = expanded.getFirst(); ArgConsumer args = new ArgConsumer(this, expanded.getSecond()); Command command = this.getCommand(label); - return command == null ? null : new CommandExecution(command, label, args); + return command == null ? null : new ExecutionWrapper(command, label, args); + } + + private static Tuple> expand(String string, boolean preserveEmptyLast) { + String label = string.split("\\s", 2)[0]; + List args = CommandArgument.from(string.substring(label.length()), preserveEmptyLast); + return new Tuple<>(label, args); + } + + public static Tuple> expand(String string) { + return expand(string, false); + } + + private static final class ExecutionWrapper { + private Command command; + private String label; + private ArgConsumer args; + + private ExecutionWrapper(Command command, String label, ArgConsumer args) { + this.command = command; + this.label = label; + this.args = args; + } + + private void execute() { + try { + this.command.execute(this.label, this.args); + } catch (Throwable t) { + // Create a handleable exception, wrap if needed + ICommandException exception = t instanceof ICommandException + ? (ICommandException) t + : new CommandUnhandledException(t); + + exception.handle(command, args.args); + } + } + + private Stream tabComplete() { + try { + return this.command.tabComplete(this.label, this.args); + } catch (Throwable t) { + return Stream.empty(); + } + } } } From 089c5fb0951c64e0c30059a34b788bf43c64d17d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 1 Oct 2019 14:29:19 -0700 Subject: [PATCH 680/682] fix buildinlayers crash --- src/main/java/baritone/process/BuilderProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index ab1400f8..cd15f283 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -363,7 +363,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil @Override public boolean inSchematic(int x, int y, int z, IBlockState currentState) { - return ISchematic.super.inSchematic(x, y, z, currentState) && y >= minYInclusive && y <= maxYInclusive; + return ISchematic.super.inSchematic(x, y, z, currentState) && y >= minYInclusive && y <= maxYInclusive && realSchematic.inSchematic(x, y, z, currentState); } @Override From 3a3d880d814f70cee2fb0eb8aa7c4853502f9e7c Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 4 Oct 2019 08:55:02 -0500 Subject: [PATCH 681/682] ArgConsumer API separation --- .../baritone/api/utils/command/Command.java | 6 +- .../command/argparser/ArgParserManager.java | 7 +- .../command/argparser/DefaultArgParsers.java | 22 +- .../utils/command/argparser/IArgParser.java | 10 +- .../command/argument/CommandArgument.java | 170 ------- .../command/argument/ICommandArgument.java | 102 ++++ .../utils/command/datatypes/IDatatype.java | 6 +- .../command/datatypes/IDatatypeContext.java | 8 +- .../command/datatypes/RelativeBlockPos.java | 6 +- .../command/datatypes/RelativeCoordinate.java | 4 +- .../utils/command/datatypes/RelativeFile.java | 4 +- .../utils/command/datatypes/RelativeGoal.java | 6 +- .../command/datatypes/RelativeGoalBlock.java | 6 +- .../command/datatypes/RelativeGoalXZ.java | 6 +- .../command/datatypes/RelativeGoalYLevel.java | 4 +- .../CommandInvalidArgumentException.java | 8 +- .../CommandInvalidTypeException.java | 10 +- .../exception/CommandNotFoundException.java | 4 +- .../exception/CommandUnhandledException.java | 4 +- .../command/exception/ICommandException.java | 4 +- .../{ArgConsumer.java => IArgConsumer.java} | 425 ++++------------- .../command/helpers/pagination/Paginator.java | 28 +- .../tabcomplete/TabCompleteHelper.java | 5 +- .../command/manager/ICommandManager.java | 6 +- .../utils/command/BaritoneChatControl.java | 11 +- .../command/argument/CommandArgument.java | 97 ++++ .../command/argument/CommandArguments.java | 79 ++++ .../utils/command/defaults/AxisCommand.java | 6 +- .../command/defaults/BlacklistCommand.java | 6 +- .../utils/command/defaults/BuildCommand.java | 6 +- .../utils/command/defaults/CancelCommand.java | 6 +- .../utils/command/defaults/ChestsCommand.java | 6 +- .../utils/command/defaults/ClickCommand.java | 6 +- .../utils/command/defaults/ComeCommand.java | 6 +- .../utils/command/defaults/CommandAlias.java | 6 +- .../command/defaults/ExploreCommand.java | 6 +- .../defaults/ExploreFilterCommand.java | 6 +- .../utils/command/defaults/FarmCommand.java | 6 +- .../utils/command/defaults/FindCommand.java | 6 +- .../utils/command/defaults/FollowCommand.java | 6 +- .../command/defaults/ForceCancelCommand.java | 6 +- .../utils/command/defaults/GcCommand.java | 6 +- .../utils/command/defaults/GoalCommand.java | 6 +- .../utils/command/defaults/HelpCommand.java | 6 +- .../utils/command/defaults/InvertCommand.java | 6 +- .../utils/command/defaults/MineCommand.java | 6 +- .../utils/command/defaults/PathCommand.java | 6 +- .../command/defaults/PauseResumeCommands.java | 14 +- .../utils/command/defaults/ProcCommand.java | 6 +- .../command/defaults/ReloadAllCommand.java | 6 +- .../utils/command/defaults/RenderCommand.java | 6 +- .../utils/command/defaults/RepackCommand.java | 6 +- .../command/defaults/SaveAllCommand.java | 6 +- .../command/defaults/SchematicaCommand.java | 6 +- .../utils/command/defaults/SelCommand.java | 6 +- .../utils/command/defaults/SetCommand.java | 6 +- .../command/defaults/ThisWayCommand.java | 6 +- .../utils/command/defaults/TunnelCommand.java | 6 +- .../command/defaults/VersionCommand.java | 6 +- .../command/defaults/WaypointsCommand.java | 6 +- .../helpers/arguments/ArgConsumer.java | 444 ++++++++++++++++++ .../utils/command/manager/CommandManager.java | 23 +- 62 files changed, 1025 insertions(+), 696 deletions(-) delete mode 100644 src/api/java/baritone/api/utils/command/argument/CommandArgument.java create mode 100644 src/api/java/baritone/api/utils/command/argument/ICommandArgument.java rename src/api/java/baritone/api/utils/command/helpers/arguments/{ArgConsumer.java => IArgConsumer.java} (58%) create mode 100644 src/main/java/baritone/utils/command/argument/CommandArgument.java create mode 100644 src/main/java/baritone/utils/command/argument/CommandArguments.java create mode 100644 src/main/java/baritone/utils/command/helpers/arguments/ArgConsumer.java diff --git a/src/api/java/baritone/api/utils/command/Command.java b/src/api/java/baritone/api/utils/command/Command.java index 280c5f03..ba4ed938 100644 --- a/src/api/java/baritone/api/utils/command/Command.java +++ b/src/api/java/baritone/api/utils/command/Command.java @@ -21,7 +21,7 @@ import baritone.api.IBaritone; import baritone.api.utils.Helper; import baritone.api.utils.IPlayerContext; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Collections; import java.util.List; @@ -59,13 +59,13 @@ public abstract class Command implements Helper { /** * Called when this command is executed. */ - public abstract void execute(String label, ArgConsumer args) throws CommandException; + public abstract void execute(String label, IArgConsumer args) throws CommandException; /** * Called when the command needs to tab complete. Return a Stream representing the entries to put in the completions * list. */ - public abstract Stream tabComplete(String label, ArgConsumer args) throws CommandException; + public abstract Stream tabComplete(String label, IArgConsumer args) throws CommandException; /** * @return A single-line string containing a short description of this command's purpose. diff --git a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java index 1b0730c6..2b864f42 100644 --- a/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java +++ b/src/api/java/baritone/api/utils/command/argparser/ArgParserManager.java @@ -17,10 +17,9 @@ package baritone.api.utils.command.argparser; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.exception.CommandNoParserForTypeException; -import baritone.api.utils.command.exception.CommandUnhandledException; import baritone.api.utils.command.registry.Registry; public class ArgParserManager { @@ -69,7 +68,7 @@ public class ArgParserManager { * @return An instance of the specified class. * @throws CommandInvalidTypeException If the parsing failed */ - public static T parseStateless(Class type, CommandArgument arg) throws CommandInvalidTypeException { + public static T parseStateless(Class type, ICommandArgument arg) throws CommandInvalidTypeException { IArgParser.Stateless parser = getParserStateless(type); if (parser == null) { throw new CommandNoParserForTypeException(type); @@ -91,7 +90,7 @@ public class ArgParserManager { * @throws CommandInvalidTypeException If the parsing failed * @see IArgParser.Stated */ - public static T parseStated(Class type, Class stateKlass, CommandArgument arg, S state) throws CommandInvalidTypeException { + public static T parseStated(Class type, Class stateKlass, ICommandArgument arg, S state) throws CommandInvalidTypeException { IArgParser.Stated parser = getParserStated(type, stateKlass); if (parser == null) { throw new CommandNoParserForTypeException(type); diff --git a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java index c33f61fb..b734f47d 100644 --- a/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java +++ b/src/api/java/baritone/api/utils/command/argparser/DefaultArgParsers.java @@ -17,7 +17,7 @@ package baritone.api.utils.command.argparser; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; import java.util.Arrays; import java.util.List; @@ -34,8 +34,8 @@ public class DefaultArgParsers { } @Override - public Integer parseArg(CommandArgument arg) throws RuntimeException { - return Integer.parseInt(arg.value); + public Integer parseArg(ICommandArgument arg) throws RuntimeException { + return Integer.parseInt(arg.getValue()); } } @@ -48,8 +48,8 @@ public class DefaultArgParsers { } @Override - public Long parseArg(CommandArgument arg) throws RuntimeException { - return Long.parseLong(arg.value); + public Long parseArg(ICommandArgument arg) throws RuntimeException { + return Long.parseLong(arg.getValue()); } } @@ -62,8 +62,8 @@ public class DefaultArgParsers { } @Override - public Float parseArg(CommandArgument arg) throws RuntimeException { - String value = arg.value; + public Float parseArg(ICommandArgument arg) throws RuntimeException { + String value = arg.getValue(); if (!value.matches("^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$")) { throw new IllegalArgumentException("failed float format check"); } @@ -80,8 +80,8 @@ public class DefaultArgParsers { } @Override - public Double parseArg(CommandArgument arg) throws RuntimeException { - String value = arg.value; + public Double parseArg(ICommandArgument arg) throws RuntimeException { + String value = arg.getValue(); if (!value.matches("^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)|)$")) { throw new IllegalArgumentException("failed double format check"); } @@ -101,8 +101,8 @@ public class DefaultArgParsers { } @Override - public Boolean parseArg(CommandArgument arg) throws RuntimeException { - String value = arg.value; + public Boolean parseArg(ICommandArgument arg) throws RuntimeException { + String value = arg.getValue(); if (TRUTHY_VALUES.contains(value.toLowerCase(Locale.US))) { return true; } else if (FALSY_VALUES.contains(value.toLowerCase(Locale.US))) { diff --git a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java index 09e2aa2e..c1f615f6 100644 --- a/src/api/java/baritone/api/utils/command/argparser/IArgParser.java +++ b/src/api/java/baritone/api/utils/command/argparser/IArgParser.java @@ -17,7 +17,7 @@ package baritone.api.utils.command.argparser; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; public interface IArgParser { @@ -27,7 +27,7 @@ public interface IArgParser { Class getTarget(); /** - * A stateless argument parser is just that. It takes a {@link CommandArgument} and outputs its type. + * A stateless argument parser is just that. It takes a {@link ICommandArgument} and outputs its type. * * @see ArgParserManager#REGISTRY */ @@ -39,11 +39,11 @@ public interface IArgParser { * @throws RuntimeException if you want the parsing to fail. The exception will be caught and turned into an * appropriate error. */ - T parseArg(CommandArgument arg) throws Exception; + T parseArg(ICommandArgument arg) throws Exception; } /** - * A stated argument parser is similar to a stateless one. It also takes a {@link CommandArgument}, but it also + * A stated argument parser is similar to a stateless one. It also takes a {@link ICommandArgument}, but it also * takes a second argument that can be any type, referred to as the state. * * @see ArgParserManager#REGISTRY @@ -59,6 +59,6 @@ public interface IArgParser { * @throws RuntimeException if you want the parsing to fail. The exception will be caught and turned into an * appropriate error. */ - T parseArg(CommandArgument arg, S state) throws Exception; + T parseArg(ICommandArgument arg, S state) throws Exception; } } diff --git a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java b/src/api/java/baritone/api/utils/command/argument/CommandArgument.java deleted file mode 100644 index a5b044c4..00000000 --- a/src/api/java/baritone/api/utils/command/argument/CommandArgument.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.api.utils.command.argument; - -import baritone.api.utils.command.argparser.ArgParserManager; -import baritone.api.utils.command.argparser.IArgParser; -import baritone.api.utils.command.exception.CommandInvalidArgumentException; -import baritone.api.utils.command.exception.CommandInvalidTypeException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; -import net.minecraft.util.EnumFacing; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -/** - * A {@link CommandArgument} is an immutable object representing one command argument. It contains data on the index of - * that argument, its value, and the rest of the string that argument was found in - *

    - * You're recommended to use {@link ArgConsumer}s to handle these. - */ -public class CommandArgument { - - public final int index; - public final String value; - public final String rawRest; - public final static Pattern argPattern = Pattern.compile("\\S+"); - - private CommandArgument(int index, String value, String rawRest) { - this.index = index; - this.value = value; - this.rawRest = rawRest; - } - - /** - * Gets an enum value from the enum class with the same name as this argument's value - *

    - * For example if you getEnum as an {@link EnumFacing}, and this argument's value is "up", it will return {@link - * EnumFacing#UP} - * - * @param enumClass The enum class to search - * @return An enum constant of that class with the same name as this argument's value - * @throws CommandInvalidTypeException If the constant couldn't be found - * @see ArgConsumer#peekEnum(Class) - * @see ArgConsumer#peekEnum(Class, int) - * @see ArgConsumer#peekEnumOrNull(Class) - * @see ArgConsumer#peekEnumOrNull(Class, int) - * @see ArgConsumer#getEnum(Class) - * @see ArgConsumer#getEnumOrNull(Class) - */ - public > E getEnum(Class enumClass) throws CommandInvalidTypeException { - return Stream.of(enumClass.getEnumConstants()) - .filter(e -> e.name().equalsIgnoreCase(value)) - .findFirst() - .orElseThrow(() -> new CommandInvalidTypeException(this, enumClass.getSimpleName())); - } - - /** - * Tries to use a stateless {@link IArgParser} to parse this argument into the specified class - * - * @param type The class to parse this argument into - * @return An instance of the specified type - * @throws CommandInvalidTypeException If the parsing failed - */ - public T getAs(Class type) throws CommandInvalidTypeException { - return ArgParserManager.parseStateless(type, this); - } - - /** - * Tries to use a stateless {@link IArgParser} to parse this argument into the specified class - * - * @param type The class to parse this argument into - * @return If the parser succeeded - */ - public boolean is(Class type) { - try { - getAs(type); - return true; - } catch (Throwable t) { - return false; - } - } - - /** - * Tries to use a stated {@link IArgParser} to parse this argument into the specified class - * - * @param type The class to parse this argument into - * @return An instance of the specified type - * @throws CommandInvalidTypeException If the parsing failed - */ - @SuppressWarnings("UnusedReturnValue") - public T getAs(Class type, Class stateType, S state) throws CommandInvalidTypeException { - return ArgParserManager.parseStated(type, stateType, this, state); - } - - /** - * Tries to use a stated {@link IArgParser} to parse this argument into the specified class - * - * @param type The class to parse this argument into - * @return If the parser succeeded - */ - public boolean is(Class type, Class stateType, S state) { - try { - getAs(type, stateType, state); - return true; - } catch (Throwable t) { - return false; - } - } - - /** - * Turn a string into a list of {@link CommandArgument}s. This is needed because of {@link CommandArgument#rawRest} - * - * @param string The string to convert - * @param preserveEmptyLast If the string ends with whitespace, add an empty {@link CommandArgument} to the end This - * is useful for tab completion - * @return A list of {@link CommandArgument}s - */ - public static List from(String string, boolean preserveEmptyLast) { - List args = new ArrayList<>(); - Matcher argMatcher = argPattern.matcher(string); - int lastEnd = -1; - while (argMatcher.find()) { - args.add(new CommandArgument( - args.size(), - argMatcher.group(), - string.substring(argMatcher.start()) - )); - lastEnd = argMatcher.end(); - } - if (preserveEmptyLast && lastEnd < string.length()) { - args.add(new CommandArgument(args.size(), "", "")); - } - return args; - } - - /** - * @see #from(String, boolean) - */ - public static List from(String string) { - return from(string, false); - } - - /** - * Returns an "unknown" {@link CommandArgument}. This shouldn't be used unless you absolutely have no information - - * ESPECIALLY not with {@link CommandInvalidArgumentException}s - * - * @return The unknown {@link CommandArgument} - */ - public static CommandArgument unknown() { - return new CommandArgument(-1, "", ""); - } -} diff --git a/src/api/java/baritone/api/utils/command/argument/ICommandArgument.java b/src/api/java/baritone/api/utils/command/argument/ICommandArgument.java new file mode 100644 index 00000000..7cbe2540 --- /dev/null +++ b/src/api/java/baritone/api/utils/command/argument/ICommandArgument.java @@ -0,0 +1,102 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.api.utils.command.argument; + +import baritone.api.utils.command.argparser.IArgParser; +import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; +import net.minecraft.util.EnumFacing; + +/** + * A {@link ICommandArgument} is an immutable object representing one command argument. It contains data on the index of + * that argument, its value, and the rest of the string that argument was found in + *

    + * You're recommended to use {@link IArgConsumer}}s to handle these. + * + * @author Brady + * @since 10/2/2019 + */ +public interface ICommandArgument { + + /** + * @return The index of this command argument in the list of command arguments generated + */ + int getIndex(); + + /** + * @return The raw value of just this argument + */ + String getValue(); + + /** + * @return The raw value of the remaining arguments after this one was captured + */ + String getRawRest(); + + /** + * Gets an enum value from the enum class with the same name as this argument's value + *

    + * For example if you getEnum as an {@link EnumFacing}, and this argument's value is "up", it will return {@link + * EnumFacing#UP} + * + * @param enumClass The enum class to search + * @return An enum constant of that class with the same name as this argument's value + * @throws CommandInvalidTypeException If the constant couldn't be found + * @see IArgConsumer#peekEnum(Class) + * @see IArgConsumer#peekEnum(Class, int) + * @see IArgConsumer#peekEnumOrNull(Class) + * @see IArgConsumer#peekEnumOrNull(Class, int) + * @see IArgConsumer#getEnum(Class) + * @see IArgConsumer#getEnumOrNull(Class) + */ + > E getEnum(Class enumClass) throws CommandInvalidTypeException; + + /** + * Tries to use a stateless {@link IArgParser} to parse this argument into the specified class + * + * @param type The class to parse this argument into + * @return An instance of the specified type + * @throws CommandInvalidTypeException If the parsing failed + */ + T getAs(Class type) throws CommandInvalidTypeException; + + /** + * Tries to use a stateless {@link IArgParser} to parse this argument into the specified class + * + * @param type The class to parse this argument into + * @return If the parser succeeded + */ + boolean is(Class type); + + /** + * Tries to use a stated {@link IArgParser} to parse this argument into the specified class + * + * @param type The class to parse this argument into + * @return An instance of the specified type + * @throws CommandInvalidTypeException If the parsing failed + */ + T getAs(Class type, Class stateType, S state) throws CommandInvalidTypeException; + + /** + * Tries to use a stated {@link IArgParser} to parse this argument into the specified class + * + * @param type The class to parse this argument into + * @return If the parser succeeded + */ + boolean is(Class type, Class stateType, S state); +} diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java index 8c155fb6..36a37fec 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatype.java @@ -19,7 +19,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.argparser.IArgParser; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.stream.Stream; @@ -41,7 +41,7 @@ import java.util.stream.Stream; public interface IDatatype { /** - * Attempts to complete missing or partial input provided through the {@link ArgConsumer} provided by + * Attempts to complete missing or partial input provided through the {@link IArgConsumer}} provided by * {@link IDatatypeContext#getConsumer()} in order to aide the user in executing commands. *

    * One benefit over datatypes over {@link IArgParser}s is that instead of each command trying to guess what values @@ -50,7 +50,7 @@ public interface IDatatype { * * @param ctx The argument consumer to tab complete * @return A stream representing the strings that can be tab completed. DO NOT INCLUDE SPACES IN ANY STRINGS. - * @see ArgConsumer#tabCompleteDatatype(IDatatype) + * @see IArgConsumer#tabCompleteDatatype(IDatatype) */ Stream tabComplete(IDatatypeContext ctx) throws CommandException; } diff --git a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeContext.java b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeContext.java index 1452bf4a..33f3ad23 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/IDatatypeContext.java +++ b/src/api/java/baritone/api/utils/command/datatypes/IDatatypeContext.java @@ -18,7 +18,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.IBaritone; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; /** * Provides an {@link IDatatype} with contextual information so @@ -39,9 +39,9 @@ public interface IDatatypeContext { IBaritone getBaritone(); /** - * Provides the {@link ArgConsumer} to fetch input information from. + * Provides the {@link IArgConsumer}} to fetch input information from. * - * @return The context {@link ArgConsumer}. + * @return The context {@link IArgConsumer}}. */ - ArgConsumer getConsumer(); + IArgConsumer getConsumer(); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java index 8459db88..4a876220 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeBlockPos.java @@ -19,7 +19,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.stream.Stream; @@ -32,7 +32,7 @@ public enum RelativeBlockPos implements IDatatypePost tabComplete(IDatatypeContext ctx) throws CommandException { - final ArgConsumer consumer = ctx.getConsumer(); + final IArgConsumer consumer = ctx.getConsumer(); if (consumer.hasAny() && !consumer.has(4)) { while (consumer.has(2)) { if (consumer.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) == null) { diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java index 84a29f63..7ef3532a 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeCoordinate.java @@ -18,7 +18,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -51,7 +51,7 @@ public enum RelativeCoordinate implements IDatatypePost { @Override public Stream tabComplete(IDatatypeContext ctx) throws CommandException { - final ArgConsumer consumer = ctx.getConsumer(); + final IArgConsumer consumer = ctx.getConsumer(); if (!consumer.has(2) && consumer.getString().matches("^(~|$)")) { return Stream.of("~"); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java index 71a9ca58..0ad4b88b 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeFile.java @@ -18,7 +18,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.io.File; import java.io.IOException; @@ -70,7 +70,7 @@ public enum RelativeFile implements IDatatypePost { } } - public static Stream tabComplete(ArgConsumer consumer, File base0) throws CommandException { + public static Stream tabComplete(IArgConsumer consumer, File base0) throws CommandException { // I will not make the caller deal with this, seriously // Tab complete code is beautiful and I'm not going to bloat it with dumb ass checked exception bullshit -LoganDark diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java index d47e05ce..0c98073f 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoal.java @@ -23,7 +23,7 @@ import baritone.api.pathing.goals.GoalXZ; import baritone.api.pathing.goals.GoalYLevel; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import net.minecraft.util.math.MathHelper; import java.util.ArrayList; @@ -38,10 +38,10 @@ public enum RelativeGoal implements IDatatypePost { if (origin == null) { origin = BetterBlockPos.ORIGIN; } - final ArgConsumer consumer = ctx.getConsumer(); + final IArgConsumer consumer = ctx.getConsumer(); List> coords = new ArrayList<>(); - final ArgConsumer copy = consumer.copy(); // This is a hack and should be fixed in the future probably + final IArgConsumer copy = consumer.copy(); // This is a hack and should be fixed in the future probably for (int i = 0; i < 3; i++) { if (copy.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) != null) { coords.add(o -> consumer.getDatatypePost(RelativeCoordinate.INSTANCE, o)); diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java index cd1c0be1..b3c0e284 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalBlock.java @@ -20,7 +20,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import net.minecraft.util.math.MathHelper; import java.util.stream.Stream; @@ -34,7 +34,7 @@ public enum RelativeGoalBlock implements IDatatypePost tabComplete(IDatatypeContext ctx) { - final ArgConsumer consumer = ctx.getConsumer(); + final IArgConsumer consumer = ctx.getConsumer(); if (consumer.hasAtMost(3)) { return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java index b8bd0cd6..22d50ebf 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalXZ.java @@ -20,7 +20,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import net.minecraft.util.math.MathHelper; import java.util.stream.Stream; @@ -34,7 +34,7 @@ public enum RelativeGoalXZ implements IDatatypePost { origin = BetterBlockPos.ORIGIN; } - final ArgConsumer consumer = ctx.getConsumer(); + final IArgConsumer consumer = ctx.getConsumer(); return new GoalXZ( MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x)), MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y)) @@ -43,7 +43,7 @@ public enum RelativeGoalXZ implements IDatatypePost { @Override public Stream tabComplete(IDatatypeContext ctx) { - final ArgConsumer consumer = ctx.getConsumer(); + final IArgConsumer consumer = ctx.getConsumer(); if (consumer.hasAtMost(2)) { return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE); } diff --git a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java index a8a9b232..7a443b27 100644 --- a/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java +++ b/src/api/java/baritone/api/utils/command/datatypes/RelativeGoalYLevel.java @@ -20,7 +20,7 @@ package baritone.api.utils.command.datatypes; import baritone.api.pathing.goals.GoalYLevel; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import net.minecraft.util.math.MathHelper; import java.util.stream.Stream; @@ -41,7 +41,7 @@ public enum RelativeGoalYLevel implements IDatatypePost tabComplete(IDatatypeContext ctx) { - final ArgConsumer consumer = ctx.getConsumer(); + final IArgConsumer consumer = ctx.getConsumer(); if (consumer.hasAtMost(1)) { return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE); } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java b/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java index 62706705..bc9236e4 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandInvalidArgumentException.java @@ -17,16 +17,16 @@ package baritone.api.utils.command.exception; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; public abstract class CommandInvalidArgumentException extends CommandErrorMessageException { - public final CommandArgument arg; + public final ICommandArgument arg; - protected CommandInvalidArgumentException(CommandArgument arg, String reason) { + protected CommandInvalidArgumentException(ICommandArgument arg, String reason) { super(String.format( "Error at argument #%s: %s", - arg.index == -1 ? "" : Integer.toString(arg.index + 1), + arg.getIndex() == -1 ? "" : Integer.toString(arg.getIndex() + 1), reason )); this.arg = arg; diff --git a/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java b/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java index 5e5b81cd..8dffe1d0 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandInvalidTypeException.java @@ -17,23 +17,23 @@ package baritone.api.utils.command.exception; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; public class CommandInvalidTypeException extends CommandInvalidArgumentException { - public CommandInvalidTypeException(CommandArgument arg, String expected) { + public CommandInvalidTypeException(ICommandArgument arg, String expected) { super(arg, String.format("Expected %s", expected)); } - public CommandInvalidTypeException(CommandArgument arg, String expected, Throwable cause) { + public CommandInvalidTypeException(ICommandArgument arg, String expected, Throwable cause) { super(arg, String.format("Expected %s.\nMore details: %s", expected, cause.getMessage())); } - public CommandInvalidTypeException(CommandArgument arg, String expected, String got) { + public CommandInvalidTypeException(ICommandArgument arg, String expected, String got) { super(arg, String.format("Expected %s, but got %s instead", expected, got)); } - public CommandInvalidTypeException(CommandArgument arg, String expected, String got, Throwable cause) { + public CommandInvalidTypeException(ICommandArgument arg, String expected, String got, Throwable cause) { super(arg, String.format("Expected %s, but got %s instead.\nMore details: %s", expected, got, cause.getMessage())); } } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java b/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java index e8904cbc..bca8d543 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandNotFoundException.java @@ -18,7 +18,7 @@ package baritone.api.utils.command.exception; import baritone.api.utils.command.Command; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; import java.util.List; @@ -34,7 +34,7 @@ public class CommandNotFoundException extends CommandException { } @Override - public void handle(Command command, List args) { + public void handle(Command command, List args) { HELPER.logDirect(getMessage()); } } diff --git a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java index 6d647a20..55b359cc 100644 --- a/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java +++ b/src/api/java/baritone/api/utils/command/exception/CommandUnhandledException.java @@ -18,7 +18,7 @@ package baritone.api.utils.command.exception; import baritone.api.utils.command.Command; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; import net.minecraft.util.text.TextFormatting; import java.util.List; @@ -36,7 +36,7 @@ public class CommandUnhandledException extends RuntimeException implements IComm } @Override - public void handle(Command command, List args) { + public void handle(Command command, List args) { HELPER.logDirect("An unhandled exception occurred." + "The error is in your game's log, please report this at https://github.com/cabaletta/baritone/issues", TextFormatting.RED); diff --git a/src/api/java/baritone/api/utils/command/exception/ICommandException.java b/src/api/java/baritone/api/utils/command/exception/ICommandException.java index 379e97b7..229c08c0 100644 --- a/src/api/java/baritone/api/utils/command/exception/ICommandException.java +++ b/src/api/java/baritone/api/utils/command/exception/ICommandException.java @@ -18,7 +18,7 @@ package baritone.api.utils.command.exception; import baritone.api.utils.command.Command; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; import net.minecraft.util.text.TextFormatting; import java.util.List; @@ -49,7 +49,7 @@ public interface ICommandException { * @param command The command that threw it. * @param args The arguments the command was called with. */ - default void handle(Command command, List args) { + default void handle(Command command, List args) { HELPER.logDirect(this.getMessage(), TextFormatting.RED); } } diff --git a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java b/src/api/java/baritone/api/utils/command/helpers/arguments/IArgConsumer.java similarity index 58% rename from src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java rename to src/api/java/baritone/api/utils/command/helpers/arguments/IArgConsumer.java index e92855d1..1e50a530 100644 --- a/src/api/java/baritone/api/utils/command/helpers/arguments/ArgConsumer.java +++ b/src/api/java/baritone/api/utils/command/helpers/arguments/IArgConsumer.java @@ -17,171 +17,118 @@ package baritone.api.utils.command.helpers.arguments; -import baritone.api.IBaritone; import baritone.api.utils.Helper; import baritone.api.utils.command.Command; import baritone.api.utils.command.argparser.IArgParser; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; import baritone.api.utils.command.datatypes.IDatatype; -import baritone.api.utils.command.datatypes.IDatatypeContext; import baritone.api.utils.command.datatypes.IDatatypeFor; import baritone.api.utils.command.datatypes.IDatatypePost; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidTypeException; import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.exception.CommandTooManyArgumentsException; -import baritone.api.utils.command.manager.ICommandManager; import net.minecraft.util.EnumFacing; -import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; -import java.util.List; import java.util.stream.Stream; /** - * The {@link ArgConsumer} is how {@link Command}s read the arguments passed to them. This class has many benefits: + * The {@link IArgConsumer} is how {@link Command}s read the arguments passed to them. This class has many benefits: * *

      - *
    • Mutability. The whole concept of the {@link ArgConsumer} is to let you gradually consume arguments in any way + *
    • Mutability. The whole concept of the {@link IArgConsumer}} is to let you gradually consume arguments in any way * you'd like. You can change your consumption based on earlier arguments, for subcommands for example.
    • - *
    • You don't need to keep track of your consumption. The {@link ArgConsumer} keeps track of the arguments you + *
    • You don't need to keep track of your consumption. The {@link IArgConsumer}} keeps track of the arguments you * consume so that it can throw detailed exceptions whenever something is out of the ordinary. Additionally, if you * need to retrieve an argument after you've already consumed it - look no further than {@link #consumed()}!
    • *
    • Easy retrieval of many different types. If you need to retrieve an instance of an int or float for example, * look no further than {@link #getAs(Class)}. If you need a more powerful way of retrieving data, try out the many * {@code getDatatype...} methods.
    • - *
    • It's very easy to throw detailed exceptions. The {@link ArgConsumer} has many different methods that can + *
    • It's very easy to throw detailed exceptions. The {@link IArgConsumer}} has many different methods that can * enforce the number of arguments, the type of arguments, and more, throwing different types of * {@link CommandException}s if something seems off. You're recommended to do all validation and store all needed * data in variables BEFORE logging any data to chat via {@link Helper#logDirect(String)}, so that the error * handlers can do their job and log the error to chat.
    • *
    */ -public class ArgConsumer { +public interface IArgConsumer { - /** - * The parent {@link ICommandManager} for this {@link ArgConsumer}. Used by {@link #context}. - */ - private final ICommandManager manager; + LinkedList getArgs(); - /** - * The {@link IDatatypeContext} instance for this {@link ArgConsumer}, passed to - * datatypes when an operation is performed upon them. - * - * @see IDatatype - * @see IDatatypeContext - */ - private final IDatatypeContext context; - - /** - * The list of arguments in this ArgConsumer - */ - public final LinkedList args; - - /** - * The list of consumed arguments for this ArgConsumer. The most recently consumed argument is the last one - */ - public final Deque consumed; - - private ArgConsumer(ICommandManager manager, Deque args, Deque consumed) { - this.manager = manager; - this.context = this.new Context(); - this.args = new LinkedList<>(args); - this.consumed = new LinkedList<>(consumed); - } - - public ArgConsumer(ICommandManager manager, List args) { - this(manager, new LinkedList<>(args), new LinkedList<>()); - } + Deque getConsumed(); /** * @param num The number of arguments to check for - * @return {@code true} if there are at least {@code num} arguments left in this {@link ArgConsumer} + * @return {@code true} if there are at least {@code num} arguments left in this {@link IArgConsumer}} * @see #hasAny() * @see #hasAtMost(int) * @see #hasExactly(int) */ - public boolean has(int num) { - return args.size() >= num; - } + boolean has(int num); /** - * @return {@code true} if there is at least 1 argument left in this {@link ArgConsumer} + * @return {@code true} if there is at least 1 argument left in this {@link IArgConsumer}} * @see #has(int) * @see #hasAtMostOne() * @see #hasExactlyOne() */ - public boolean hasAny() { - return has(1); - } + boolean hasAny(); /** * @param num The number of arguments to check for - * @return {@code true} if there are at most {@code num} arguments left in this {@link ArgConsumer} + * @return {@code true} if there are at most {@code num} arguments left in this {@link IArgConsumer}} * @see #has(int) * @see #hasAtMost(int) * @see #hasExactly(int) */ - public boolean hasAtMost(int num) { - return args.size() <= num; - } + boolean hasAtMost(int num); /** - * @return {@code true} if there is at most 1 argument left in this {@link ArgConsumer} + * @return {@code true} if there is at most 1 argument left in this {@link IArgConsumer}} * @see #hasAny() * @see #hasAtMostOne() * @see #hasExactlyOne() */ - public boolean hasAtMostOne() { - return hasAtMost(1); - } + boolean hasAtMostOne(); /** * @param num The number of arguments to check for - * @return {@code true} if there are exactly {@code num} arguments left in this {@link ArgConsumer} + * @return {@code true} if there are exactly {@code num} arguments left in this {@link IArgConsumer}} * @see #has(int) * @see #hasAtMost(int) */ - public boolean hasExactly(int num) { - return args.size() == num; - } + boolean hasExactly(int num); /** - * @return {@code true} if there is exactly 1 argument left in this {@link ArgConsumer} + * @return {@code true} if there is exactly 1 argument left in this {@link IArgConsumer}} * @see #hasAny() * @see #hasAtMostOne() */ - public boolean hasExactlyOne() { - return hasExactly(1); - } + boolean hasExactlyOne(); /** * @param index The index to peek - * @return The argument at index {@code index} in this {@link ArgConsumer}, with 0 being the next one. This does not - * mutate the {@link ArgConsumer} + * @return The argument at index {@code index} in this {@link IArgConsumer}}, with 0 being the next one. This does not + * mutate the {@link IArgConsumer}} * @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left * @see #peek() * @see #peekString(int) * @see #peekAs(Class, int) * @see #get() */ - public CommandArgument peek(int index) throws CommandNotEnoughArgumentsException { - requireMin(index + 1); - return args.get(index); - } + ICommandArgument peek(int index) throws CommandNotEnoughArgumentsException; /** - * @return The next argument in this {@link ArgConsumer}. This does not mutate the {@link ArgConsumer} + * @return The next argument in this {@link IArgConsumer}}. This does not mutate the {@link IArgConsumer}} * @throws CommandNotEnoughArgumentsException If there is less than one argument left * @see #peek(int) * @see #peekString() * @see #peekAs(Class) * @see #get() */ - public CommandArgument peek() throws CommandNotEnoughArgumentsException { - return peek(0); - } + ICommandArgument peek() throws CommandNotEnoughArgumentsException; /** * @param index The index to peek @@ -192,9 +139,7 @@ public class ArgConsumer { * @see #peek() * @see #getAs(Class) */ - public boolean is(Class type, int index) throws CommandNotEnoughArgumentsException { - return peek(index).is(type); - } + boolean is(Class type, int index) throws CommandNotEnoughArgumentsException; /** * @param type The type to check for @@ -204,31 +149,25 @@ public class ArgConsumer { * @see #peek() * @see #getAs(Class) */ - public boolean is(Class type) throws CommandNotEnoughArgumentsException { - return is(type, 0); - } + boolean is(Class type) throws CommandNotEnoughArgumentsException; /** * @param index The index to peek - * @return The value of the argument at index {@code index} in this {@link ArgConsumer}, with 0 being the next one - * This does not mutate the {@link ArgConsumer} + * @return The value of the argument at index {@code index} in this {@link IArgConsumer}}, with 0 being the next one + * This does not mutate the {@link IArgConsumer}} * @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left * @see #peek() * @see #peekString() */ - public String peekString(int index) throws CommandNotEnoughArgumentsException { - return peek(index).value; - } + String peekString(int index) throws CommandNotEnoughArgumentsException; /** - * @return The value of the next argument in this {@link ArgConsumer}. This does not mutate the {@link ArgConsumer} + * @return The value of the next argument in this {@link IArgConsumer}}. This does not mutate the {@link IArgConsumer}} * @throws CommandNotEnoughArgumentsException If there is less than one argument left * @see #peekString(int) * @see #getString() */ - public String peekString() throws CommandNotEnoughArgumentsException { - return peekString(0); - } + String peekString() throws CommandNotEnoughArgumentsException; /** * @param index The index to peek @@ -238,11 +177,9 @@ public class ArgConsumer { * @throws java.util.NoSuchElementException If the constant couldn't be found * @see #peekEnumOrNull(Class) * @see #getEnum(Class) - * @see CommandArgument#getEnum(Class) + * @see ICommandArgument#getEnum(Class) */ - public > E peekEnum(Class enumClass, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return peek(index).getEnum(enumClass); - } + > E peekEnum(Class enumClass, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; /** * @param enumClass The class to search @@ -251,11 +188,9 @@ public class ArgConsumer { * @throws CommandInvalidTypeException If the constant couldn't be found * @see #peekEnumOrNull(Class) * @see #getEnum(Class) - * @see CommandArgument#getEnum(Class) + * @see ICommandArgument#getEnum(Class) */ - public > E peekEnum(Class enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return peekEnum(enumClass, 0); - } + > E peekEnum(Class enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; /** * @param index The index to peek @@ -264,15 +199,9 @@ public class ArgConsumer { * next argument's value. If no constant could be found, null * @see #peekEnum(Class) * @see #getEnumOrNull(Class) - * @see CommandArgument#getEnum(Class) + * @see ICommandArgument#getEnum(Class) */ - public > E peekEnumOrNull(Class enumClass, int index) throws CommandNotEnoughArgumentsException { - try { - return peekEnum(enumClass, index); - } catch (CommandInvalidTypeException e) { - return null; - } - } + > E peekEnumOrNull(Class enumClass, int index) throws CommandNotEnoughArgumentsException; /** * @param enumClass The class to search @@ -280,11 +209,9 @@ public class ArgConsumer { * next argument's value. If no constant could be found, null * @see #peekEnum(Class) * @see #getEnumOrNull(Class) - * @see CommandArgument#getEnum(Class) + * @see ICommandArgument#getEnum(Class) */ - public > E peekEnumOrNull(Class enumClass) throws CommandNotEnoughArgumentsException { - return peekEnumOrNull(enumClass, 0); - } + > E peekEnumOrNull(Class enumClass) throws CommandNotEnoughArgumentsException; /** * Tries to use a stateless {@link IArgParser} to parse the argument at the specified index into the specified @@ -292,7 +219,7 @@ public class ArgConsumer { *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. * * @param type The type to peek as * @param index The index to peek @@ -303,16 +230,14 @@ public class ArgConsumer { * @see #peekAsOrDefault(Class, Object, int) * @see #peekAsOrNull(Class, int) */ - public T peekAs(Class type, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return peek(index).getAs(type); - } + T peekAs(Class type, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; /** * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. * * @param type The type to peek as * @return An instance of the specified type @@ -322,9 +247,7 @@ public class ArgConsumer { * @see #peekAsOrDefault(Class, Object) * @see #peekAsOrNull(Class) */ - public T peekAs(Class type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return peekAs(type, 0); - } + T peekAs(Class type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; /** * Tries to use a stateless {@link IArgParser} to parse the argument at the specified index into the specified @@ -332,7 +255,7 @@ public class ArgConsumer { *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. * * @param type The type to peek as * @param def The value to return if the argument can't be parsed @@ -343,20 +266,14 @@ public class ArgConsumer { * @see #peekAs(Class, int) * @see #peekAsOrNull(Class, int) */ - public T peekAsOrDefault(Class type, T def, int index) throws CommandNotEnoughArgumentsException { - try { - return peekAs(type, index); - } catch (CommandInvalidTypeException e) { - return def; - } - } + T peekAsOrDefault(Class type, T def, int index) throws CommandNotEnoughArgumentsException; /** * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. * * @param type The type to peek as * @param def The value to return if the argument can't be parsed @@ -366,9 +283,7 @@ public class ArgConsumer { * @see #peekAs(Class) * @see #peekAsOrNull(Class) */ - public T peekAsOrDefault(Class type, T def) throws CommandNotEnoughArgumentsException { - return peekAsOrDefault(type, def, 0); - } + T peekAsOrDefault(Class type, T def) throws CommandNotEnoughArgumentsException; /** * Tries to use a stateless {@link IArgParser} to parse the argument at the specified index into the specified @@ -376,7 +291,7 @@ public class ArgConsumer { *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. * * @param type The type to peek as * @param index The index to peek @@ -386,16 +301,14 @@ public class ArgConsumer { * @see #peekAs(Class, int) * @see #peekAsOrDefault(Class, Object, int) */ - public T peekAsOrNull(Class type, int index) throws CommandNotEnoughArgumentsException { - return peekAsOrDefault(type, null, index); - } + T peekAsOrNull(Class type, int index) throws CommandNotEnoughArgumentsException; /** * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. * * @param type The type to peek as * @return An instance of the specified type, or {@code null} if it couldn't be parsed @@ -404,48 +317,30 @@ public class ArgConsumer { * @see #peekAs(Class) * @see #peekAsOrDefault(Class, Object) */ - public T peekAsOrNull(Class type) throws CommandNotEnoughArgumentsException { - return peekAsOrNull(type, 0); - } + T peekAsOrNull(Class type) throws CommandNotEnoughArgumentsException; - public T peekDatatype(IDatatypeFor datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return copy().getDatatypeFor(datatype); - } + T peekDatatype(IDatatypeFor datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; - public T peekDatatype(IDatatypePost datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return this.peekDatatype(datatype, null); - } + T peekDatatype(IDatatypePost datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; - public T peekDatatype(IDatatypePost datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return copy().getDatatypePost(datatype, original); - } + T peekDatatype(IDatatypePost datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; - public T peekDatatypeOrNull(IDatatypeFor datatype) { - return copy().getDatatypeForOrNull(datatype); - } + T peekDatatypeOrNull(IDatatypeFor datatype); - public T peekDatatypeOrNull(IDatatypePost datatype) { - return copy().getDatatypePostOrNull(datatype, null); - } + T peekDatatypeOrNull(IDatatypePost datatype); - public > T peekDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return copy().getDatatypePost(datatype, original); - } + > T peekDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; - public > T peekDatatypePostOrDefault(D datatype, O original, T def) { - return copy().getDatatypePostOrDefault(datatype, original, def); - } + > T peekDatatypePostOrDefault(D datatype, O original, T def); - public > T peekDatatypePostOrNull(D datatype, O original) { - return peekDatatypePostOrDefault(datatype, original, null); - } + > T peekDatatypePostOrNull(D datatype, O original); /** * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. * @@ -454,16 +349,14 @@ public class ArgConsumer { * @see IDatatype * @see IDatatypeFor */ - public > T peekDatatypeFor(Class datatype) { - return copy().peekDatatypeFor(datatype); - } + > T peekDatatypeFor(Class datatype); /** * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. * @@ -473,16 +366,14 @@ public class ArgConsumer { * @see IDatatype * @see IDatatypeFor */ - public > T peekDatatypeForOrDefault(Class datatype, T def) { - return copy().peekDatatypeForOrDefault(datatype, def); - } + > T peekDatatypeForOrDefault(Class datatype, T def); /** * Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. *

    * Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method. * @@ -491,9 +382,7 @@ public class ArgConsumer { * @see IDatatype * @see IDatatypeFor */ - public > T peekDatatypeForOrNull(Class datatype) { - return peekDatatypeForOrDefault(datatype, null); - } + > T peekDatatypeForOrNull(Class datatype); /** * Gets the next argument and returns it. This consumes the first argument so that subsequent calls will return @@ -502,12 +391,7 @@ public class ArgConsumer { * @return The next argument * @throws CommandNotEnoughArgumentsException If there's less than one argument left */ - public CommandArgument get() throws CommandNotEnoughArgumentsException { - requireMin(1); - CommandArgument arg = args.removeFirst(); - consumed.add(arg); - return arg; - } + ICommandArgument get() throws CommandNotEnoughArgumentsException; /** * Gets the value of the next argument and returns it. This consumes the first argument so that subsequent calls @@ -516,9 +400,7 @@ public class ArgConsumer { * @return The value of the next argument * @throws CommandNotEnoughArgumentsException If there's less than one argument left */ - public String getString() throws CommandNotEnoughArgumentsException { - return get().value; - } + String getString() throws CommandNotEnoughArgumentsException; /** * Gets an enum value from the enum class with the same name as the next argument's value @@ -531,11 +413,9 @@ public class ArgConsumer { * @throws CommandInvalidTypeException If the constant couldn't be found * @see #peekEnum(Class) * @see #getEnumOrNull(Class) - * @see CommandArgument#getEnum(Class) + * @see ICommandArgument#getEnum(Class) */ - public > E getEnum(Class enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return get().getEnum(enumClass); - } + > E getEnum(Class enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; /** * Gets an enum value from the enum class with the same name as the next argument's value @@ -550,16 +430,9 @@ public class ArgConsumer { * @see #getEnum(Class) * @see #getEnumOrNull(Class) * @see #peekEnumOrNull(Class) - * @see CommandArgument#getEnum(Class) + * @see ICommandArgument#getEnum(Class) */ - public > E getEnumOrDefault(Class enumClass, E def) throws CommandNotEnoughArgumentsException { - try { - peekEnum(enumClass); - return getEnum(enumClass); - } catch (CommandInvalidTypeException e) { - return def; - } - } + > E getEnumOrDefault(Class enumClass, E def) throws CommandNotEnoughArgumentsException; /** * Gets an enum value from the enum class with the same name as the next argument's value @@ -573,18 +446,16 @@ public class ArgConsumer { * @see #getEnum(Class) * @see #getEnumOrDefault(Class, Enum) * @see #peekEnumOrNull(Class) - * @see CommandArgument#getEnum(Class) + * @see ICommandArgument#getEnum(Class) */ - public > E getEnumOrNull(Class enumClass) throws CommandNotEnoughArgumentsException { - return getEnumOrDefault(enumClass, null); - } + > E getEnumOrNull(Class enumClass) throws CommandNotEnoughArgumentsException; /** * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. * * @param type The type to peek as * @return An instance of the specified type @@ -597,16 +468,14 @@ public class ArgConsumer { * @see #peekAsOrDefault(Class, Object, int) * @see #peekAsOrNull(Class, int) */ - public T getAs(Class type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - return get().getAs(type); - } + T getAs(Class type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; /** * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. * * @param type The type to peek as * @param def The default value @@ -619,22 +488,14 @@ public class ArgConsumer { * @see #peekAsOrDefault(Class, Object, int) * @see #peekAsOrNull(Class, int) */ - public T getAsOrDefault(Class type, T def) throws CommandNotEnoughArgumentsException { - try { - T val = peek().getAs(type); - get(); - return val; - } catch (CommandInvalidTypeException e) { - return def; - } - } + T getAsOrDefault(Class type, T def) throws CommandNotEnoughArgumentsException; /** * Tries to use a stateless {@link IArgParser} to parse the next argument into the specified class *

    * A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take. * While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire - * {@link ArgConsumer}. + * {@link IArgConsumer}}. * * @param type The type to peek as * @return An instance of the specified type, or {@code null} if it couldn't be parsed @@ -646,75 +507,25 @@ public class ArgConsumer { * @see #peekAsOrDefault(Class, Object, int) * @see #peekAsOrNull(Class, int) */ - public T getAsOrNull(Class type) throws CommandNotEnoughArgumentsException { - return getAsOrDefault(type, null); - } + T getAsOrNull(Class type) throws CommandNotEnoughArgumentsException; - public > T getDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - try { - return datatype.apply(this.context, original); - } catch (Exception e) { - e.printStackTrace(); - throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName()); - } - } + > T getDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; - public > T getDatatypePostOrDefault(D datatype, O original, T _default) { - final List argsSnapshot = new ArrayList<>(this.args); - final List consumedSnapshot = new ArrayList<>(this.consumed); - try { - return this.getDatatypePost(datatype, original); - } catch (Exception e) { - this.args.clear(); - this.args.addAll(argsSnapshot); - this.consumed.clear(); - this.consumed.addAll(consumedSnapshot); - return _default; - } - } + > T getDatatypePostOrDefault(D datatype, O original, T _default); - public > T getDatatypePostOrNull(D datatype, O original) { - return this.getDatatypePostOrDefault(datatype, original, null); - } + > T getDatatypePostOrNull(D datatype, O original); - public > T getDatatypeFor(D datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { - try { - return datatype.get(this.context); - } catch (Exception e) { - throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName()); - } - } + > T getDatatypeFor(D datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException; - public > T getDatatypeForOrDefault(D datatype, T def) { - final List argsSnapshot = new ArrayList<>(this.args); - final List consumedSnapshot = new ArrayList<>(this.consumed); - try { - return this.getDatatypeFor(datatype); - } catch (Exception e) { - this.args.clear(); - this.args.addAll(argsSnapshot); - this.consumed.clear(); - this.consumed.addAll(consumedSnapshot); - return def; - } - } + > T getDatatypeForOrDefault(D datatype, T def); - public > T getDatatypeForOrNull(D datatype) { - return this.getDatatypeForOrDefault(datatype, null); - } + > T getDatatypeForOrNull(D datatype); - public Stream tabCompleteDatatype(T datatype) { - try { - return datatype.tabComplete(this.context); - } catch (Exception e) { - e.printStackTrace(); - } - return Stream.empty(); - } + Stream tabCompleteDatatype(T datatype); /** * Returns the "raw rest" of the string. For example, from a string arg1 arg2  arg3, split - * into three {@link CommandArgument}s {@code "arg1"}, {@code "arg2"}, and {@code "arg3"}: + * into three {@link ICommandArgument}s {@code "arg1"}, {@code "arg2"}, and {@code "arg3"}: * *

      *
    • {@code rawRest()} would return arg1 arg2  arg3
    • @@ -726,9 +537,7 @@ public class ArgConsumer { * * @return The "raw rest" of the string. */ - public String rawRest() { - return args.size() > 0 ? args.getFirst().rawRest : ""; - } + String rawRest(); /** * @param min The minimum amount of arguments to require. @@ -736,11 +545,7 @@ public class ArgConsumer { * @see #requireMax(int) * @see #requireExactly(int) */ - public void requireMin(int min) throws CommandNotEnoughArgumentsException { - if (args.size() < min) { - throw new CommandNotEnoughArgumentsException(min + consumed.size()); - } - } + void requireMin(int min) throws CommandNotEnoughArgumentsException; /** * @param max The maximum amount of arguments allowed. @@ -748,11 +553,7 @@ public class ArgConsumer { * @see #requireMin(int) * @see #requireExactly(int) */ - public void requireMax(int max) throws CommandTooManyArgumentsException { - if (args.size() > max) { - throw new CommandTooManyArgumentsException(max + consumed.size()); - } - } + void requireMax(int max) throws CommandTooManyArgumentsException; /** * @param args The exact amount of arguments to require. @@ -761,58 +562,34 @@ public class ArgConsumer { * @see #requireMin(int) * @see #requireMax(int) */ - public void requireExactly(int args) throws CommandException { - requireMin(args); - requireMax(args); - } + void requireExactly(int args) throws CommandException; /** - * @return If this {@link ArgConsumer} has consumed at least one argument. + * @return If this {@link IArgConsumer}} has consumed at least one argument. * @see #consumed() * @see #consumedString() */ - public boolean hasConsumed() { - return !consumed.isEmpty(); - } + boolean hasConsumed(); /** - * @return The last argument this {@link ArgConsumer} has consumed, or the {@link CommandArgument#unknown() unknown} - * argument if no arguments have been consumed yet. + * @return The last argument this {@link IArgConsumer}} has consumed, or an "unknown" argument, indicated by a + * comamnd argument index that has a value of {@code -1}, if no arguments have been consumed yet. * @see #consumedString() * @see #hasConsumed() */ - public CommandArgument consumed() { - return consumed.size() > 0 ? consumed.getLast() : CommandArgument.unknown(); - } + ICommandArgument consumed(); /** - * @return The value of thelast argument this {@link ArgConsumer} has consumed, or an empty string if no arguments + * @return The value of thelast argument this {@link IArgConsumer}} has consumed, or an empty string if no arguments * have been consumed yet * @see #consumed() * @see #hasConsumed() */ - public String consumedString() { - return consumed().value; - } + String consumedString(); /** - * @return A copy of this {@link ArgConsumer}. It has the same arguments (both consumed and not), but does not + * @return A copy of this {@link IArgConsumer}}. It has the same arguments (both consumed and not), but does not * affect or mutate this instance. Useful for the various {@code peek} functions */ - public ArgConsumer copy() { - return new ArgConsumer(manager, args, consumed); - } - - private final class Context implements IDatatypeContext { - - @Override - public final IBaritone getBaritone() { - return ArgConsumer.this.manager.getBaritone(); - } - - @Override - public final ArgConsumer getConsumer() { - return ArgConsumer.this; - } - } + IArgConsumer copy(); } diff --git a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java index da5ac436..cf5d5d7c 100644 --- a/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java +++ b/src/api/java/baritone/api/utils/command/helpers/pagination/Paginator.java @@ -20,7 +20,7 @@ package baritone.api.utils.command.helpers.pagination; import baritone.api.utils.Helper; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidTypeException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; @@ -115,7 +115,7 @@ public class Paginator implements Helper { display(transform, null); } - public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform, String commandPrefix) throws CommandException { + public static void paginate(IArgConsumer consumer, Paginator pagi, Runnable pre, Function transform, String commandPrefix) throws CommandException { int page = 1; consumer.requireMax(1); if (consumer.hasAny()) { @@ -127,7 +127,7 @@ public class Paginator implements Helper { "a valid page (1-%d)", pagi.getMaxPage() ), - consumer.consumed().value + consumer.consumed().getValue() ); } } @@ -138,47 +138,47 @@ public class Paginator implements Helper { pagi.display(transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, List elems, Runnable pre, Function transform, String commandPrefix) throws CommandException { + public static void paginate(IArgConsumer consumer, List elems, Runnable pre, Function transform, String commandPrefix) throws CommandException { paginate(consumer, new Paginator<>(elems), pre, transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, T[] elems, Runnable pre, Function transform, String commandPrefix) throws CommandException { + public static void paginate(IArgConsumer consumer, T[] elems, Runnable pre, Function transform, String commandPrefix) throws CommandException { paginate(consumer, Arrays.asList(elems), pre, transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform, String commandPrefix) throws CommandException { + public static void paginate(IArgConsumer consumer, Paginator pagi, Function transform, String commandPrefix) throws CommandException { paginate(consumer, pagi, null, transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, List elems, Function transform, String commandPrefix) throws CommandException { + public static void paginate(IArgConsumer consumer, List elems, Function transform, String commandPrefix) throws CommandException { paginate(consumer, new Paginator<>(elems), null, transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, T[] elems, Function transform, String commandPrefix) throws CommandException { + public static void paginate(IArgConsumer consumer, T[] elems, Function transform, String commandPrefix) throws CommandException { paginate(consumer, Arrays.asList(elems), null, transform, commandPrefix); } - public static void paginate(ArgConsumer consumer, Paginator pagi, Runnable pre, Function transform) throws CommandException { + public static void paginate(IArgConsumer consumer, Paginator pagi, Runnable pre, Function transform) throws CommandException { paginate(consumer, pagi, pre, transform, null); } - public static void paginate(ArgConsumer consumer, List elems, Runnable pre, Function transform) throws CommandException { + public static void paginate(IArgConsumer consumer, List elems, Runnable pre, Function transform) throws CommandException { paginate(consumer, new Paginator<>(elems), pre, transform, null); } - public static void paginate(ArgConsumer consumer, T[] elems, Runnable pre, Function transform) throws CommandException { + public static void paginate(IArgConsumer consumer, T[] elems, Runnable pre, Function transform) throws CommandException { paginate(consumer, Arrays.asList(elems), pre, transform, null); } - public static void paginate(ArgConsumer consumer, Paginator pagi, Function transform) throws CommandException { + public static void paginate(IArgConsumer consumer, Paginator pagi, Function transform) throws CommandException { paginate(consumer, pagi, null, transform, null); } - public static void paginate(ArgConsumer consumer, List elems, Function transform) throws CommandException { + public static void paginate(IArgConsumer consumer, List elems, Function transform) throws CommandException { paginate(consumer, new Paginator<>(elems), null, transform, null); } - public static void paginate(ArgConsumer consumer, T[] elems, Function transform) throws CommandException { + public static void paginate(IArgConsumer consumer, T[] elems, Function transform) throws CommandException { paginate(consumer, Arrays.asList(elems), null, transform, null); } } diff --git a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java index db63b2d5..9be9dfb3 100644 --- a/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java +++ b/src/api/java/baritone/api/utils/command/helpers/tabcomplete/TabCompleteHelper.java @@ -21,8 +21,7 @@ import baritone.api.BaritoneAPI; import baritone.api.Settings; import baritone.api.event.events.TabCompleteEvent; import baritone.api.utils.SettingsUtil; -import baritone.api.utils.command.datatypes.IDatatype; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import baritone.api.utils.command.manager.ICommandManager; import net.minecraft.util.ResourceLocation; @@ -45,7 +44,7 @@ import java.util.stream.Stream; * {@link #filterPrefix(String)} *
    • Get the stream using {@link #stream()}
    • *
    • Pass it up to whatever's calling your tab complete function (i.e. - * {@link ICommandManager#tabComplete(String)} or {@link ArgConsumer#tabCompleteDatatype(IDatatype)})
    • + * {@link ICommandManager#tabComplete(String)} or {@link IArgConsumer}#tabCompleteDatatype(IDatatype)}) *
    *

    * For advanced users: if you're intercepting {@link TabCompleteEvent}s directly, use {@link #build()} instead for an diff --git a/src/api/java/baritone/api/utils/command/manager/ICommandManager.java b/src/api/java/baritone/api/utils/command/manager/ICommandManager.java index 63682433..d3fac415 100644 --- a/src/api/java/baritone/api/utils/command/manager/ICommandManager.java +++ b/src/api/java/baritone/api/utils/command/manager/ICommandManager.java @@ -19,7 +19,7 @@ package baritone.api.utils.command.manager; import baritone.api.IBaritone; import baritone.api.utils.command.Command; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; import baritone.api.utils.command.registry.Registry; import net.minecraft.util.Tuple; @@ -44,9 +44,9 @@ public interface ICommandManager { boolean execute(String string); - boolean execute(Tuple> expanded); + boolean execute(Tuple> expanded); - Stream tabComplete(Tuple> expanded); + Stream tabComplete(Tuple> expanded); Stream tabComplete(String prefix); } diff --git a/src/main/java/baritone/utils/command/BaritoneChatControl.java b/src/main/java/baritone/utils/command/BaritoneChatControl.java index 30ba9244..70e2370e 100644 --- a/src/main/java/baritone/utils/command/BaritoneChatControl.java +++ b/src/main/java/baritone/utils/command/BaritoneChatControl.java @@ -26,12 +26,13 @@ import baritone.api.event.events.TabCompleteEvent; import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.utils.Helper; import baritone.api.utils.SettingsUtil; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; import baritone.api.utils.command.exception.CommandNotFoundException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.manager.ICommandManager; +import baritone.utils.command.argument.CommandArguments; import baritone.utils.command.manager.CommandManager; import net.minecraft.util.Tuple; import net.minecraft.util.text.ITextComponent; @@ -106,7 +107,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { if (msg.isEmpty()) { return this.runCommand("help"); } - Tuple> pair = CommandManager.expand(msg); + Tuple> pair = CommandManager.expand(msg); String command = pair.getFirst(); String rest = msg.substring(pair.getFirst().length()); ArgConsumer argc = new ArgConsumer(this.manager, pair.getSecond()); @@ -155,7 +156,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { return; } String msg = prefix.substring(commandPrefix.length()); - List args = CommandArgument.from(msg, true); + List args = CommandArguments.from(msg, true); Stream stream = tabComplete(msg); if (args.size() == 1) { stream = stream.map(x -> commandPrefix + x); @@ -165,7 +166,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener { public Stream tabComplete(String msg) { try { - List args = CommandArgument.from(msg, true); + List args = CommandArguments.from(msg, true); ArgConsumer argc = new ArgConsumer(this.manager, args); if (argc.hasAtMost(2)) { if (argc.hasExactly(1)) { diff --git a/src/main/java/baritone/utils/command/argument/CommandArgument.java b/src/main/java/baritone/utils/command/argument/CommandArgument.java new file mode 100644 index 00000000..9c374248 --- /dev/null +++ b/src/main/java/baritone/utils/command/argument/CommandArgument.java @@ -0,0 +1,97 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils.command.argument; + +import baritone.api.utils.command.argparser.ArgParserManager; +import baritone.api.utils.command.argument.ICommandArgument; +import baritone.api.utils.command.exception.CommandInvalidArgumentException; +import baritone.api.utils.command.exception.CommandInvalidTypeException; + +import java.util.stream.Stream; + +/** + * The default implementation of {@link ICommandArgument} + * + * @author LoganDark + */ +class CommandArgument implements ICommandArgument { + + private final int index; + private final String value; + private final String rawRest; + + CommandArgument(int index, String value, String rawRest) { + this.index = index; + this.value = value; + this.rawRest = rawRest; + } + + @Override + public int getIndex() { + return this.index; + } + + @Override + public String getValue() { + return this.value; + } + + @Override + public String getRawRest() { + return this.rawRest; + } + + @Override + public > E getEnum(Class enumClass) throws CommandInvalidTypeException { + return Stream.of(enumClass.getEnumConstants()) + .filter(e -> e.name().equalsIgnoreCase(value)) + .findFirst() + .orElseThrow(() -> new CommandInvalidTypeException(this, enumClass.getSimpleName())); + } + + @Override + public T getAs(Class type) throws CommandInvalidTypeException { + return ArgParserManager.parseStateless(type, this); + } + + @Override + public boolean is(Class type) { + try { + getAs(type); + return true; + } catch (Throwable t) { + return false; + } + } + + @SuppressWarnings("UnusedReturnValue") + @Override + public T getAs(Class type, Class stateType, S state) throws CommandInvalidTypeException { + return ArgParserManager.parseStated(type, stateType, this, state); + } + + @Override + public boolean is(Class type, Class stateType, S state) { + try { + getAs(type, stateType, state); + return true; + } catch (Throwable t) { + return false; + } + } +} diff --git a/src/main/java/baritone/utils/command/argument/CommandArguments.java b/src/main/java/baritone/utils/command/argument/CommandArguments.java new file mode 100644 index 00000000..22f89559 --- /dev/null +++ b/src/main/java/baritone/utils/command/argument/CommandArguments.java @@ -0,0 +1,79 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils.command.argument; + +import baritone.api.utils.command.argument.ICommandArgument; +import baritone.api.utils.command.exception.CommandInvalidArgumentException; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author LoganDark + */ +public final class CommandArguments { + + private CommandArguments() {} + + private static final Pattern ARG_PATTERN = Pattern.compile("\\S+"); + + /** + * Turn a string into a list of {@link ICommandArgument}s. This is needed because of {@link ICommandArgument#getRawRest()} + * + * @param string The string to convert + * @param preserveEmptyLast If the string ends with whitespace, add an empty {@link ICommandArgument} to the end This + * is useful for tab completion + * @return A list of {@link ICommandArgument}s + */ + public static List from(String string, boolean preserveEmptyLast) { + List args = new ArrayList<>(); + Matcher argMatcher = ARG_PATTERN.matcher(string); + int lastEnd = -1; + while (argMatcher.find()) { + args.add(new CommandArgument( + args.size(), + argMatcher.group(), + string.substring(argMatcher.start()) + )); + lastEnd = argMatcher.end(); + } + if (preserveEmptyLast && lastEnd < string.length()) { + args.add(new CommandArgument(args.size(), "", "")); + } + return args; + } + + /** + * @see #from(String, boolean) + */ + public static List from(String string) { + return from(string, false); + } + + /** + * Returns an "unknown" {@link CommandArgument}. This shouldn't be used unless you absolutely have no information - + * ESPECIALLY not with {@link CommandInvalidArgumentException}s + * + * @return The unknown {@link CommandArgument} + */ + public static CommandArgument unknown() { + return new CommandArgument(-1, "", ""); + } +} diff --git a/src/main/java/baritone/utils/command/defaults/AxisCommand.java b/src/main/java/baritone/utils/command/defaults/AxisCommand.java index f80356ad..f67c82e5 100644 --- a/src/main/java/baritone/utils/command/defaults/AxisCommand.java +++ b/src/main/java/baritone/utils/command/defaults/AxisCommand.java @@ -22,7 +22,7 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalAxis; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -35,7 +35,7 @@ public class AxisCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); Goal goal = new GoalAxis(); baritone.getCustomGoalProcess().setGoal(goal); @@ -43,7 +43,7 @@ public class AxisCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java index 43aaa737..accda72b 100644 --- a/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BlacklistCommand.java @@ -22,7 +22,7 @@ import baritone.api.process.IGetToBlockProcess; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -35,7 +35,7 @@ public class BlacklistCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); IGetToBlockProcess proc = baritone.getGetToBlockProcess(); if (!proc.isActive()) { @@ -49,7 +49,7 @@ public class BlacklistCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/BuildCommand.java b/src/main/java/baritone/utils/command/defaults/BuildCommand.java index 5d084d48..b852d0be 100644 --- a/src/main/java/baritone/utils/command/defaults/BuildCommand.java +++ b/src/main/java/baritone/utils/command/defaults/BuildCommand.java @@ -24,7 +24,7 @@ import baritone.api.utils.command.datatypes.RelativeBlockPos; import baritone.api.utils.command.datatypes.RelativeFile; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import net.minecraft.client.Minecraft; import java.io.File; @@ -42,7 +42,7 @@ public class BuildCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { File file = args.getDatatypePost(RelativeFile.INSTANCE, schematicsDir).getAbsoluteFile(); if (!file.getName().toLowerCase(Locale.US).endsWith(".schematic")) { file = new File(file.getAbsolutePath() + ".schematic"); @@ -64,7 +64,7 @@ public class BuildCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, IArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return RelativeFile.tabComplete(args, schematicsDir); } else if (args.has(2)) { diff --git a/src/main/java/baritone/utils/command/defaults/CancelCommand.java b/src/main/java/baritone/utils/command/defaults/CancelCommand.java index 67cde8f4..868da5e0 100644 --- a/src/main/java/baritone/utils/command/defaults/CancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/CancelCommand.java @@ -20,7 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -33,14 +33,14 @@ public class CancelCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); baritone.getPathingBehavior().cancelEverything(); logDirect("ok canceled"); } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java index f65a18e5..130d5909 100644 --- a/src/main/java/baritone/utils/command/defaults/ChestsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ChestsCommand.java @@ -23,7 +23,7 @@ import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; @@ -41,7 +41,7 @@ public class ChestsCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); Set> entries = ctx.worldData().getContainerMemory().getRememberedInventories().entrySet(); @@ -62,7 +62,7 @@ public class ChestsCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ClickCommand.java b/src/main/java/baritone/utils/command/defaults/ClickCommand.java index 07bd4de9..ba8e917c 100644 --- a/src/main/java/baritone/utils/command/defaults/ClickCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ClickCommand.java @@ -20,7 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -33,14 +33,14 @@ public class ClickCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); baritone.openClick(); logDirect("aight dude"); } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ComeCommand.java b/src/main/java/baritone/utils/command/defaults/ComeCommand.java index 52a0cec6..cc4f4071 100644 --- a/src/main/java/baritone/utils/command/defaults/ComeCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ComeCommand.java @@ -22,7 +22,7 @@ import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; @@ -37,7 +37,7 @@ public class ComeCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); Entity entity = mc.getRenderViewEntity(); if (entity == null) { @@ -48,7 +48,7 @@ public class ComeCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/CommandAlias.java b/src/main/java/baritone/utils/command/defaults/CommandAlias.java index 0f28e48e..6aa32af1 100644 --- a/src/main/java/baritone/utils/command/defaults/CommandAlias.java +++ b/src/main/java/baritone/utils/command/defaults/CommandAlias.java @@ -19,7 +19,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.utils.command.Command; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Collections; import java.util.List; @@ -43,12 +43,12 @@ public class CommandAlias extends Command { } @Override - public void execute(String label, ArgConsumer args) { + public void execute(String label, IArgConsumer args) { this.baritone.getCommandManager().execute(String.format("%s %s", target, args.rawRest())); } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return this.baritone.getCommandManager().tabComplete(String.format("%s %s", target, args.rawRest())); } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java index 55e3d756..15a8e241 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreCommand.java @@ -22,7 +22,7 @@ import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeGoalXZ; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -35,7 +35,7 @@ public class ExploreCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { if (args.hasAny()) { args.requireExactly(2); } else { @@ -49,7 +49,7 @@ public class ExploreCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { if (args.hasAtMost(2)) { return args.tabCompleteDatatype(RelativeGoalXZ.INSTANCE); } diff --git a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java index 29f34c86..6f60a55d 100644 --- a/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ExploreFilterCommand.java @@ -23,7 +23,7 @@ import baritone.api.utils.command.datatypes.RelativeFile; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.exception.CommandInvalidTypeException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import com.google.gson.JsonSyntaxException; import java.io.File; @@ -39,7 +39,7 @@ public class ExploreFilterCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(2); File file = args.getDatatypePost(RelativeFile.INSTANCE, mc.gameDir.getAbsoluteFile().getParentFile()); boolean invert = false; @@ -63,7 +63,7 @@ public class ExploreFilterCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, IArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return RelativeFile.tabComplete(args, RelativeFile.gameDir()); } diff --git a/src/main/java/baritone/utils/command/defaults/FarmCommand.java b/src/main/java/baritone/utils/command/defaults/FarmCommand.java index a9dc7a8b..0ece390d 100644 --- a/src/main/java/baritone/utils/command/defaults/FarmCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FarmCommand.java @@ -20,7 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -33,14 +33,14 @@ public class FarmCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); baritone.getFarmProcess().farm(); logDirect("Farming"); } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/FindCommand.java b/src/main/java/baritone/utils/command/defaults/FindCommand.java index 513d6539..62a49e02 100644 --- a/src/main/java/baritone/utils/command/defaults/FindCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FindCommand.java @@ -22,7 +22,7 @@ import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.BlockById; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import net.minecraft.block.Block; import java.util.ArrayList; @@ -37,7 +37,7 @@ public class FindCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { List toFind = new ArrayList<>(); while (args.hasAny()) { toFind.add(args.getDatatypeFor(BlockById.INSTANCE)); @@ -59,7 +59,7 @@ public class FindCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return args.tabCompleteDatatype(BlockById.INSTANCE); } diff --git a/src/main/java/baritone/utils/command/defaults/FollowCommand.java b/src/main/java/baritone/utils/command/defaults/FollowCommand.java index d2e674c9..b1cb5a80 100644 --- a/src/main/java/baritone/utils/command/defaults/FollowCommand.java +++ b/src/main/java/baritone/utils/command/defaults/FollowCommand.java @@ -23,7 +23,7 @@ import baritone.api.utils.command.datatypes.EntityClassById; import baritone.api.utils.command.datatypes.IDatatypeFor; import baritone.api.utils.command.datatypes.NearbyPlayer; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; @@ -42,7 +42,7 @@ public class FollowCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMin(1); FollowGroup group; FollowList list; @@ -88,7 +88,7 @@ public class FollowCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, IArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper() .append(FollowGroup.class) diff --git a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java index 05b62992..7a020b14 100644 --- a/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ForceCancelCommand.java @@ -21,7 +21,7 @@ import baritone.api.IBaritone; import baritone.api.behavior.IPathingBehavior; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -34,7 +34,7 @@ public class ForceCancelCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); IPathingBehavior pathingBehavior = baritone.getPathingBehavior(); pathingBehavior.cancelEverything(); @@ -43,7 +43,7 @@ public class ForceCancelCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/GcCommand.java b/src/main/java/baritone/utils/command/defaults/GcCommand.java index 068b5136..20b2e334 100644 --- a/src/main/java/baritone/utils/command/defaults/GcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GcCommand.java @@ -20,7 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -33,14 +33,14 @@ public class GcCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); System.gc(); logDirect("ok called System.gc()"); } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/GoalCommand.java b/src/main/java/baritone/utils/command/defaults/GoalCommand.java index baac24b6..f2692fb2 100644 --- a/src/main/java/baritone/utils/command/defaults/GoalCommand.java +++ b/src/main/java/baritone/utils/command/defaults/GoalCommand.java @@ -25,7 +25,7 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.RelativeCoordinate; import baritone.api.utils.command.datatypes.RelativeGoal; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import java.util.Arrays; @@ -39,7 +39,7 @@ public class GoalCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { ICustomGoalProcess goalProcess = baritone.getCustomGoalProcess(); if (args.hasAny() && Arrays.asList("reset", "clear", "none").contains(args.peekString())) { args.requireMax(1); @@ -59,7 +59,7 @@ public class GoalCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, IArgConsumer args) throws CommandException { TabCompleteHelper helper = new TabCompleteHelper(); if (args.hasExactlyOne()) { helper.append("reset", "clear", "none", "~"); diff --git a/src/main/java/baritone/utils/command/defaults/HelpCommand.java b/src/main/java/baritone/utils/command/defaults/HelpCommand.java index 7db0d893..480207f1 100644 --- a/src/main/java/baritone/utils/command/defaults/HelpCommand.java +++ b/src/main/java/baritone/utils/command/defaults/HelpCommand.java @@ -21,7 +21,7 @@ import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandNotFoundException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import baritone.api.utils.command.helpers.pagination.Paginator; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.util.text.ITextComponent; @@ -44,7 +44,7 @@ public class HelpCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(1); if (!args.hasAny() || args.is(Integer.class)) { Paginator.paginate( @@ -97,7 +97,7 @@ public class HelpCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, IArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper() .addCommands(this.baritone.getCommandManager()) diff --git a/src/main/java/baritone/utils/command/defaults/InvertCommand.java b/src/main/java/baritone/utils/command/defaults/InvertCommand.java index 232ac0f3..9b5d0a16 100644 --- a/src/main/java/baritone/utils/command/defaults/InvertCommand.java +++ b/src/main/java/baritone/utils/command/defaults/InvertCommand.java @@ -24,7 +24,7 @@ import baritone.api.process.ICustomGoalProcess; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -37,7 +37,7 @@ public class InvertCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; @@ -54,7 +54,7 @@ public class InvertCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/MineCommand.java b/src/main/java/baritone/utils/command/defaults/MineCommand.java index da92b098..2a91c6e6 100644 --- a/src/main/java/baritone/utils/command/defaults/MineCommand.java +++ b/src/main/java/baritone/utils/command/defaults/MineCommand.java @@ -23,7 +23,7 @@ import baritone.api.utils.command.Command; import baritone.api.utils.command.datatypes.BlockById; import baritone.api.utils.command.datatypes.ForBlockOptionalMeta; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import baritone.cache.WorldScanner; import java.util.ArrayList; @@ -38,7 +38,7 @@ public class MineCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { int quantity = args.getAsOrDefault(Integer.class, 0); args.requireMin(1); List boms = new ArrayList<>(); @@ -51,7 +51,7 @@ public class MineCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return args.tabCompleteDatatype(BlockById.INSTANCE); } diff --git a/src/main/java/baritone/utils/command/defaults/PathCommand.java b/src/main/java/baritone/utils/command/defaults/PathCommand.java index 6de33373..e52a93a4 100644 --- a/src/main/java/baritone/utils/command/defaults/PathCommand.java +++ b/src/main/java/baritone/utils/command/defaults/PathCommand.java @@ -25,7 +25,7 @@ import baritone.api.utils.command.datatypes.RelativeCoordinate; import baritone.api.utils.command.datatypes.RelativeGoal; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.cache.WorldScanner; @@ -40,7 +40,7 @@ public class PathCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess(); Goal goal; if (args.hasAny()) { @@ -56,7 +56,7 @@ public class PathCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, IArgConsumer args) throws CommandException { if (args.hasAny() && !args.has(4)) { while (args.has(2)) { if (args.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) == null) { diff --git a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java index 2c363ff4..08a0ae66 100644 --- a/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java +++ b/src/main/java/baritone/utils/command/defaults/PauseResumeCommands.java @@ -24,7 +24,7 @@ import baritone.api.process.PathingCommandType; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -79,7 +79,7 @@ public class PauseResumeCommands { ); pauseCommand = new Command(baritone, "pause") { @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); if (paused[0]) { throw new CommandInvalidStateException("Already paused"); @@ -89,7 +89,7 @@ public class PauseResumeCommands { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } @@ -112,7 +112,7 @@ public class PauseResumeCommands { }; resumeCommand = new Command(baritone, "resume") { @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); if (!paused[0]) { throw new CommandInvalidStateException("Not paused"); @@ -122,7 +122,7 @@ public class PauseResumeCommands { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } @@ -143,13 +143,13 @@ public class PauseResumeCommands { }; pausedCommand = new Command(baritone, "paused") { @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); logDirect(String.format("Baritone is %spaused", paused[0] ? "" : "not ")); } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ProcCommand.java b/src/main/java/baritone/utils/command/defaults/ProcCommand.java index 232a53a2..233c18a3 100644 --- a/src/main/java/baritone/utils/command/defaults/ProcCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ProcCommand.java @@ -24,7 +24,7 @@ import baritone.api.process.PathingCommand; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -37,7 +37,7 @@ public class ProcCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); IPathingControlManager pathingControlManager = baritone.getPathingControlManager(); IBaritoneProcess process = pathingControlManager.mostRecentInControl().orElse(null); @@ -62,7 +62,7 @@ public class ProcCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java index f13af77d..6128094c 100644 --- a/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ReloadAllCommand.java @@ -20,7 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -33,14 +33,14 @@ public class ReloadAllCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); ctx.worldData().getCachedWorld().reloadAllFromDisk(); logDirect("Reloaded"); } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/RenderCommand.java b/src/main/java/baritone/utils/command/defaults/RenderCommand.java index 710df10f..15473afa 100644 --- a/src/main/java/baritone/utils/command/defaults/RenderCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RenderCommand.java @@ -21,7 +21,7 @@ import baritone.api.IBaritone; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -34,7 +34,7 @@ public class RenderCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); BetterBlockPos origin = ctx.playerFeet(); int renderDistance = (mc.gameSettings.renderDistanceChunks + 1) * 16; @@ -50,7 +50,7 @@ public class RenderCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/RepackCommand.java b/src/main/java/baritone/utils/command/defaults/RepackCommand.java index 2f1a988d..1f11802a 100644 --- a/src/main/java/baritone/utils/command/defaults/RepackCommand.java +++ b/src/main/java/baritone/utils/command/defaults/RepackCommand.java @@ -20,7 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import baritone.cache.WorldScanner; import java.util.Arrays; @@ -34,13 +34,13 @@ public class RepackCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); logDirect(String.format("Queued %d chunks for repacking", WorldScanner.INSTANCE.repack(ctx))); } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java index 21dbfb64..9c507f69 100644 --- a/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SaveAllCommand.java @@ -20,7 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -33,14 +33,14 @@ public class SaveAllCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); ctx.worldData().getCachedWorld().save(); logDirect("Saved"); } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java index ed695169..c531a48b 100644 --- a/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SchematicaCommand.java @@ -20,7 +20,7 @@ package baritone.utils.command.defaults; import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -33,13 +33,13 @@ public class SchematicaCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); baritone.getBuilderProcess().buildOpenSchematic(); } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/SelCommand.java b/src/main/java/baritone/utils/command/defaults/SelCommand.java index 8e2512d1..83fc77e3 100644 --- a/src/main/java/baritone/utils/command/defaults/SelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SelCommand.java @@ -35,7 +35,7 @@ import baritone.api.utils.command.datatypes.RelativeBlockPos; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.exception.CommandInvalidTypeException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.utils.IRenderer; import net.minecraft.init.Blocks; @@ -75,7 +75,7 @@ public class SelCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { Action action = Action.getByName(args.getString()); if (action == null) { throw new CommandInvalidTypeException(args.consumed(), "an action"); @@ -186,7 +186,7 @@ public class SelCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, IArgConsumer args) throws CommandException { if (args.hasExactlyOne()) { return new TabCompleteHelper() .append(Action.getAllNames()) diff --git a/src/main/java/baritone/utils/command/defaults/SetCommand.java b/src/main/java/baritone/utils/command/defaults/SetCommand.java index 8add3fed..be07a7ae 100644 --- a/src/main/java/baritone/utils/command/defaults/SetCommand.java +++ b/src/main/java/baritone/utils/command/defaults/SetCommand.java @@ -24,7 +24,7 @@ import baritone.api.utils.SettingsUtil; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidTypeException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import baritone.api.utils.command.helpers.pagination.Paginator; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.util.text.ITextComponent; @@ -50,7 +50,7 @@ public class SetCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { String arg = args.hasAny() ? args.getString().toLowerCase(Locale.US) : "list"; if (Arrays.asList("s", "save").contains(arg)) { SettingsUtil.save(Baritone.settings()); @@ -186,7 +186,7 @@ public class SetCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, IArgConsumer args) throws CommandException { if (args.hasAny()) { String arg = args.getString(); if (args.hasExactlyOne() && !Arrays.asList("s", "save").contains(args.peekString().toLowerCase(Locale.US))) { diff --git a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java index d11346cc..bef3a513 100644 --- a/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java +++ b/src/main/java/baritone/utils/command/defaults/ThisWayCommand.java @@ -21,7 +21,7 @@ import baritone.api.IBaritone; import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -34,7 +34,7 @@ public class ThisWayCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireExactly(1); GoalXZ goal = GoalXZ.fromDirection( ctx.playerFeetAsVec(), @@ -46,7 +46,7 @@ public class ThisWayCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java index b7e00fe6..1b9066f9 100644 --- a/src/main/java/baritone/utils/command/defaults/TunnelCommand.java +++ b/src/main/java/baritone/utils/command/defaults/TunnelCommand.java @@ -22,7 +22,7 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalStrictDirection; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -35,7 +35,7 @@ public class TunnelCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); Goal goal = new GoalStrictDirection( ctx.playerFeet(), @@ -46,7 +46,7 @@ public class TunnelCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/VersionCommand.java b/src/main/java/baritone/utils/command/defaults/VersionCommand.java index 89dc6576..4c9aa850 100644 --- a/src/main/java/baritone/utils/command/defaults/VersionCommand.java +++ b/src/main/java/baritone/utils/command/defaults/VersionCommand.java @@ -21,7 +21,7 @@ import baritone.api.IBaritone; import baritone.api.utils.command.Command; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import java.util.Arrays; import java.util.List; @@ -34,7 +34,7 @@ public class VersionCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { args.requireMax(0); String version = getClass().getPackage().getImplementationVersion(); if (version == null) { @@ -45,7 +45,7 @@ public class VersionCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) { + public Stream tabComplete(String label, IArgConsumer args) { return Stream.empty(); } diff --git a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java index 45bd7b50..bda39e2a 100644 --- a/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java +++ b/src/main/java/baritone/utils/command/defaults/WaypointsCommand.java @@ -29,7 +29,7 @@ import baritone.api.utils.command.datatypes.RelativeBlockPos; import baritone.api.utils.command.exception.CommandException; import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.exception.CommandInvalidTypeException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; import baritone.api.utils.command.helpers.pagination.Paginator; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import net.minecraft.util.text.ITextComponent; @@ -52,7 +52,7 @@ public class WaypointsCommand extends Command { } @Override - public void execute(String label, ArgConsumer args) throws CommandException { + public void execute(String label, IArgConsumer args) throws CommandException { Action action = args.hasAny() ? Action.getByName(args.getString()) : Action.LIST; if (action == null) { throw new CommandInvalidTypeException(args.consumed(), "an action"); @@ -241,7 +241,7 @@ public class WaypointsCommand extends Command { } @Override - public Stream tabComplete(String label, ArgConsumer args) throws CommandException { + public Stream tabComplete(String label, IArgConsumer args) throws CommandException { if (args.hasAny()) { if (args.hasExactlyOne()) { return new TabCompleteHelper() diff --git a/src/main/java/baritone/utils/command/helpers/arguments/ArgConsumer.java b/src/main/java/baritone/utils/command/helpers/arguments/ArgConsumer.java new file mode 100644 index 00000000..06aaa6eb --- /dev/null +++ b/src/main/java/baritone/utils/command/helpers/arguments/ArgConsumer.java @@ -0,0 +1,444 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.utils.command.helpers.arguments; + +import baritone.api.IBaritone; +import baritone.api.utils.command.argument.ICommandArgument; +import baritone.api.utils.command.datatypes.IDatatype; +import baritone.api.utils.command.datatypes.IDatatypeContext; +import baritone.api.utils.command.datatypes.IDatatypeFor; +import baritone.api.utils.command.datatypes.IDatatypePost; +import baritone.api.utils.command.exception.CommandException; +import baritone.api.utils.command.exception.CommandInvalidTypeException; +import baritone.api.utils.command.exception.CommandNotEnoughArgumentsException; +import baritone.api.utils.command.exception.CommandTooManyArgumentsException; +import baritone.api.utils.command.helpers.arguments.IArgConsumer; +import baritone.api.utils.command.manager.ICommandManager; +import baritone.utils.command.argument.CommandArguments; + +import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Stream; + +public class ArgConsumer implements IArgConsumer { + + /** + * The parent {@link ICommandManager} for this {@link IArgConsumer}}. Used by {@link #context}. + */ + private final ICommandManager manager; + + /** + * The {@link IDatatypeContext} instance for this {@link IArgConsumer}}, passed to + * datatypes when an operation is performed upon them. + * + * @see IDatatype + * @see IDatatypeContext + */ + private final IDatatypeContext context; + + /** + * The list of arguments in this ArgConsumer + */ + private final LinkedList args; + + /** + * The list of consumed arguments for this ArgConsumer. The most recently consumed argument is the last one + */ + private final Deque consumed; + + private ArgConsumer(ICommandManager manager, Deque args, Deque consumed) { + this.manager = manager; + this.context = this.new Context(); + this.args = new LinkedList<>(args); + this.consumed = new LinkedList<>(consumed); + } + + public ArgConsumer(ICommandManager manager, List args) { + this(manager, new LinkedList<>(args), new LinkedList<>()); + } + + @Override + public LinkedList getArgs() { + return this.args; + } + + @Override + public Deque getConsumed() { + return this.consumed; + } + + @Override + public boolean has(int num) { + return args.size() >= num; + } + + @Override + public boolean hasAny() { + return has(1); + } + + @Override + public boolean hasAtMost(int num) { + return args.size() <= num; + } + + @Override + public boolean hasAtMostOne() { + return hasAtMost(1); + } + + @Override + public boolean hasExactly(int num) { + return args.size() == num; + } + + @Override + public boolean hasExactlyOne() { + return hasExactly(1); + } + + @Override + public ICommandArgument peek(int index) throws CommandNotEnoughArgumentsException { + requireMin(index + 1); + return args.get(index); + } + + @Override + public ICommandArgument peek() throws CommandNotEnoughArgumentsException { + return peek(0); + } + + @Override + public boolean is(Class type, int index) throws CommandNotEnoughArgumentsException { + return peek(index).is(type); + } + + @Override + public boolean is(Class type) throws CommandNotEnoughArgumentsException { + return is(type, 0); + } + + @Override + public String peekString(int index) throws CommandNotEnoughArgumentsException { + return peek(index).getValue(); + } + + @Override + public String peekString() throws CommandNotEnoughArgumentsException { + return peekString(0); + } + + @Override + public > E peekEnum(Class enumClass, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return peek(index).getEnum(enumClass); + } + + @Override + public > E peekEnum(Class enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return peekEnum(enumClass, 0); + } + + @Override + public > E peekEnumOrNull(Class enumClass, int index) throws CommandNotEnoughArgumentsException { + try { + return peekEnum(enumClass, index); + } catch (CommandInvalidTypeException e) { + return null; + } + } + + @Override + public > E peekEnumOrNull(Class enumClass) throws CommandNotEnoughArgumentsException { + return peekEnumOrNull(enumClass, 0); + } + + @Override + public T peekAs(Class type, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return peek(index).getAs(type); + } + + @Override + public T peekAs(Class type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return peekAs(type, 0); + } + + @Override + public T peekAsOrDefault(Class type, T def, int index) throws CommandNotEnoughArgumentsException { + try { + return peekAs(type, index); + } catch (CommandInvalidTypeException e) { + return def; + } + } + + @Override + public T peekAsOrDefault(Class type, T def) throws CommandNotEnoughArgumentsException { + return peekAsOrDefault(type, def, 0); + } + + @Override + public T peekAsOrNull(Class type, int index) throws CommandNotEnoughArgumentsException { + return peekAsOrDefault(type, null, index); + } + + @Override + public T peekAsOrNull(Class type) throws CommandNotEnoughArgumentsException { + return peekAsOrNull(type, 0); + } + + @Override + public T peekDatatype(IDatatypeFor datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return copy().getDatatypeFor(datatype); + } + + @Override + public T peekDatatype(IDatatypePost datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return this.peekDatatype(datatype, null); + } + + @Override + public T peekDatatype(IDatatypePost datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return copy().getDatatypePost(datatype, original); + } + + @Override + public T peekDatatypeOrNull(IDatatypeFor datatype) { + return copy().getDatatypeForOrNull(datatype); + } + + @Override + public T peekDatatypeOrNull(IDatatypePost datatype) { + return copy().getDatatypePostOrNull(datatype, null); + } + + @Override + public > T peekDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return copy().getDatatypePost(datatype, original); + } + + @Override + public > T peekDatatypePostOrDefault(D datatype, O original, T def) { + return copy().getDatatypePostOrDefault(datatype, original, def); + } + + @Override + public > T peekDatatypePostOrNull(D datatype, O original) { + return peekDatatypePostOrDefault(datatype, original, null); + } + + @Override + public > T peekDatatypeFor(Class datatype) { + return copy().peekDatatypeFor(datatype); + } + + @Override + public > T peekDatatypeForOrDefault(Class datatype, T def) { + return copy().peekDatatypeForOrDefault(datatype, def); + } + + @Override + public > T peekDatatypeForOrNull(Class datatype) { + return peekDatatypeForOrDefault(datatype, null); + } + + @Override + public ICommandArgument get() throws CommandNotEnoughArgumentsException { + requireMin(1); + ICommandArgument arg = args.removeFirst(); + consumed.add(arg); + return arg; + } + + @Override + public String getString() throws CommandNotEnoughArgumentsException { + return get().getValue(); + } + + @Override + public > E getEnum(Class enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return get().getEnum(enumClass); + } + + @Override + public > E getEnumOrDefault(Class enumClass, E def) throws CommandNotEnoughArgumentsException { + try { + peekEnum(enumClass); + return getEnum(enumClass); + } catch (CommandInvalidTypeException e) { + return def; + } + } + + @Override + public > E getEnumOrNull(Class enumClass) throws CommandNotEnoughArgumentsException { + return getEnumOrDefault(enumClass, null); + } + + @Override + public T getAs(Class type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + return get().getAs(type); + } + + @Override + public T getAsOrDefault(Class type, T def) throws CommandNotEnoughArgumentsException { + try { + T val = peek().getAs(type); + get(); + return val; + } catch (CommandInvalidTypeException e) { + return def; + } + } + + @Override + public T getAsOrNull(Class type) throws CommandNotEnoughArgumentsException { + return getAsOrDefault(type, null); + } + + @Override + public > T getDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + try { + return datatype.apply(this.context, original); + } catch (Exception e) { + e.printStackTrace(); + throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName()); + } + } + + @Override + public > T getDatatypePostOrDefault(D datatype, O original, T _default) { + final List argsSnapshot = new ArrayList<>(this.args); + final List consumedSnapshot = new ArrayList<>(this.consumed); + try { + return this.getDatatypePost(datatype, original); + } catch (Exception e) { + this.args.clear(); + this.args.addAll(argsSnapshot); + this.consumed.clear(); + this.consumed.addAll(consumedSnapshot); + return _default; + } + } + + @Override + public > T getDatatypePostOrNull(D datatype, O original) { + return this.getDatatypePostOrDefault(datatype, original, null); + } + + @Override + public > T getDatatypeFor(D datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException { + try { + return datatype.get(this.context); + } catch (Exception e) { + throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName()); + } + } + + @Override + public > T getDatatypeForOrDefault(D datatype, T def) { + final List argsSnapshot = new ArrayList<>(this.args); + final List consumedSnapshot = new ArrayList<>(this.consumed); + try { + return this.getDatatypeFor(datatype); + } catch (Exception e) { + this.args.clear(); + this.args.addAll(argsSnapshot); + this.consumed.clear(); + this.consumed.addAll(consumedSnapshot); + return def; + } + } + + @Override + public > T getDatatypeForOrNull(D datatype) { + return this.getDatatypeForOrDefault(datatype, null); + } + + @Override + public Stream tabCompleteDatatype(T datatype) { + try { + return datatype.tabComplete(this.context); + } catch (Exception e) { + e.printStackTrace(); + } + return Stream.empty(); + } + + @Override + public String rawRest() { + return args.size() > 0 ? args.getFirst().getRawRest() : ""; + } + + @Override + public void requireMin(int min) throws CommandNotEnoughArgumentsException { + if (args.size() < min) { + throw new CommandNotEnoughArgumentsException(min + consumed.size()); + } + } + + @Override + public void requireMax(int max) throws CommandTooManyArgumentsException { + if (args.size() > max) { + throw new CommandTooManyArgumentsException(max + consumed.size()); + } + } + + @Override + public void requireExactly(int args) throws CommandException { + requireMin(args); + requireMax(args); + } + + @Override + public boolean hasConsumed() { + return !consumed.isEmpty(); + } + + @Override + public ICommandArgument consumed() { + return consumed.size() > 0 ? consumed.getLast() : CommandArguments.unknown(); + } + + @Override + public String consumedString() { + return consumed().getValue(); + } + + @Override + public ArgConsumer copy() { + return new ArgConsumer(manager, args, consumed); + } + + /** + * Implementation of {@link IDatatypeContext} which adapts to the parent {@link IArgConsumer}} + */ + private final class Context implements IDatatypeContext { + + @Override + public final IBaritone getBaritone() { + return ArgConsumer.this.manager.getBaritone(); + } + + @Override + public final ArgConsumer getConsumer() { + return ArgConsumer.this; + } + } +} diff --git a/src/main/java/baritone/utils/command/manager/CommandManager.java b/src/main/java/baritone/utils/command/manager/CommandManager.java index c9c51eb1..290b3852 100644 --- a/src/main/java/baritone/utils/command/manager/CommandManager.java +++ b/src/main/java/baritone/utils/command/manager/CommandManager.java @@ -20,13 +20,14 @@ package baritone.utils.command.manager; import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.utils.command.Command; -import baritone.api.utils.command.argument.CommandArgument; +import baritone.api.utils.command.argument.ICommandArgument; import baritone.api.utils.command.exception.CommandUnhandledException; import baritone.api.utils.command.exception.ICommandException; -import baritone.api.utils.command.helpers.arguments.ArgConsumer; +import baritone.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.manager.ICommandManager; import baritone.api.utils.command.registry.Registry; +import baritone.utils.command.argument.CommandArguments; import baritone.utils.command.defaults.DefaultCommands; import net.minecraft.util.Tuple; @@ -76,7 +77,7 @@ public class CommandManager implements ICommandManager { } @Override - public boolean execute(Tuple> expanded) { + public boolean execute(Tuple> expanded) { ExecutionWrapper execution = this.from(expanded); if (execution != null) { execution.execute(); @@ -85,16 +86,16 @@ public class CommandManager implements ICommandManager { } @Override - public Stream tabComplete(Tuple> expanded) { + public Stream tabComplete(Tuple> expanded) { ExecutionWrapper execution = this.from(expanded); return execution == null ? Stream.empty() : execution.tabComplete(); } @Override public Stream tabComplete(String prefix) { - Tuple> pair = expand(prefix, true); + Tuple> pair = expand(prefix, true); String label = pair.getFirst(); - List args = pair.getSecond(); + List args = pair.getSecond(); if (args.isEmpty()) { return new TabCompleteHelper() .addCommands(this.baritone.getCommandManager()) @@ -105,7 +106,7 @@ public class CommandManager implements ICommandManager { } } - private ExecutionWrapper from(Tuple> expanded) { + private ExecutionWrapper from(Tuple> expanded) { String label = expanded.getFirst(); ArgConsumer args = new ArgConsumer(this, expanded.getSecond()); @@ -113,13 +114,13 @@ public class CommandManager implements ICommandManager { return command == null ? null : new ExecutionWrapper(command, label, args); } - private static Tuple> expand(String string, boolean preserveEmptyLast) { + private static Tuple> expand(String string, boolean preserveEmptyLast) { String label = string.split("\\s", 2)[0]; - List args = CommandArgument.from(string.substring(label.length()), preserveEmptyLast); + List args = CommandArguments.from(string.substring(label.length()), preserveEmptyLast); return new Tuple<>(label, args); } - public static Tuple> expand(String string) { + public static Tuple> expand(String string) { return expand(string, false); } @@ -143,7 +144,7 @@ public class CommandManager implements ICommandManager { ? (ICommandException) t : new CommandUnhandledException(t); - exception.handle(command, args.args); + exception.handle(command, args.getArgs()); } } From bfd8773efa6f9fc08db48551cc2b2d0c2d3abaab Mon Sep 17 00:00:00 2001 From: Brady Date: Fri, 4 Oct 2019 09:20:26 -0500 Subject: [PATCH 682/682] Make getBaritoneForPlayer null-safe --- src/api/java/baritone/api/IBaritoneProvider.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index bdefb66f..c5c6cf39 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -21,6 +21,7 @@ import baritone.api.cache.IWorldScanner; import net.minecraft.client.entity.EntityPlayerSP; import java.util.List; +import java.util.Objects; /** * Provides the present {@link IBaritone} instances @@ -57,7 +58,7 @@ public interface IBaritoneProvider { */ default IBaritone getBaritoneForPlayer(EntityPlayerSP player) { for (IBaritone baritone : getAllBaritones()) { - if (player.equals(baritone.getPlayerContext().player())) { + if (Objects.equals(player, baritone.getPlayerContext().player())) { return baritone; } }