From e3c4d06b2b4c7dfc20bb44c2620032d38bdbedd6 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 30 Aug 2019 11:55:25 -0700 Subject: [PATCH 01/57] 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 0834b1e85..bd3b054a3 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 80dcf5ce5..6ff013525 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 157774489..8890fdc33 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 caa44cbc6..6f4349ace 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 000000000..d5bed1ff2 --- /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 000000000..987e64f7c --- /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 71045768a..9e5b6dbb4 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 dc471e5fb..00b24e3df 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 000000000..dfe5c7707 --- /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 7f8d16abe..5ad233363 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 f73f0e746..5ca5f8049 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 7ebabc9cb..4885e32f9 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 000000000..7168687d3 --- /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 000000000..c711d7259 --- /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 a7e006086..7d148c9f2 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 000000000..39b52f217 --- /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 16a56667c..de0cbf6ba 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 99683d8ad..7b36a7165 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 000000000..2ad44823d --- /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 4e659dec3..17387aa0f 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 000000000..3de8a7ebe --- /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 000000000..26fca9e19 --- /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 000000000..5c56544eb --- /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 000000000..8fc08e860 --- /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 000000000..6b5d47614 --- /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 000000000..301ad8911 --- /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 000000000..1d8890ed6 --- /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 000000000..5b507fcdd --- /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 000000000..c8cfe2741 --- /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 000000000..eb8417240 --- /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 000000000..7b7dbf72e --- /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 000000000..35caeaa27 --- /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 000000000..313fd6b16 --- /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 000000000..2168f25a6 --- /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 000000000..07e765e58 --- /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 000000000..788986b1f --- /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 000000000..9516fea77 --- /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 000000000..58013f4fc --- /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 000000000..130335496 --- /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 000000000..28ff08bb0 --- /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 000000000..8607c5122 --- /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 000000000..041eeded2 --- /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 000000000..367bc6987 --- /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 000000000..e51fa5fc9 --- /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 000000000..ab6b33712 --- /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 000000000..416feae57 --- /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 000000000..300cf9744 --- /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 000000000..f3da2913b --- /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 000000000..9817afb7f --- /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 000000000..94fcd4ede --- /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 000000000..18e0bc9d7 --- /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 000000000..1b5934ba7 --- /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 000000000..4c05bd02d --- /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 000000000..a4b2d746a --- /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 000000000..2bd41ae4b --- /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 000000000..1828dec38 --- /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 000000000..1f9ce9a7d --- /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 000000000..a2ae89519 --- /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 000000000..e78cb696e --- /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 000000000..7790f2a49 --- /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 000000000..cb6a2fbf8 --- /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 000000000..e96bf5eb5 --- /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 000000000..da420db8d --- /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 000000000..ec87dd753 --- /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 000000000..2eafe55c9 --- /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 000000000..d7746623c --- /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 000000000..68dbc3397 --- /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 000000000..633701ba0 --- /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 000000000..82398b353 --- /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 000000000..d371603e1 --- /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 000000000..163408cce --- /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 000000000..2522674f4 --- /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 000000000..e9541131e --- /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 000000000..62b47562a --- /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 000000000..a232ddc31 --- /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 000000000..0b33c2d61 --- /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 000000000..8e12f6b67 --- /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 000000000..342cf3366 --- /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 000000000..76ad3af0b --- /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 000000000..0988774d3 --- /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 000000000..4dbbb9622 --- /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 000000000..29d5d6bad --- /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 000000000..44d3b7b24 --- /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 000000000..459940ab9 --- /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 000000000..849ace189 --- /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 000000000..2999666a8 --- /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 000000000..6c9ef884e --- /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 000000000..db7942b6d --- /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 000000000..ce689b0b4 --- /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 000000000..75dff5661 --- /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 000000000..c92d4d564 --- /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 000000000..8aabfd69e --- /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 000000000..310bfd7ca --- /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 000000000..0731df1f1 --- /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 000000000..4e36491b9 --- /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 3b5fa70cc..66ef181d1 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 a4b2d4368..d2aae7766 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 7219175ed..d1d9a7d51 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 d6cf69c3b..22c042f77 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 2ff688ad0..76ae0b4e0 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 84ea8da37..0c37ac162 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 00273a9f4..e78c0ce1f 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 4fb4d540e..755f27c2a 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 f3b1d20bc..1b3ef0f14 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 b01572477..cb5e7be08 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 000000000..72733f27d --- /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 02/57] 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 7168687d3..6116f22b9 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 c711d7259..54f85ecd9 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 39b52f217..d2297d3b8 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 3de8a7ebe..753f82490 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 5b507fcdd..8309e696a 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 c8cfe2741..469e9caf0 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 eb8417240..dc9d0baeb 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 7b7dbf72e..eb4047dc8 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 07e765e58..1d9a48dd0 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 9516fea77..3213a0338 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 58013f4fc..41b6ff55b 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 ab6b33712..e7fd614ec 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 2bd41ae4b..6b2570124 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 a2ae89519..201346e63 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 cb6a2fbf8..692d64224 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 e96bf5eb5..efe0d0e22 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 2eafe55c9..c184db7fe 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 68dbc3397..fdbb0a402 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 e9541131e..6a23c2a45 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 6c9ef884e..8f6b91f01 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 8aabfd69e..39fbb19d6 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 310bfd7ca..9af0a3e9c 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 0731df1f1..35fcc38b3 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 4e36491b9..6046ed218 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 66ef181d1..1d1c356ba 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 03/57] 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 6f4349ace..009268fbc 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 4885e32f9..aa01aa5ae 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 6116f22b9..000000000 --- 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 000000000..b77bf541e --- /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 000000000..eafe49e16 --- /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 54f85ecd9..000000000 --- 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 d2297d3b8..000000000 --- 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 2ad44823d..000000000 --- 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 eb4047dc8..7226d0cb3 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 ec87dd753..1cd869d8e 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 d7746623c..b0d2e1b58 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 000000000..54ead39a7 --- /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 000000000..b419952dc --- /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 1d1c356ba..c11162794 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 22c042f77..365c8bf76 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 e78c0ce1f..00273a9f4 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 755f27c2a..c891f1098 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 1b3ef0f14..7e59bc926 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 000000000..735e183a8 --- /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 04/57] 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 b77bf541e..dcfda0f88 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 eafe49e16..2457484fc 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 9acb2ad92..a9f7cdf7b 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 b419952dc..343bdda62 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 67ac69420..148b21e71 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 7e59bc926..75648ae18 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 05/57] 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 148b21e71..67ac69420 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 75648ae18..c253cdf85 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 06/57] 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 c253cdf85..fd62c5cfc 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 07/57] 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 fd62c5cfc..18c7a7b15 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 08/57] 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 000000000..120b58674 --- /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 18e0bc9d7..fac6422ff 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 b0d2e1b58..ff8bc783c 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 09/57] 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 5ad233363..86511b545 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 301ad8911..03d3b5c99 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 fac6422ff..9d260e761 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 000000000..5eeeeba9a --- /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 10/57] 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 343bdda62..e3b7cbeba 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 365c8bf76..3c314e712 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 735e183a8..ad602f37e 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 11/57] 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 54ead39a7..614ec3514 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 e3b7cbeba..8a1b000f6 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 000000000..fef080448 --- /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 ad602f37e..aa2eaab43 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 12/57] 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 3c314e712..b5ca6a6ab 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 13/57] 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 b5ca6a6ab..3acd9661b 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 14/57] 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 614ec3514..d3a3f1678 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 15/57] 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 d3a3f1678..5bb738a2e 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 16/57] 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 000000000..22438277e --- /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 5bb738a2e..e0782803d 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 8a1b000f6..d3de16f0c 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 fef080448..1fd912a2e 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 17/57] 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 e0782803d..2719cfa7c 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 18/57] 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 8f6b91f01..e050239c4 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 19/57] 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 4ac0f7233..53ab195d4 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 849ace189..dba4513e5 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 e050239c4..9cec8d1f9 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 20/57] 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 41b6ff55b..b612e3424 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 6b2570124..1dd485128 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 21/57] 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 dcfda0f88..5bfabb4cf 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 000000000..8d0f770ef --- /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 c11162794..ff4cc5849 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 22/57] 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 2b9a7232b..ac57ea34c 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 201346e63..6cfaa59b5 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 23/57] 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 7b36a7165..9bb573bef 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 a9f7cdf7b..457af87b9 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 753f82490..be390e2a7 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 ff8bc783c..283aba68d 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 9cec8d1f9..df20d3b4e 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 24/57] 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 000000000..68439905b --- /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 5bfabb4cf..836cbbc56 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 2457484fc..2e7cf42e7 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 22438277e..000000000 --- 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 000000000..a53e452b0 --- /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 ff4cc5849..0211d1f0f 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 18c7a7b15..b7eb2bb8e 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 25/57] 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 a53e452b0..4f27152d7 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 26/57] 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 836cbbc56..098dc2696 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 27/57] 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 098dc2696..ac817e27a 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 28/57] 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 ac817e27a..90d163d88 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 29/57] 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 6ff013525..316d6e475 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 ac57ea34c..720e835e8 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 89dd63048..55385f467 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 fb2a07aaf..6bf4d026e 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 4f75aba72..94a02ba57 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 3f4a02de1..85e294a35 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 24ae385ac..167a00a65 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 f1026ab50..d0b51e175 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 86511b545..aeb301b05 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 9add7176a..fed62c749 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 3b94a8339..b0f536e53 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 e37dea197..56f6976be 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 17387aa0f..3a2f4f1f9 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 be390e2a7..a06887b26 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 300cf9744..a9ca11fb9 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 d98e32376..5caee6a34 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 b96692f2d9ed27417b9da4bafc6290ce52bb9930 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 13:12:06 -0700 Subject: [PATCH 30/57] 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 6a23c2a45..d5767de95 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 31/57] 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 01df2a48b..23df5d39f 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 720e835e8..f126de386 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 56f6976be..998a981f4 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 03d3b5c99..ae80734d3 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 000000000..6cc358e44 --- /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 788986b1f..28c86e80d 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 df20d3b4e..3cf823a09 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 db7942b6d..24d0b6a31 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 5caee6a34..aac6b5542 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 18b13b89b..448dddd30 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 32/57] 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 316d6e475..ebebc4d4f 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 b7dd442dc..5bd19bc28 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 69a5ae9a2..353474b29 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 b405a610bbd3cb9d314bd958fb0d239cd6719a4d Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Sun, 1 Sep 2019 15:53:13 -0700 Subject: [PATCH 33/57] 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 0c37ac162..5fded3f3d 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 fd253105e..c9c9e0f5d 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 34/57] 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 821dc68c3..0b2f92d91 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 8d0f770ef..9e2e2396a 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 eface5c0d..0d600853e 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 5fded3f3d..b3f31059a 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 c9c9e0f5d..6bac6ce6f 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 fa1c2d006..32b3292ca 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 55dfb6192..3efb24044 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 fd0ace8ca..3ba9c314e 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 35/57] 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 2c892d982..4ca48c249 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 ebebc4d4f..8d649d4bd 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 000000000..4067c3078 --- /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 000000000..d7513160c --- /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 000000000..48355a14e --- /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 26fca9e19..7fa3b2a89 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 1c3f3f108..d640f0791 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 000000000..ef66be5ee --- /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 d2aae7766..a0e190155 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 000000000..68b8021bc --- /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 000000000..b95c60b2b --- /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 000000000..48f8ae499 --- /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 ce5c28a0c..9f8053875 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 cb5e7be08..3de40b91b 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 36/57] 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 000000000..3b6bb41cd --- /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 000000000..56c49b80f --- /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 000000000..c34cd1123 --- /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 000000000..b7536e819 --- /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 000000000..033e390c0 --- /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 000000000..2c94fa9f0 --- /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 000000000..8091944ef --- /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 90d163d88..bd17307c1 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 ef66be5ee..c696bd722 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 37/57] 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 efe0d0e22..a4ec3f239 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 d5767de95..f343c56e1 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 65d2bdaf2bb40a0c566c5779ef98d3e352e62f9f Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Tue, 3 Sep 2019 06:09:02 -0700 Subject: [PATCH 38/57] 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 d7513160c..763714e7d 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 000000000..f65f1c550 --- /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 c696bd722..366ec9f2e 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 68b8021bc..3b3855030 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 b95c60b2b..5fea4cba7 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 39/57] 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 366ec9f2e..78d790148 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 40/57] 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 78d790148..2579a3bd9 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 41/57] 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 3b6bb41cd..ec4d8731a 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 56c49b80f..deb9f5fe4 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 b7536e819..7989cbfc6 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 033e390c0..133e4e626 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 000000000..2d13f1eba --- /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 2c94fa9f0..c6c1bcf26 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 8091944ef..ed66e2fc0 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 bd17307c1..1fd4264f6 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 2579a3bd9..fea637e83 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 b3f31059a..6bea9a7c5 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 42/57] 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 ec4d8731a..4a7e9b255 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 43/57] 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 7989cbfc6..a9b5f3561 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 1fd4264f6..bd17307c1 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 44/57] 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 fea637e83..3ef7b2ec5 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 45/57] 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 8d649d4bd..67f5496ed 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 48355a14e..7bdb970ee 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 3ef7b2ec5..eb09895d4 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 48f8ae499..4d0fd9a76 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 3de40b91b..9ebb58d46 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 46/57] 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 67f5496ed..1bdb1e397 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 7bdb970ee..5fb024eab 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 eb09895d4..446724dc1 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 f343c56e1..90f4e351a 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 4d0fd9a76..a696fe67a 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 9ebb58d46..3d1412169 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 47/57] 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 b612e3424..b47983b0d 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 e7fd614ec..c18cc1a45 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 48/57] 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 68439905b..ac0f760f5 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 987e64f7c..1ec29c67b 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 4a7e9b255..cee9ff9af 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 deb9f5fe4..bb4c6cc1e 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 c34cd1123..6e97e41fb 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 a9b5f3561..6fc9eff8c 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 133e4e626..34b1478bd 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 2d13f1eba..d29179c8f 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 c6c1bcf26..aa249ea07 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 ed66e2fc0..bc6325643 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 4067c3078..4771c2e9c 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 763714e7d..e69549f9a 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 2e7cf42e7..44c756d1d 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 5fb024eab..534c509e8 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 5c56544eb..47bb83362 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 469e9caf0..13e3d6862 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 dc9d0baeb..ea22dc909 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 7226d0cb3..e44b7652b 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 f65f1c550..2dbadd9da 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 6cc358e44..90a1c71cf 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 35caeaa27..1684fd2fe 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 313fd6b16..f0c4cb61d 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 2168f25a6..4e74f03ea 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 1d9a48dd0..f38028bda 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 28c86e80d..ab728ede3 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 3213a0338..8d5cc70bf 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 b47983b0d..afc829784 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 130335496..a0f94cee2 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 28ff08bb0..1a907135c 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 8607c5122..7e9b85f9c 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 041eeded2..9d00350e7 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 283aba68d..8696a2da5 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 49/57] 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 d29179c8f..4c7ee546e 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 4c05bd02d..000000000 --- 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 75dff5661..287acaa51 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 a0e190155..0b7e614fe 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 367bc6987..59f638673 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 e51fa5fc9..bb19480f1 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 c18cc1a45..1c64f118b 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 416feae57..a07bfc3b1 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 a9ca11fb9..6d4fac078 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 f3da2913b..974a9867e 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 120b58674..559752bd1 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 9817afb7f..0b5f40ce3 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 94fcd4ede..0ffaf427b 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 d640f0791..a52d252ad 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 1b5934ba7..15951182d 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 a4b2d746a..24e02f260 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 1dd485128..848e913ba 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 1828dec38..8c265912e 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 1f9ce9a7d..6fd620d16 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 6cfaa59b5..0107ee3b8 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 e78cb696e..685db0c33 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 7790f2a49..17e241cf2 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 692d64224..883aed7e4 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 a4ec3f239..16bb128af 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 da420db8d..a29f2c9b1 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 1cd869d8e..ebfb7fe17 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 c184db7fe..d65819fae 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 8696a2da5..2b3919e42 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 fdbb0a402..469089f69 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 633701ba0..73a0245de 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 82398b353..3fa07ca33 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 d371603e1..0cf2ae787 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 163408cce..a34a6a583 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 2522674f4..edef29a7d 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 446724dc1..c6529d3d0 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 90f4e351a..3bf6267ec 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 5eeeeba9a..d16dbd94e 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 62b47562a..00d9e67cf 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 a232ddc31..6cd06f9ce 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 78da79af3..894b23a0b 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 8a001a2438cc4fd387009ea00052a901d643df68 Mon Sep 17 00:00:00 2001 From: Logan Darklock Date: Fri, 6 Sep 2019 03:59:10 -0700 Subject: [PATCH 50/57] 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 1bdb1e397..2952ed648 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 47bb83362..3eed255f9 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 8890fdc33..5444bb838 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 23df5d39f..238b4d88f 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 009268fbc..325d4bd0e 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 1ec29c67b..7690ee8f6 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 dfe5c7707..7f072c4df 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 5ca5f8049..c48c2a046 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 cee9ff9af..27bf69361 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 bb4c6cc1e..d278fa4cc 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 6fc9eff8c..8a55376f6 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 34b1478bd..63a4f86f3 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 4c7ee546e..b74c564ff 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 bd17307c1..3776baf36 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 44c756d1d..963d147ca 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 7d148c9f2..633e3acbe 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 998a981f4..000000000 --- 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 9bb573bef..87884cd2a 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 457af87b9..b461c3891 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 0b2f92d91..b2dfc308e 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 e726a9cc5..5c8ab83f5 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 a06887b26..df7bab65d 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 7fa3b2a89..410a34a92 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 6b5d47614..619fa67a3 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 ae80734d3..fe964bce8 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 1d8890ed6..c8ac7630b 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 8309e696a..5d2975286 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 13e3d6862..617ccb57f 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 ea22dc909..09cdbb925 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 90a1c71cf..47b634804 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 1684fd2fe..5af2a0b83 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 f38028bda..a3c54b487 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 8d5cc70bf..866017c71 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 afc829784..fa0be0b46 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 1a907135c..0730b5178 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 dba4513e5..9de56284e 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 3cf823a09..c68b77c2e 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 24d0b6a31..2fb2f5bc0 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 ce689b0b4..972b634d9 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 c92d4d564..b17997d35 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 39fbb19d6..1cbf32e73 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 9af0a3e9c..86f2b1b01 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 35fcc38b3..78da7b212 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 4f27152d7..03f5e25fb 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 9e2e2396a..de74a4dba 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 6046ed218..b07dd9d0f 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 0b7e614fe..4b00c7974 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 0d600853e..c278738a2 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 d1d9a7d51..c3aa2ad91 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 3acd9661b..458e7afe3 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 5bd19bc28..b8739d1c7 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 cbc8cdd86..66827a35f 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 8e660affd..41a183f8a 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 4eab7144f..c1f5ed012 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 6bea9a7c5..4d3c2e5c4 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 4defff5d5..3c0ef0a22 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 b7eb2bb8e..a741c6d6e 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 a696fe67a..435f7dc7e 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 9f8053875..48b80231c 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 534c509e8..f9315de69 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 3d1412169..bfa0dc2d1 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 59f638673..794af0c56 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 bb19480f1..1152ee083 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 1c64f118b..dd789ccb4 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 a07bfc3b1..49fdc537f 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 6d4fac078..72e07da1a 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 974a9867e..68fc547ea 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 559752bd1..494ae8f7e 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 0b5f40ce3..cfbf1f464 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 0ffaf427b..c407ca690 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 a52d252ad..213bd393f 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 15951182d..9298f32a9 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 24e02f260..c0925342e 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 848e913ba..9f637257e 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 8c265912e..4390585c1 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 6fd620d16..4f71366a1 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 0107ee3b8..7588edd23 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 685db0c33..5bd7d58a2 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 17e241cf2..7e838c6f8 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 883aed7e4..55f099288 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 16bb128af..ccd7d6401 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 a29f2c9b1..1a46bdc74 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 ebfb7fe17..0f155e744 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 d65819fae..b2c7e69fe 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 2b3919e42..b8b3f91f0 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 469089f69..a0ada87fa 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 73a0245de..a7904bda4 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 3fa07ca33..90a260a5d 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 0cf2ae787..357197eea 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 a34a6a583..953e75270 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 edef29a7d..be455bc2a 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 c6529d3d0..f04e09707 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 3bf6267ec..4588c4500 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 d16dbd94e..2f83cb0cf 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 00d9e67cf..8d59fba64 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 6cd06f9ce..71b30c199 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 894b23a0b..7069e02f1 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 6bac6ce6f..86fc7bae0 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 3efb24044..93e781204 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 3ba9c314e..548e3e372 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 51/57] 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 27bf69361..c1cb6bde0 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 d278fa4cc..ecb0dd70f 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 8a55376f6..20b1c2502 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 63a4f86f3..a0589cee5 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 b74c564ff..ca2577c87 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 aa249ea07..d6a734bea 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 bc6325643..388fdb4de 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 619fa67a3..c96418a49 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 fe964bce8..2f51bbad4 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 5d2975286..e793b8b5c 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 47b634804..3cb27a508 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 a3c54b487..6ef22b935 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 c68b77c2e..75cf5962c 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 bfa0dc2d1..b64995c24 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 f04e09707..fcaae5ed1 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 52/57] 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 0730b5178..a4dc75bd8 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 75cf5962c..a0c1f7936 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 b17997d35..4a8badd29 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 f9315de69..2de47ed75 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 b64995c24..8f8a35787 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 53/57] "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 df7bab65d..23bbd4a7b 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 410a34a92..bb00c8a75 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 c96418a49..7237ea078 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 2f51bbad4..7518e4593 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 e793b8b5c..49d8f477a 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 617ccb57f..e8d1589c8 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 09cdbb925..fd053584c 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 2dbadd9da..f91eea0a1 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 3cb27a508..c6720b1c2 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 6ef22b935..376f6b632 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 ab728ede3..f8b778df9 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 a0f94cee2..4b4170a9f 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 a4dc75bd8..ff3324935 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 342cf3366..76d639798 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 9de56284e..9c1f2f350 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 2999666a8..1563405ea 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 2fb2f5bc0..22c796d00 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 972b634d9..2878b8dff 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 287acaa51..425da5efa 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 4a8badd29..82a3dc6fe 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 8f8a35787..589174364 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 54/57] 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 4d3c2e5c4..0d84d9527 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 55/57] 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 a741c6d6e..01c248845 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 56/57] 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 3776baf36..22ba74ea5 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 57/57] 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 4b00c7974..7f70bbea2 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 44715f4c5..9fdd0489f 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;