This commit is contained in:
Logan Darklock 2019-09-06 03:59:10 -07:00
parent 69e3481a32
commit 8a001a2438
No known key found for this signature in database
GPG Key ID: B8C37CEDE1AC60EA
100 changed files with 2065 additions and 1341 deletions

View File

@ -495,7 +495,7 @@ public final class Settings {
/** /**
* Render the path as a line instead of a frickin thingy * Render the path as a line instead of a frickin thingy
*/ */
public final Setting<Boolean> renderPathAsLine = new Setting<>(true); public final Setting<Boolean> renderPathAsLine = new Setting<>(false);
/** /**
* Render the goal * Render the goal

View File

@ -15,10 +15,10 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>. * along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/ */
package baritone.api.utils.command; package baritone.api.accessor;
import java.net.URI; import java.net.URI;
public interface Lol { public interface IGuiScreen {
void openLink(URI url); void openLink(URI url);
} }

View File

@ -74,7 +74,9 @@ public interface IPathingBehavior extends IBehavior {
* is a pause in effect. * is a pause in effect.
* @see #isPathing() * @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. * Cancels the pathing behavior or the current path calculation, and all processes that could be controlling path.

View File

@ -18,11 +18,14 @@
package baritone.api.cache; package baritone.api.cache;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import static java.util.Arrays.asList;
/** /**
* A marker for a position in the world. * 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. * @return A name that can be passed to {@link #getByName(String)} to retrieve this tag
*
* @param name The name of the tag
* @return The tag, if one is found, otherwise, {@code null}
*/ */
public static Tag fromString(String name) { public String getName() {
return TAG_LIST.stream().filter(tag -> ArrayUtils.contains(tag.names, name.toLowerCase())).findFirst().orElse(null); 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<String> names = new HashSet<>();
for (Tag tag : Tag.values()) {
names.addAll(asList(tag.names));
}
return names.toArray(new String[0]);
} }
} }
} }

View File

@ -34,12 +34,11 @@ public interface IWorldScanner {
/** /**
* Scans the world, up to the specified max chunk radius, for the specified blocks. * 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 * @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon
* scan is based upon
* @param filter The blocks to scan for * @param filter The blocks to scan for
* @param max The maximum number of blocks to scan before cutoff * @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 * @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value
* returned, if the value is negative, then this condition doesn't apply. * is negative, then this condition doesn't apply.
* @param maxSearchRadius The maximum chunk search radius * @param maxSearchRadius The maximum chunk search radius
* @return The matching block positions * @return The matching block positions
*/ */
@ -52,14 +51,36 @@ public interface IWorldScanner {
/** /**
* Scans a single chunk for the specified blocks. * Scans a single chunk for the specified blocks.
* *
* @param ctx The {@link IPlayerContext} containing player and world info that the * @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon
* scan is based upon
* @param filter The blocks to scan for * @param filter The blocks to scan for
* @param pos The position of the target chunk * @param pos The position of the target chunk
* @param max The maximum number of blocks to scan before cutoff * @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 * @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value
* returned, if the value is negative, then this condition doesn't apply. * is negative, then this condition doesn't apply.
* @return The matching block positions * @return The matching block positions
*/ */
List<BlockPos> scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold); List<BlockPos> 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<BlockPos> scanChunk(IPlayerContext ctx, List<Block> 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);
} }

View File

@ -44,8 +44,8 @@ public class Overrideable<T> {
@Override @Override
public String toString() { public String toString() {
return String.format( return String.format(
"Overrideable{modified=%s,value=%s}", "Overrideable{modified=%b,value=%s}",
Boolean.toString(modified), modified,
value.toString() value.toString()
); );
} }

View File

@ -18,7 +18,12 @@
package baritone.api.pathing.goals; 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 <i>effectively</i> 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 * @author LoganDark
*/ */

View File

@ -18,11 +18,13 @@
package baritone.api.process; package baritone.api.process;
import baritone.api.utils.ISchematic; import baritone.api.utils.ISchematic;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
import java.io.File; import java.io.File;
import java.util.List;
/** /**
* @author Brady * @author Brady
@ -63,4 +65,11 @@ public interface IBuilderProcess extends IBaritoneProcess {
void resume(); void resume();
void clearArea(BlockPos corner1, BlockPos corner2); 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<IBlockState> getApproxPlaceable();
} }

View File

@ -40,7 +40,7 @@ public abstract class AbstractSchematic implements ISchematic {
protected int y; protected int y;
protected int z; 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.baritone = baritone;
this.ctx = baritone == null ? null : baritone.getPlayerContext(); this.ctx = baritone == null ? null : baritone.getPlayerContext();
this.x = x; this.x = x;
@ -62,36 +62,4 @@ public abstract class AbstractSchematic implements ISchematic {
public int lengthZ() { public int lengthZ() {
return z; return z;
} }
protected IBlockState[] approxPlaceable() {
EntityPlayerSP player = ctx.player();
NonNullList<ItemStack> inventory = player.inventory.mainInventory;
List<IBlockState> 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;
// <toxic cloud>
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
));
// </toxic cloud>
}
}
return placeable.toArray(new IBlockState[0]);
}
} }

View File

@ -67,13 +67,13 @@ public class CompositeSchematic extends AbstractSchematic {
} }
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
CompositeSchematicEntry entry = getSchematic(x, y, z, current); CompositeSchematicEntry entry = getSchematic(x, y, z, current);
if (entry == null) { if (entry == null) {
throw new IllegalStateException("couldn't find schematic for this position"); 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);
} }
} }

View File

@ -22,10 +22,12 @@ import baritone.api.utils.BlockOptionalMeta;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
public class FillBomSchematic extends AbstractSchematic { import java.util.List;
public class FillSchematic extends AbstractSchematic {
private final BlockOptionalMeta bom; 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); super(baritone, x, y, z);
this.bom = bom; this.bom = bom;
} }
@ -35,14 +37,14 @@ public class FillBomSchematic extends AbstractSchematic {
} }
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
if (bom.matches(current)) { if (bom.matches(current)) {
return current; return current;
} else if (current.getBlock() != Blocks.AIR) { } else if (current.getBlock() != Blocks.AIR) {
return Blocks.AIR.getDefaultState(); return Blocks.AIR.getDefaultState();
} }
for (IBlockState placeable : approxPlaceable()) { for (IBlockState placeable : approxPlaceable) {
if (bom.matches(placeable)) { if (bom.matches(placeable)) {
return placeable; return placeable;
} }

View File

@ -21,6 +21,8 @@ import baritone.api.IBaritone;
import baritone.api.utils.ISchematic; import baritone.api.utils.ISchematic;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import java.util.List;
public abstract class MaskSchematic extends AbstractSchematic { public abstract class MaskSchematic extends AbstractSchematic {
private final ISchematic schematic; private final ISchematic schematic;
@ -37,7 +39,7 @@ public abstract class MaskSchematic extends AbstractSchematic {
} }
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
return schematic.desiredState(x, y, z, current); return schematic.desiredState(x, y, z, current, approxPlaceable);
} }
} }

View File

@ -24,15 +24,17 @@ import net.minecraft.block.state.IBlockState;
public class ReplaceSchematic extends MaskSchematic { public class ReplaceSchematic extends MaskSchematic {
private final BlockOptionalMetaLookup filter; private final BlockOptionalMetaLookup filter;
private final boolean[][][] cache; private final Boolean[][][] cache;
public ReplaceSchematic(IBaritone baritone, ISchematic schematic, BlockOptionalMetaLookup filter) { public ReplaceSchematic(IBaritone baritone, ISchematic schematic, BlockOptionalMetaLookup filter) {
super(baritone, schematic); super(baritone, schematic);
this.filter = filter; 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) { 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];
} }
} }

View File

@ -56,6 +56,7 @@ import net.minecraft.util.ResourceLocation;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
@ -79,6 +80,42 @@ public final class BlockOptionalMeta {
private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$");
private static final Map<Object, Object> normalizations; private static final Map<Object, Object> 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 { static {
Map<Object, Object> _normalizations = new HashMap<>(); Map<Object, Object> _normalizations = new HashMap<>();
Consumer<Enum> put = instance -> _normalizations.put(instance.getClass(), instance); Consumer<Enum> put = instance -> _normalizations.put(instance.getClass(), instance);
@ -172,7 +209,7 @@ public final class BlockOptionalMeta {
_normalizations.put(BlockWall.EAST, false); _normalizations.put(BlockWall.EAST, false);
_normalizations.put(BlockWall.WEST, false); _normalizations.put(BlockWall.WEST, false);
_normalizations.put(BlockWall.SOUTH, false); _normalizations.put(BlockWall.SOUTH, false);
normalizations = _normalizations; normalizations = Collections.unmodifiableMap(_normalizations);
} }
private static <C extends Comparable<C>, P extends IProperty<C>> P castToIProperty(Object value) { private static <C extends Comparable<C>, P extends IProperty<C>> P castToIProperty(Object value) {
@ -180,7 +217,6 @@ public final class BlockOptionalMeta {
return (P) value; return (P) value;
} }
@SuppressWarnings("unused")
private static <C extends Comparable<C>, P extends IProperty<C>> C castToIPropertyValue(P iproperty, Object value) { private static <C extends Comparable<C>, P extends IProperty<C>> C castToIPropertyValue(P iproperty, Object value) {
//noinspection unchecked //noinspection unchecked
return (C) value; return (C) value;
@ -225,7 +261,7 @@ public final class BlockOptionalMeta {
private static Set<IBlockState> getStates(@Nonnull Block block, @Nullable Integer meta) { private static Set<IBlockState> getStates(@Nonnull Block block, @Nullable Integer meta) {
return block.getBlockState().getValidStates().stream() return block.getBlockState().getValidStates().stream()
.filter(blockstate -> meta == null || stateMeta(blockstate) == meta) .filter(blockstate -> meta == null || stateMeta(blockstate) == meta)
.collect(Collectors.toCollection(HashSet::new)); .collect(Collectors.toSet());
} }
private static ImmutableSet<Integer> getStateHashes(Set<IBlockState> blockstates) { private static ImmutableSet<Integer> getStateHashes(Set<IBlockState> 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() { public Block getBlock() {
return block; return block;
} }

View File

@ -45,6 +45,12 @@ public class BlockOptionalMetaLookup {
.toArray(BlockOptionalMeta[]::new); .toArray(BlockOptionalMeta[]::new);
} }
public BlockOptionalMetaLookup(String... blocks) {
this.boms = Arrays.stream(blocks)
.map(BlockOptionalMeta::new)
.toArray(BlockOptionalMeta[]::new);
}
public boolean has(Block block) { public boolean has(Block block) {
for (BlockOptionalMeta bom : boms) { for (BlockOptionalMeta bom : boms) {
if (bom.getBlock() == block) { if (bom.getBlock() == block) {

View File

@ -22,7 +22,6 @@ import net.minecraft.util.ResourceLocation;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
public class BlockUtils { public class BlockUtils {
private static transient Map<String, Block> resourceCache = new HashMap<>(); private static transient Map<String, Block> resourceCache = new HashMap<>();
@ -39,7 +38,11 @@ public class BlockUtils {
public static Block stringToBlockRequired(String name) { public static Block stringToBlockRequired(String name) {
Block block = stringToBlockNullable(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; return block;
} }

View File

@ -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 <https://www.gnu.org/licenses/>.
*/
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<Settings.Setting<Boolean>> toggleable = BaritoneAPI.getSettings().getAllValuesByType(Boolean.class);
for (Settings.Setting<Boolean> 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 <num>");
}
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<IBaritoneProcess> 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<BlockPos, IRememberedInventory> 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<Entity> 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<Entity> 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<BlockPos> 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<IWaypoint> waypoints = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getByTag(tag);
// might as well show them from oldest to newest
List<IWaypoint> 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<ItemStack> 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();
}
}

View File

@ -39,14 +39,15 @@ public interface Helper {
Helper HELPER = new Helper() {}; Helper HELPER = new Helper() {};
static ITextComponent getPrefix() { static ITextComponent getPrefix() {
return new TextComponentString("") {{ ITextComponent baritone = new TextComponentString(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone");
getStyle().setColor(TextFormatting.DARK_PURPLE); baritone.getStyle().setColor(TextFormatting.LIGHT_PURPLE);
appendSibling(new TextComponentString("[")); ITextComponent prefix = new TextComponentString("");
appendSibling(new TextComponentString(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone") {{ prefix.getStyle().setColor(TextFormatting.DARK_PURPLE);
getStyle().setColor(TextFormatting.LIGHT_PURPLE); prefix.appendText("[");
}}); prefix.appendSibling(baritone);
appendSibling(new TextComponentString("]")); prefix.appendText("]");
}};
return prefix;
} }
Minecraft mc = Minecraft.getMinecraft(); Minecraft mc = Minecraft.getMinecraft();
@ -71,31 +72,31 @@ public interface Helper {
* @param components The components to send * @param components The components to send
*/ */
default void logDirect(ITextComponent... components) { default void logDirect(ITextComponent... components) {
ITextComponent component = new TextComponentString("") {{ ITextComponent component = new TextComponentString("");
appendSibling(getPrefix()); component.appendSibling(getPrefix());
appendSibling(new TextComponentString(" ")); component.appendSibling(new TextComponentString(" "));
asList(components).forEach(this::appendSibling); asList(components).forEach(component::appendSibling);
}};
Minecraft.getMinecraft().addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component)); 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 message The message to display in chat
* @param color The color to print that message in * @param color The color to print that message in
*/ */
default void logDirect(String message, TextFormatting color) { default void logDirect(String message, TextFormatting color) {
Arrays.stream(message.split("\\n")).forEach(line -> Arrays.stream(message.split("\\n")).forEach(line -> {
logDirect(new TextComponentString(line.replace("\t", " ")) {{ ITextComponent component = new TextComponentString(line.replace("\t", " "));
getStyle().setColor(color); 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 * @param message The message to display in chat
*/ */

View File

@ -48,6 +48,14 @@ public interface IPlayerContext {
// TODO find a better way to deal with soul sand!!!!! // TODO find a better way to deal with soul sand!!!!!
BetterBlockPos feet = new BetterBlockPos(player().posX, player().posY + 0.1251, player().posZ); 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 { try {
if (world().getBlockState(feet).getBlock() instanceof BlockSlab) { if (world().getBlockState(feet).getBlock() instanceof BlockSlab) {
return feet.up(); return feet.up();

View File

@ -20,9 +20,11 @@ package baritone.api.utils;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import java.util.List;
/** /**
* Basic representation of a schematic. Provides the dimensions and * Basic representation of a schematic. Provides the dimensions and the desired statefor a given position relative to
* the desired statefor a given position relative to the origin. * the origin.
* *
* @author leijurv * @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). * 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 x The x position of the block, relative to the origin
* @param y The y 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 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 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 * @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<IBlockState> approxPlaceable);
/** /**
* @return The width (X axis length) of this schematic * @return The width (X axis length) of this schematic

View File

@ -121,6 +121,15 @@ public class SettingsUtil {
return modified; 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<java.lang.String>}, this function returns
* {@code List<String>}.
*
* @param setting The setting
* @return The type
*/
public static String settingTypeToString(Settings.Setting setting) { public static String settingTypeToString(Settings.Setting setting) {
return setting.getType().getTypeName() return setting.getType().getTypeName()
.replaceAll("(?:\\w+\\.)+(\\w+)", "$1"); .replaceAll("(?:\\w+\\.)+(\\w+)", "$1");

View File

@ -20,6 +20,7 @@ package baritone.api.utils.command;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.Settings; import baritone.api.Settings;
import baritone.api.accessor.IGuiScreen;
import baritone.api.event.events.ChatEvent; import baritone.api.event.events.ChatEvent;
import baritone.api.event.events.TabCompleteEvent; import baritone.api.event.events.TabCompleteEvent;
import baritone.api.event.listener.AbstractGameEventListener; 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.helpers.tabcomplete.TabCompleteHelper;
import baritone.api.utils.command.manager.CommandManager; import baritone.api.utils.command.manager.CommandManager;
import com.mojang.realmsclient.util.Pair; import com.mojang.realmsclient.util.Pair;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent; 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.isNull;
import static java.util.Objects.nonNull; import static java.util.Objects.nonNull;
import static java.util.stream.Stream.of;
public class BaritoneChatControl implements Helper, AbstractGameEventListener { public class BaritoneChatControl implements Helper, AbstractGameEventListener {
public final IBaritone baritone; public final IBaritone baritone;
@ -67,10 +68,6 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
String prefix = settings.prefix.value; String prefix = settings.prefix.value;
boolean forceRun = msg.startsWith(FORCE_COMMAND_PREFIX); 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) { if ((settings.prefixControl.value && msg.startsWith(prefix)) || forceRun) {
event.cancel(); event.cancel();
@ -79,11 +76,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
if (!runCommand(commandStr) && !commandStr.trim().isEmpty()) { if (!runCommand(commandStr) && !commandStr.trim().isEmpty()) {
new CommandNotFoundException(CommandExecution.expand(commandStr).first()).handle(null, null); new CommandNotFoundException(CommandExecution.expand(commandStr).first()).handle(null, null);
} }
} else if ((settings.chatControl.value || settings.chatControlAnyway.value) && runCommand(msg)) {
return;
}
if ((settings.chatControl.value || settings.chatControlAnyway.value) && runCommand(msg)) {
event.cancel(); event.cancel();
} }
} }
@ -92,18 +85,20 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
if (settings.echoCommands.value) { if (settings.echoCommands.value) {
String msg = command + rest; String msg = command + rest;
String toDisplay = settings.censorRanCommands.value ? command + " ..." : msg; String toDisplay = settings.censorRanCommands.value ? command + " ..." : msg;
logDirect(new TextComponentString(String.format("> %s", toDisplay)) {{
getStyle() ITextComponent component = new TextComponentString(String.format("> %s", toDisplay));
.setColor(TextFormatting.WHITE) component.getStyle()
.setHoverEvent(new HoverEvent( .setColor(TextFormatting.WHITE)
HoverEvent.Action.SHOW_TEXT, .setHoverEvent(new HoverEvent(
new TextComponentString("Click to rerun command") HoverEvent.Action.SHOW_TEXT,
)) new TextComponentString("Click to rerun command")
.setClickEvent(new ClickEvent( ))
ClickEvent.Action.RUN_COMMAND, .setClickEvent(new ClickEvent(
FORCE_COMMAND_PREFIX + msg ClickEvent.Action.RUN_COMMAND,
)); FORCE_COMMAND_PREFIX + msg
}}); ));
logDirect(component);
} }
} }
@ -113,7 +108,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
return false; return false;
} else if (msg.trim().equalsIgnoreCase("orderpizza")) { } else if (msg.trim().equalsIgnoreCase("orderpizza")) {
try { 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) {} } catch (NullPointerException | URISyntaxException ignored) {}
return false; return false;
@ -129,22 +124,18 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
ArgConsumer argc = new ArgConsumer(pair.second()); ArgConsumer argc = new ArgConsumer(pair.second());
if (!argc.has()) { if (!argc.has()) {
for (Settings.Setting setting : settings.allSettings) { Settings.Setting setting = settings.byLowerName.get(command.toLowerCase(Locale.US));
if (setting.getName().equals("logger")) {
continue; 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)) { return true;
logRanCommand(command, rest);
if (setting.getValueClass() == Boolean.class) {
CommandManager.execute(String.format("set toggle %s", setting.getName()));
} else {
CommandManager.execute(String.format("set %s", setting.getName()));
}
return true;
}
} }
} else if (argc.hasExactlyOne()) { } else if (argc.hasExactlyOne()) {
for (Settings.Setting setting : settings.allSettings) { for (Settings.Setting setting : settings.allSettings) {
@ -217,14 +208,14 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
TabCompleteHelper helper = new TabCompleteHelper(); TabCompleteHelper helper = new TabCompleteHelper();
if ((Boolean) setting.value) { if ((Boolean) setting.value) {
helper.append(of("true", "false")); helper.append(Stream.of("true", "false"));
} else { } else {
helper.append(of("false", "true")); helper.append(Stream.of("false", "true"));
} }
return helper.filterPrefix(argc.getString()).stream(); return helper.filterPrefix(argc.getString()).stream();
} else { } else {
return of(SettingsUtil.settingValueToString(setting)); return Stream.of(SettingsUtil.settingValueToString(setting));
} }
} }
} }

View File

@ -27,8 +27,6 @@ import baritone.api.utils.command.execution.CommandExecution;
import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.arguments.ArgConsumer;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -46,27 +44,20 @@ public abstract class Command implements Helper, AbstractGameEventListener {
*/ */
public final List<String> names; public final List<String> names;
/**
* A <b>single-line</b> string containing a short description of this command's purpose.
*/
public final String shortDesc;
/** /**
* Creates a new Baritone control command. * Creates a new Baritone control command.
* *
* @param names The names of this command. This is what you put after the command prefix. * @param names The names of this command. This is what you put after the command prefix.
* @param shortDesc A <b>single-line</b> string containing a short description of this command's purpose.
*/ */
protected Command(List<String> names, String shortDesc) { protected Command(List<String> names) {
this.names = names.stream() this.names = names.stream()
.map(s -> s.toLowerCase(Locale.US)) .map(s -> s.toLowerCase(Locale.US))
.collect(Collectors.toCollection(ArrayList::new)); .collect(Collectors.toList());
this.shortDesc = shortDesc;
baritone.getGameEventHandler().registerEventListener(this); baritone.getGameEventHandler().registerEventListener(this);
} }
protected Command(String name, String shortDesc) { protected Command(String name) {
this(Collections.singletonList(name), shortDesc); this(Collections.singletonList(name));
} }
/** /**
@ -88,7 +79,7 @@ public abstract class Command implements Helper, AbstractGameEventListener {
try { try {
return tabCompleted(execution.label, execution.args, execution.settings); return tabCompleted(execution.label, execution.args, execution.settings);
} catch (Throwable t) { } 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<String> tabCompleted(String label, ArgConsumer args, Settings settings); protected abstract Stream<String> tabCompleted(String label, ArgConsumer args, Settings settings);
/**
* @return A <b>single-line</b> 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. * @return A list of lines that will be printed by the help command when the user wishes to view them.
*/ */

View File

@ -22,8 +22,6 @@ import baritone.api.utils.command.exception.CommandInvalidTypeException;
import baritone.api.utils.command.exception.CommandNoParserForTypeException; import baritone.api.utils.command.exception.CommandNoParserForTypeException;
import baritone.api.utils.command.registry.Registry; import baritone.api.utils.command.registry.Registry;
import java.util.Iterator;
import static java.util.Objects.isNull; import static java.util.Objects.isNull;
public class ArgParserManager { public class ArgParserManager {
@ -38,16 +36,13 @@ public class ArgParserManager {
* @return A parser that can parse arguments into this class, if found. * @return A parser that can parse arguments into this class, if found.
*/ */
public static <T> ArgParser.Stateless<T> getParserStateless(Class<T> klass) { public static <T> ArgParser.Stateless<T> getParserStateless(Class<T> klass) {
for (Iterator<ArgParser> it = REGISTRY.descendingIterator(); it.hasNext(); ) { //noinspection unchecked
ArgParser<?> parser = it.next(); return REGISTRY.descendingStream()
.filter(ArgParser.Stateless.class::isInstance)
if (parser instanceof ArgParser.Stateless && parser.getKlass().isAssignableFrom(klass)) { .map(ArgParser.Stateless.class::cast)
//noinspection unchecked .filter(parser -> parser.getKlass().isAssignableFrom(klass))
return (ArgParser.Stateless<T>) parser; .findFirst()
} .orElse(null);
}
return null;
} }
/** /**
@ -55,21 +50,27 @@ public class ArgParserManager {
* @return A parser that can parse arguments into this class, if found. * @return A parser that can parse arguments into this class, if found.
*/ */
public static <T, S> ArgParser.Stated<T, S> getParserStated(Class<T> klass, Class<S> stateKlass) { public static <T, S> ArgParser.Stated<T, S> getParserStated(Class<T> klass, Class<S> stateKlass) {
for (Iterator<ArgParser> it = REGISTRY.descendingIterator(); it.hasNext(); ) { //noinspection unchecked
ArgParser<?> parser = it.next(); return REGISTRY.descendingStream()
.filter(ArgParser.Stated.class::isInstance)
//noinspection unchecked .map(ArgParser.Stated.class::cast)
if (parser instanceof ArgParser.Stated .filter(parser -> parser.getKlass().isAssignableFrom(klass))
&& parser.getKlass().isAssignableFrom(klass) .filter(parser -> parser.getStateKlass().isAssignableFrom(stateKlass))
&& ((ArgParser.Stated) parser).getStateKlass().isAssignableFrom(stateKlass)) { .map(ArgParser.Stated.class::cast)
//noinspection unchecked .findFirst()
return (ArgParser.Stated<T, S>) parser; .orElse(null);
}
}
return 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> T parseStateless(Class<T> klass, CommandArgument arg) { public static <T> T parseStateless(Class<T> klass, CommandArgument arg) {
ArgParser.Stateless<T> parser = getParserStateless(klass); ArgParser.Stateless<T> 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, S> T parseStated(Class<T> klass, Class<S> stateKlass, CommandArgument arg, S state) { public static <T, S> T parseStated(Class<T> klass, Class<S> stateKlass, CommandArgument arg, S state) {
ArgParser.Stated<T, S> parser = getParserStated(klass, stateKlass); ArgParser.Stated<T, S> parser = getParserStated(klass, stateKlass);

View File

@ -19,7 +19,6 @@ package baritone.api.utils.command.argparser;
import baritone.api.utils.command.argument.CommandArgument; import baritone.api.utils.command.argument.CommandArgument;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -114,11 +113,11 @@ public class DefaultArgParsers {
} }
} }
public static final List<ArgParser<?>> all = Collections.unmodifiableList(asList( public static final List<ArgParser<?>> all = asList(
IntArgumentParser.INSTANCE, IntArgumentParser.INSTANCE,
LongArgumentParser.INSTANCE, LongArgumentParser.INSTANCE,
FloatArgumentParser.INSTANCE, FloatArgumentParser.INSTANCE,
DoubleArgumentParser.INSTANCE, DoubleArgumentParser.INSTANCE,
BooleanArgumentParser.INSTANCE BooleanArgumentParser.INSTANCE
)); );
} }

View File

@ -25,6 +25,11 @@ public interface IArgParser<T> {
*/ */
Class<T> getKlass(); Class<T> getKlass();
/**
* A stateless argument parser is just that. It takes a {@link CommandArgument} and outputs its type.
*
* @see ArgParserManager#REGISTRY
*/
interface Stateless<T> extends IArgParser<T> { interface Stateless<T> extends IArgParser<T> {
/** /**
* @param arg The argument to parse. * @param arg The argument to parse.
@ -35,6 +40,12 @@ public interface IArgParser<T> {
T parseArg(CommandArgument arg) throws RuntimeException; 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<T, S> extends IArgParser<T> { interface Stated<T, S> extends IArgParser<T> {
Class<S> getStateKlass(); Class<S> getStateKlass();

View File

@ -17,16 +17,27 @@
package baritone.api.utils.command.argument; package baritone.api.utils.command.argument;
import baritone.api.utils.command.argparser.ArgParser;
import baritone.api.utils.command.argparser.ArgParserManager; import baritone.api.utils.command.argparser.ArgParserManager;
import baritone.api.utils.command.exception.CommandInvalidArgumentException;
import baritone.api.utils.command.exception.CommandInvalidTypeException; 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.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.NoSuchElementException;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; 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
* <p>
* You're recommended to use {@link ArgConsumer}s to handle these. Check out {@link ArgConsumer#from(String)}
*/
public class CommandArgument { public class CommandArgument {
public final int index; public final int index;
public final String value; public final String value;
@ -39,18 +50,54 @@ public class CommandArgument {
this.rawRest = rawRest; this.rawRest = rawRest;
} }
/**
* Gets an enum value from the enum class with the same name as this argument's value
* <p>
* 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 extends Enum<?>> E getEnum(Class<E> enumClass) { public <E extends Enum<?>> E getEnum(Class<E> enumClass) {
//noinspection OptionalGetWithoutIsPresent try {
return Arrays.stream(enumClass.getEnumConstants()) //noinspection OptionalGetWithoutIsPresent
.filter(e -> e.name().equalsIgnoreCase(value)) return Arrays.stream(enumClass.getEnumConstants())
.findFirst() .filter(e -> e.name().equalsIgnoreCase(value))
.get(); .findFirst()
.get();
} catch (NoSuchElementException e) {
throw new CommandInvalidTypeException(this, enumClass.getSimpleName());
}
} }
/**
* Tries to use a <b>stateless</b> {@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> T getAs(Class<T> type) { public <T> T getAs(Class<T> type) {
return ArgParserManager.parseStateless(type, this); return ArgParserManager.parseStateless(type, this);
} }
/**
* Tries to use a <b>stateless</b> {@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 <T> boolean is(Class<T> type) { public <T> boolean is(Class<T> type) {
try { try {
getAs(type); getAs(type);
@ -60,10 +107,27 @@ public class CommandArgument {
} }
} }
/**
* Tries to use a <b>stated</b> {@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, S> T getAs(Class<T> type, Class<S> stateType, S state) { public <T, S> T getAs(Class<T> type, Class<S> stateType, S state) {
return ArgParserManager.parseStated(type, stateType, this, state); return ArgParserManager.parseStated(type, stateType, this, state);
} }
/**
* Tries to use a <b>stated</b> {@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 <T, S> boolean is(Class<T> type, Class<S> stateType, S state) { public <T, S> boolean is(Class<T> type, Class<S> stateType, S state) {
try { try {
getAs(type, stateType, state); 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<CommandArgument> from(String string, boolean preserveEmptyLast) { public static List<CommandArgument> from(String string, boolean preserveEmptyLast) {
List<CommandArgument> args = new ArrayList<>(); List<CommandArgument> args = new ArrayList<>();
Matcher argMatcher = argPattern.matcher(string); Matcher argMatcher = argPattern.matcher(string);
@ -94,10 +166,19 @@ public class CommandArgument {
return args; return args;
} }
/**
* @see #from(String, boolean)
*/
public static List<CommandArgument> from(String string) { public static List<CommandArgument> from(String string) {
return from(string, false); 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() { public static CommandArgument unknown() {
return new CommandArgument(-1, "<unknown>", ""); return new CommandArgument(-1, "<unknown>", "");
} }

View File

@ -36,7 +36,7 @@ public class BlockById implements IDatatypeFor<Block> {
ResourceLocation id = new ResourceLocation(consumer.getString()); ResourceLocation id = new ResourceLocation(consumer.getString());
if ((block = Block.REGISTRY.getObject(id)) == Blocks.AIR) { 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");
} }
} }

View File

@ -38,7 +38,7 @@ public class EntityClassById implements IDatatypeFor<Class<? extends Entity>> {
ResourceLocation id = new ResourceLocation(consumer.getString()); ResourceLocation id = new ResourceLocation(consumer.getString());
if (isNull(entity = EntityList.REGISTRY.getObject(id))) { 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");
} }
} }

View File

@ -29,8 +29,6 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
import static java.util.Arrays.asList;
public class ForWaypoints implements IDatatypeFor<IWaypoint[]> { public class ForWaypoints implements IDatatypeFor<IWaypoint[]> {
private final IWaypoint[] waypoints; private final IWaypoint[] waypoints;
@ -39,7 +37,7 @@ public class ForWaypoints implements IDatatypeFor<IWaypoint[]> {
} }
public ForWaypoints(String arg) { public ForWaypoints(String arg) {
IWaypoint.Tag tag = getTagByName(arg); IWaypoint.Tag tag = IWaypoint.Tag.getByName(arg);
waypoints = tag == null ? getWaypointsByName(arg) : getWaypointsByTag(tag); waypoints = tag == null ? getWaypointsByName(arg) : getWaypointsByTag(tag);
} }
@ -57,7 +55,7 @@ public class ForWaypoints implements IDatatypeFor<IWaypoint[]> {
return new TabCompleteHelper() return new TabCompleteHelper()
.append(getWaypointNames()) .append(getWaypointNames())
.sortAlphabetically() .sortAlphabetically()
.prepend(getTagNames()) .prepend(IWaypoint.Tag.getAllNames())
.filterPrefix(consumer.getString()) .filterPrefix(consumer.getString())
.stream(); .stream();
} }
@ -70,28 +68,6 @@ public class ForWaypoints implements IDatatypeFor<IWaypoint[]> {
.getWaypoints(); .getWaypoints();
} }
public static String[] getTagNames() {
Set<String> 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() { public static IWaypoint[] getWaypoints() {
return waypoints().getAllWaypoints().stream() return waypoints().getAllWaypoints().stream()
.sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed()) .sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed())

View File

@ -17,6 +17,7 @@
package baritone.api.utils.command.datatypes; 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.exception.CommandInvalidArgumentException;
import baritone.api.utils.command.helpers.arguments.ArgConsumer; 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 * 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 * accepts a single {@link ArgConsumer} argument. The constructor will perform all needed validation, and {@link
* {@link ArgConsumer#getDatatype(Class)} will handle RuntimeExceptions and translate them into * ArgConsumer#getDatatype(Class)} will handle RuntimeExceptions and translate them into {@link
* {@link CommandInvalidArgumentException}s. There must always be a constructor with no arguments so that * CommandInvalidArgumentException}s. There must always be a constructor with no arguments so that {@link ArgConsumer}
* {@link ArgConsumer} can create an instance for tab completion. * can create an instance for tab completion.
*/ */
public interface IDatatype { 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.
* <p>
* 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<String> tabComplete(ArgConsumer consumer); Stream<String> tabComplete(ArgConsumer consumer);
} }

View File

@ -46,7 +46,7 @@ public class PlayerByUsername implements IDatatypeFor<EntityPlayer> {
.findFirst() .findFirst()
.orElse(null) .orElse(null)
)) { )) {
throw new RuntimeException("no player found by that username"); throw new IllegalArgumentException("no player found by that username");
} }
} }

View File

@ -36,14 +36,10 @@ public class RelativeCoordinate implements IDatatypePost<Double, Double> {
} }
public RelativeCoordinate(ArgConsumer consumer) { public RelativeCoordinate(ArgConsumer consumer) {
if (!consumer.has()) {
throw new RuntimeException("relative coordinate requires an argument");
}
Matcher matcher = PATTERN.matcher(consumer.getString()); Matcher matcher = PATTERN.matcher(consumer.getString());
if (!matcher.matches()) { if (!matcher.matches()) {
throw new RuntimeException("pattern doesn't match"); throw new IllegalArgumentException("pattern doesn't match");
} }
isRelative = !matcher.group(1).isEmpty(); isRelative = !matcher.group(1).isEmpty();

View File

@ -42,7 +42,7 @@ public class RelativeFile implements IDatatypePost<File, File> {
try { try {
path = FileSystems.getDefault().getPath(consumer.getString()); path = FileSystems.getDefault().getPath(consumer.getString());
} catch (InvalidPathException e) { } catch (InvalidPathException e) {
throw new RuntimeException("invalid path"); throw new IllegalArgumentException("invalid path");
} }
} }

View File

@ -17,7 +17,6 @@
package baritone.api.utils.command.datatypes; package baritone.api.utils.command.datatypes;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalBlock;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.arguments.ArgConsumer;

View File

@ -19,7 +19,6 @@ package baritone.api.utils.command.exception;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -35,7 +34,7 @@ public class CommandUnhandledException extends CommandErrorMessageException {
public static String getBaritoneStackTrace(String stackTrace) { public static String getBaritoneStackTrace(String stackTrace) {
List<String> lines = Arrays.stream(stackTrace.split("\n")) List<String> lines = Arrays.stream(stackTrace.split("\n"))
.collect(Collectors.toCollection(ArrayList::new)); .collect(Collectors.toList());
int lastBaritoneLine = 0; int lastBaritoneLine = 0;
for (int i = 0; i < lines.size(); i++) { for (int i = 0; i < lines.size(); i++) {

View File

@ -79,45 +79,45 @@ public class Paginator<E> implements Helper {
boolean hasPrevPage = nonNull(commandPrefix) && validPage(page - 1); boolean hasPrevPage = nonNull(commandPrefix) && validPage(page - 1);
boolean hasNextPage = nonNull(commandPrefix) && validPage(page + 1); boolean hasNextPage = nonNull(commandPrefix) && validPage(page + 1);
logDirect(new TextComponentString("") {{ ITextComponent prevPageComponent = new TextComponentString("<<");
getStyle().setColor(TextFormatting.GRAY);
appendSibling(new TextComponentString("<<") {{ if (hasPrevPage) {
if (hasPrevPage) { prevPageComponent.getStyle()
getStyle() .setClickEvent(new ClickEvent(
.setClickEvent(new ClickEvent( ClickEvent.Action.RUN_COMMAND,
ClickEvent.Action.RUN_COMMAND, String.format("%s %d", commandPrefix, page - 1)
String.format("%s %d", commandPrefix, page - 1) ))
)) .setHoverEvent(new HoverEvent(
.setHoverEvent(new HoverEvent( HoverEvent.Action.SHOW_TEXT,
HoverEvent.Action.SHOW_TEXT, new TextComponentString("Click to view previous page")
new TextComponentString("Click to view previous page") ));
)); } else {
} else { prevPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
getStyle().setColor(TextFormatting.DARK_GRAY); }
}
}});
appendText(" | "); ITextComponent nextPageComponent = new TextComponentString(">>");
appendSibling(new TextComponentString(">>") {{ if (hasNextPage) {
if (hasNextPage) { nextPageComponent.getStyle()
getStyle() .setClickEvent(new ClickEvent(
.setClickEvent(new ClickEvent( ClickEvent.Action.RUN_COMMAND,
ClickEvent.Action.RUN_COMMAND, String.format("%s %d", commandPrefix, page + 1)
commandPrefix + " " + (page + 1) ))
)) .setHoverEvent(new HoverEvent(
.setHoverEvent(new HoverEvent( HoverEvent.Action.SHOW_TEXT,
HoverEvent.Action.SHOW_TEXT, new TextComponentString("Click to view next page")
new TextComponentString("Click to view next page") ));
)); } else {
} else { nextPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
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<E, ITextComponent> transform) { public void display(Function<E, ITextComponent> transform) {

View File

@ -19,7 +19,10 @@ package baritone.api.utils.command.helpers.tabcomplete;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.Settings; import baritone.api.Settings;
import baritone.api.event.events.TabCompleteEvent;
import baritone.api.utils.SettingsUtil; import baritone.api.utils.SettingsUtil;
import baritone.api.utils.command.execution.CommandExecution;
import baritone.api.utils.command.helpers.arguments.ArgConsumer;
import baritone.api.utils.command.manager.CommandManager; import baritone.api.utils.command.manager.CommandManager;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
@ -31,9 +34,24 @@ import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Stream; import java.util.stream.Stream;
import static java.util.stream.Stream.concat; /**
import static java.util.stream.Stream.of; * The {@link TabCompleteHelper} is a <b>single-use</b> object that helps you handle tab completion. It includes helper
* methods for appending and prepending streams, sorting, filtering by prefix, and so on.
* <p>
* The recommended way to use this class is:
* <ul>
* <li>Create a new instance with the empty constructor</li>
* <li>Use {@code append}, {@code prepend} or {@code add<something>} methods to add completions</li>
* <li>Sort using {@link #sort(Comparator)} or {@link #sortAlphabetically()} and then filter by prefix using
* {@link #filterPrefix(String)}</li>
* <li>Get the stream using {@link #stream()}</li>
* <li>Pass it up to whatever's calling your tab complete function (i.e.
* {@link CommandManager#tabComplete(CommandExecution)} or {@link ArgConsumer#tabCompleteDatatype(Class)})</li>
* </ul>
* <p>
* For advanced users: if you're intercepting {@link TabCompleteEvent}s directly, use {@link #build()} instead for an
* array.
*/
public class TabCompleteHelper { public class TabCompleteHelper {
private Stream<String> stream; private Stream<String> stream;
@ -49,16 +67,49 @@ public class TabCompleteHelper {
this(new String[0]); 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<String> source) { public TabCompleteHelper append(Stream<String> source) {
stream = concat(stream, source); stream = Stream.concat(stream, source);
return this; 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) { 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<? extends Enum<?>> num) { public TabCompleteHelper append(Class<? extends Enum<?>> num) {
return append( return append(
Arrays.stream(num.getEnumConstants()) 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<String> source) { public TabCompleteHelper prepend(Stream<String> source) {
stream = concat(source, stream); stream = Stream.concat(source, stream);
return this; 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) { 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<? extends Enum<?>> num) { public TabCompleteHelper prepend(Class<? extends Enum<?>> num) {
return prepend( return prepend(
Arrays.stream(num.getEnumConstants()) Arrays.stream(num.getEnumConstants())
@ -85,44 +169,98 @@ public class TabCompleteHelper {
); );
} }
/**
* Apply the specified {@code transform} to every element <b>currently</b> in this {@link TabCompleteHelper} and
* return this object for chaining
*
* @param transform The transform to apply
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper map(Function<String, String> transform) { public TabCompleteHelper map(Function<String, String> transform) {
stream = stream.map(transform); stream = stream.map(transform);
return this; return this;
} }
/**
* Apply the specified {@code filter} to every element <b>currently</b> in this {@link TabCompleteHelper} and return
* this object for chaining
*
* @param filter The filter to apply
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper filter(Predicate<String> filter) { public TabCompleteHelper filter(Predicate<String> filter) {
stream = stream.filter(filter); stream = stream.filter(filter);
return this; return this;
} }
/**
* Apply the specified {@code sort} to every element <b>currently</b> in this {@link TabCompleteHelper} and return
* this object for chaining
*
* @param comparator The comparator to use
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper sort(Comparator<String> comparator) { public TabCompleteHelper sort(Comparator<String> comparator) {
stream = stream.sorted(comparator); stream = stream.sorted(comparator);
return this; return this;
} }
/**
* Sort every element <b>currently</b> in this {@link TabCompleteHelper} alphabetically and return this object for
* chaining
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper sortAlphabetically() { public TabCompleteHelper sortAlphabetically() {
return sort(String.CASE_INSENSITIVE_ORDER); 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) { public TabCompleteHelper filterPrefix(String prefix) {
return filter(x -> x.toLowerCase(Locale.US).startsWith(prefix.toLowerCase(Locale.US))); 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
* <p>
* 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) { public TabCompleteHelper filterPrefixNamespaced(String prefix) {
return filterPrefix(new ResourceLocation(prefix).toString()); return filterPrefix(new ResourceLocation(prefix).toString());
} }
/**
* @return An array containing every element in this {@link TabCompleteHelper}
* @see #stream()
*/
public String[] build() { public String[] build() {
return stream.toArray(String[]::new); return stream.toArray(String[]::new);
} }
/**
* @return A stream containing every element in this {@link TabCompleteHelper}
* @see #build()
*/
public Stream<String> stream() { public Stream<String> stream() {
return stream; return stream;
} }
/**
* Appends every command in the {@link CommandManager#REGISTRY} to this {@link TabCompleteHelper}
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper addCommands() { public TabCompleteHelper addCommands() {
return append( return append(
CommandManager.REGISTRY.descendingStream() 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() { public TabCompleteHelper addSettings() {
return append( return append(
BaritoneAPI.getSettings().allSettings.stream() 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() { public TabCompleteHelper addModifiedSettings() {
return append( return append(
SettingsUtil.modifiedSettings(BaritoneAPI.getSettings()).stream() 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() { public TabCompleteHelper addToggleableSettings() {
return append( return append(
BaritoneAPI.getSettings().getAllValuesByType(Boolean.class).stream() BaritoneAPI.getSettings().getAllValuesByType(Boolean.class).stream()

View File

@ -20,10 +20,10 @@ package baritone.api.utils.command.registry;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Deque; import java.util.Deque;
import java.util.HashMap; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.Map; import java.util.Set;
import java.util.Spliterator; import java.util.Spliterator;
import java.util.Spliterators; import java.util.Spliterators;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -50,11 +50,11 @@ public class Registry<V> {
private final Deque<V> _entries = new LinkedList<>(); private final Deque<V> _entries = new LinkedList<>();
/** /**
* A HashMap containing keys for every entry currently registered. Map entries are added to this map when something * A HashSet containing every entry currently registered. Entries are added to this set when something is registered
* is registered and removed from the map when they are unregistered. An entry simply being present in this map * and removed from the set when they are unregistered. An entry being present in this set indicates that it is
* indicates that it is currently registered and therefore can be removed and should not be reregistered. * currently registered, can be removed, and should not be reregistered until it is removed.
*/ */
private final Map<V, Boolean> registered = new HashMap<>(); private final Set<V> registered = new HashSet<>();
/** /**
* The collection of entries that are currently in this registry. This is a collection (and not a list) because, * 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<V> {
* @return If this entry is currently registered in this registry. * @return If this entry is currently registered in this registry.
*/ */
public boolean registered(V entry) { public boolean registered(V entry) {
return registered.containsKey(entry); return registered.contains(entry);
} }
/** /**
@ -81,7 +81,7 @@ public class Registry<V> {
public boolean register(V entry) { public boolean register(V entry) {
if (!registered(entry)) { if (!registered(entry)) {
_entries.addFirst(entry); _entries.addFirst(entry);
registered.put(entry, true); registered.add(entry);
return true; return true;
} }

View File

@ -25,13 +25,22 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(GuiChat.ChatTabCompleter.class) @Mixin(GuiChat.ChatTabCompleter.class)
public abstract class MixinChatTabCompleter extends MixinTabCompleter { public abstract class MixinChatTabCompleter extends MixinTabCompleter {
@Inject(method = "<init>*", at = @At("RETURN")) @Inject(
method = "<init>*",
at = @At("RETURN")
)
private void onConstruction(CallbackInfo ci) { private void onConstruction(CallbackInfo ci) {
isChatCompleter = true; isChatCompleter = true;
} }
@Inject(method = "complete", at = @At("HEAD"), cancellable = true) @Inject(
method = "complete",
at = @At("HEAD"),
cancellable = true
)
private void onComplete(CallbackInfo ci) { private void onComplete(CallbackInfo ci) {
if (dontComplete) ci.cancel(); if (dontComplete) {
ci.cancel();
}
} }
} }

View File

@ -31,7 +31,11 @@ public abstract class MixinGuiChat implements net.minecraft.util.ITabCompleter {
@Shadow @Shadow
private TabCompleter tabCompleter; 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) { private void onSetCompletions(String[] newCompl, CallbackInfo ci) {
if (((ITabCompleter) tabCompleter).onGuiChatSetCompletions(newCompl)) { if (((ITabCompleter) tabCompleter).onGuiChatSetCompletions(newCompl)) {
ci.cancel(); ci.cancel();

View File

@ -17,7 +17,7 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.api.utils.command.Lol; import baritone.api.accessor.IGuiScreen;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.gen.Invoker;
@ -25,7 +25,7 @@ import org.spongepowered.asm.mixin.gen.Invoker;
import java.net.URI; import java.net.URI;
@Mixin(GuiScreen.class) @Mixin(GuiScreen.class)
public abstract class MixinGuiScreen implements Lol { public abstract class MixinGuiScreen implements IGuiScreen {
@Override @Override
@Invoker("openWebLink") @Invoker("openWebLink")
public abstract void openLink(URI url); public abstract void openLink(URI url);

View File

@ -44,12 +44,18 @@ public abstract class MixinItemStack implements IItemStack {
baritoneHash = item == null ? -1 : item.hashCode() + itemDamage; baritoneHash = item == null ? -1 : item.hashCode() + itemDamage;
} }
@Inject(method = "<init>*", at = @At("RETURN")) @Inject(
method = "<init>*",
at = @At("RETURN")
)
private void onInit(CallbackInfo ci) { private void onInit(CallbackInfo ci) {
recalculateHash(); recalculateHash();
} }
@Inject(method = "setItemDamage", at = @At("TAIL")) @Inject(
method = "setItemDamage",
at = @At("TAIL")
)
private void onItemDamageSet(CallbackInfo ci) { private void onItemDamageSet(CallbackInfo ci) {
recalculateHash(); recalculateHash();
} }

View File

@ -40,7 +40,10 @@ public abstract class MixinStateImplementation {
@Unique @Unique
private int hashCode; private int hashCode;
@Inject(method = "<init>*", at = @At("RETURN")) @Inject(
method = "<init>*",
at = @At("RETURN")
)
private void onInit(CallbackInfo ci) { private void onInit(CallbackInfo ci) {
hashCode = properties.hashCode(); hashCode = properties.hashCode();
} }

View File

@ -63,17 +63,17 @@ public abstract class MixinTabCompleter implements ITabCompleter {
textField.setCursorPosition(prefix.length()); 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) { private void onRequestCompletions(String prefix, CallbackInfo ci) {
if (!isChatCompleter) { if (!isChatCompleter) {
return; return;
} }
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(Minecraft.getMinecraft().player); IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone();
if (isNull(baritone)) {
return;
}
TabCompleteEvent.Pre event = new TabCompleteEvent.Pre(prefix); TabCompleteEvent.Pre event = new TabCompleteEvent.Pre(prefix);
baritone.getGameEventHandler().onPreTabComplete(event); baritone.getGameEventHandler().onPreTabComplete(event);

View File

@ -113,9 +113,6 @@ public class Baritone implements IBaritone {
memoryBehavior = new MemoryBehavior(this); memoryBehavior = new MemoryBehavior(this);
inventoryBehavior = new InventoryBehavior(this); inventoryBehavior = new InventoryBehavior(this);
inputOverrideHandler = new InputOverrideHandler(this); inputOverrideHandler = new InputOverrideHandler(this);
DefaultCommands.commands.forEach(CommandManager.REGISTRY::register);
new BaritoneChatControl(this);
} }
this.pathingControlManager = new PathingControlManager(this); this.pathingControlManager = new PathingControlManager(this);
@ -138,6 +135,9 @@ public class Baritone implements IBaritone {
} }
this.initialized = true; this.initialized = true;
DefaultCommands.COMMANDS.forEach(CommandManager.REGISTRY::register);
new BaritoneChatControl(this);
} }
@Override @Override

View File

@ -133,7 +133,7 @@ public final class InventoryBehavior extends Behavior {
} }
public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) { public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) {
IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, 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())))) { 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 return true; // gotem
} }

View File

@ -291,11 +291,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
return hasPath() && !pausedThisTick; return hasPath() && !pausedThisTick;
} }
@Override
public boolean hasPath() {
return current != null;
}
@Override @Override
public PathExecutor getCurrent() { public PathExecutor getCurrent() {
return current; return current;

View File

@ -17,7 +17,9 @@
package baritone.cache; package baritone.cache;
import baritone.api.cache.ICachedWorld;
import baritone.api.cache.IWorldScanner; import baritone.api.cache.IWorldScanner;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.BlockOptionalMetaLookup;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import baritone.utils.accessor.IBlockStateContainer; 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.BlockPos;
import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import java.util.ArrayList; import java.util.ArrayList;
@ -35,6 +38,8 @@ import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import static java.util.Objects.nonNull;
public enum WorldScanner implements IWorldScanner { public enum WorldScanner implements IWorldScanner {
INSTANCE; INSTANCE;
@ -44,6 +49,11 @@ public enum WorldScanner implements IWorldScanner {
@Override @Override
public List<BlockPos> scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLookup filter, int max, int yLevelThreshold, int maxSearchRadius) { public List<BlockPos> scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLookup filter, int max, int yLevelThreshold, int maxSearchRadius) {
ArrayList<BlockPos> res = new ArrayList<>(); ArrayList<BlockPos> res = new ArrayList<>();
if (filter.blocks().isEmpty()) {
return res;
}
ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider();
int maxSearchRadiusSq = maxSearchRadius * maxSearchRadius; int maxSearchRadiusSq = maxSearchRadius * maxSearchRadius;
@ -79,8 +89,8 @@ public enum WorldScanner implements IWorldScanner {
} }
} }
if ((allUnloaded && foundChunks) if ((allUnloaded && foundChunks)
|| (res.size() >= max || (res.size() >= max
&& (searchRadiusSq > maxSearchRadiusSq || (searchRadiusSq > 1 && foundWithinY))) && (searchRadiusSq > maxSearchRadiusSq || (searchRadiusSq > 1 && foundWithinY)))
) { ) {
return res; return res;
} }
@ -90,6 +100,10 @@ public enum WorldScanner implements IWorldScanner {
@Override @Override
public List<BlockPos> scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold) { public List<BlockPos> scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold) {
if (filter.blocks().isEmpty()) {
return Collections.emptyList();
}
ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider();
Chunk chunk = chunkProvider.getLoadedChunk(pos.x, pos.z); Chunk chunk = chunkProvider.getLoadedChunk(pos.x, pos.z);
int playerY = ctx.playerFeet().getY(); int playerY = ctx.playerFeet().getY();
@ -121,7 +135,7 @@ public enum WorldScanner implements IWorldScanner {
for (int i = 0; i < imax; i++) { for (int i = 0; i < imax; i++) {
IBlockState state = bsc.getAtPalette(storage[i]); IBlockState state = bsc.getAtPalette(storage[i]);
if (filter.has(state)) { if (filter.has(state)) {
int y = yReal | (i >> 8 & 15); int y = yReal | ((i >> 8) & 15);
if (result.size() >= max) { if (result.size() >= max) {
if (Math.abs(y - playerY) < yLevelThreshold) { if (Math.abs(y - playerY) < yLevelThreshold) {
foundWithinY = true; 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; 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;
}
} }

View File

@ -177,7 +177,7 @@ public interface MovementHelper extends ActionCosts, Helper {
return block.isPassable(null, null); 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 // for MovementTraverse and MovementAscend
// block double plant defaults to true when the block doesn't match, so don't need to check that case // 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 // all other overrides just return true or false
@ -207,6 +207,11 @@ public interface MovementHelper extends ActionCosts, Helper {
return state.getMaterial().isReplaceable(); 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) { static boolean isDoorPassable(IPlayerContext ctx, BlockPos doorPos, BlockPos playerPos) {
if (playerPos.equals(doorPos)) { if (playerPos.equals(doorPos)) {
return false; return false;

View File

@ -73,7 +73,7 @@ public class MovementAscend extends Movement {
if (additionalPlacementCost >= COST_INF) { if (additionalPlacementCost >= COST_INF) {
return 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; return COST_INF;
} }
boolean foundPlaceOption = false; boolean foundPlaceOption = false;

View File

@ -152,7 +152,7 @@ public class MovementParkour extends Movement {
return; return;
} }
IBlockState toReplace = context.get(destX, y - 1, destZ); 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; return;
} }
if (!checkOvershootSafety(context.bsi, destX + xDiff, y, destZ + zDiff)) { if (!checkOvershootSafety(context.bsi, destX + xDiff, y, destZ + zDiff)) {

View File

@ -111,7 +111,7 @@ public class MovementTraverse extends Movement {
if (srcDown == Blocks.LADDER || srcDown == Blocks.VINE) { if (srcDown == Blocks.LADDER || srcDown == Blocks.VINE) {
return COST_INF; 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()); boolean throughWater = MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock());
if (MovementHelper.isWater(destOn.getBlock()) && throughWater) { 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 // this happens when assume walk on water is true and this is a traverse in water, which isn't allowed

View File

@ -79,6 +79,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
private int ticks; private int ticks;
private boolean paused; private boolean paused;
private int layer; private int layer;
private List<IBlockState> approxPlaceable;
public BuilderProcess(Baritone baritone) { public BuilderProcess(Baritone baritone) {
super(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); build("clear area", new FillSchematic(widthX, heightY, lengthZ, Blocks.AIR.getDefaultState()), origin);
} }
@Override
public List<IBlockState> getApproxPlaceable() {
return new ArrayList<>(approxPlaceable);
}
private static ISchematic parse(NBTTagCompound schematic) { private static ISchematic parse(NBTTagCompound schematic) {
return Baritone.settings().mapArtMode.value ? new MapArtSchematic(schematic) : new Schematic(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)) { if (!schematic.inSchematic(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current)) {
return null; 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) { if (state.getBlock() == Blocks.AIR) {
return null; return null;
} }
@ -214,7 +220,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
} }
private Optional<Placement> searchForPlacables(BuilderCalculationContext bcc, List<IBlockState> desirableOnHotbar) { private Optional<Placement> searchForPlaceables(BuilderCalculationContext bcc, List<IBlockState> desirableOnHotbar) {
BetterBlockPos center = ctx.playerFeet(); BetterBlockPos center = ctx.playerFeet();
for (int dx = -5; dx <= 5; dx++) { for (int dx = -5; dx <= 5; dx++) {
for (int dy = -5; dy <= 1; dy++) { for (int dy = -5; dy <= 1; dy++) {
@ -227,7 +233,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
continue; // irrelevant continue; // irrelevant
} }
IBlockState curr = bcc.bsi.get0(x, y, z); 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) { if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() == Blocks.AIR) {
continue; continue;
} }
@ -247,7 +253,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
for (EnumFacing against : EnumFacing.values()) { for (EnumFacing against : EnumFacing.values()) {
BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against); BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against);
IBlockState placeAgainstState = bsi.get0(placeAgainstPos); 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; continue;
} }
if (!ctx.world().mayPlace(toPlace.getBlock(), new BetterBlockPos(x, y, z), false, against, null)) { 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) { private static Vec3d[] aabbSideMultipliers(EnumFacing side) {
switch (side) { switch (side) {
case UP: 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: 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 NORTH:
case SOUTH: case SOUTH:
case EAST: case EAST:
case WEST: case WEST:
double x = side.getXOffset() == 0 ? 0.5 : (1 + side.getXOffset()) / 2D; double x = side.getXOffset() == 0 ? 0.5 : (1 + side.getXOffset()) / 2D;
double z = side.getZOffset() == 0 ? 0.5 : (1 + side.getZOffset()) / 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 default: // null
throw new IllegalStateException(); throw new IllegalStateException();
} }
@ -321,6 +327,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
@Override @Override
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
approxPlaceable = approxPlaceable(36);
if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) { if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) {
ticks = 5; ticks = 5;
} else { } else {
@ -348,8 +355,8 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
schematic = new ISchematic() { schematic = new ISchematic() {
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
return realSchematic.desiredState(x, y, z, current); return realSchematic.desiredState(x, y, z, current, BuilderProcess.this.approxPlaceable);
} }
@Override @Override
@ -416,7 +423,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
} }
List<IBlockState> desirableOnHotbar = new ArrayList<>(); List<IBlockState> desirableOnHotbar = new ArrayList<>();
Optional<Placement> toPlace = searchForPlacables(bcc, desirableOnHotbar); Optional<Placement> toPlace = searchForPlaceables(bcc, desirableOnHotbar);
if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) { if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) {
Rotation rot = toPlace.get().rot; Rotation rot = toPlace.get().rot;
baritone.getLookBehavior().updateTarget(rot, true); 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); return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
} }
List<IBlockState> approxPlacable = placable(36);
if (Baritone.settings().allowInventory.value) { if (Baritone.settings().allowInventory.value) {
ArrayList<Integer> usefulSlots = new ArrayList<>(); ArrayList<Integer> usefulSlots = new ArrayList<>();
List<IBlockState> noValidHotbarOption = new ArrayList<>(); List<IBlockState> noValidHotbarOption = new ArrayList<>();
outer: outer:
for (IBlockState desired : desirableOnHotbar) { for (IBlockState desired : desirableOnHotbar) {
for (int i = 0; i < 9; i++) { for (int i = 0; i < 9; i++) {
if (valid(approxPlacable.get(i), desired)) { if (valid(approxPlaceable.get(i), desired)) {
usefulSlots.add(i); usefulSlots.add(i);
continue outer; continue outer;
} }
@ -446,7 +452,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
outer: outer:
for (int i = 9; i < 36; i++) { for (int i = 9; i < 36; i++) {
for (IBlockState desired : noValidHotbarOption) { for (IBlockState desired : noValidHotbarOption) {
if (valid(approxPlacable.get(i), desired)) { if (valid(approxPlaceable.get(i), desired)) {
baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains); baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains);
break outer; 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) { 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) { if (goal == null) {
logDirect("Unable to do it. Pausing. resume to resume, cancel to cancel"); logDirect("Unable to do it. Pausing. resume to resume, cancel to cancel");
paused = true; 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 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 // 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)); observedCompleted.add(BetterBlockPos.longHash(blockX, blockY, blockZ));
} else { } else {
incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ)); 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<IBlockState> approxPlacable) { private Goal assemble(BuilderCalculationContext bcc, List<IBlockState> approxPlaceable) {
List<BetterBlockPos> placeable = new ArrayList<>(); List<BetterBlockPos> placeable = new ArrayList<>();
List<BetterBlockPos> breakable = new ArrayList<>(); List<BetterBlockPos> breakable = new ArrayList<>();
List<BetterBlockPos> sourceLiquids = new ArrayList<>(); List<BetterBlockPos> sourceLiquids = new ArrayList<>();
incorrectPositions.forEach(pos -> { incorrectPositions.forEach(pos -> {
IBlockState state = bcc.bsi.get0(pos); IBlockState state = bcc.bsi.get0(pos);
if (state.getBlock() instanceof BlockAir) { 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); placeable.add(pos);
} }
} else { } 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? if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) { // TODO can this even happen?
return new GoalPlace(pos); return new GoalPlace(pos);
} }
IBlockState current = ctx.world().getBlockState(pos.up()); boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR;
boolean allowSameLevel = current.getBlock() != Blocks.AIR; IBlockState current = ctx.world().getBlockState(pos);
for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) { for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) {
//noinspection ConstantConditions //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)) { 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; return paused ? "Builder Paused" : "Building " + name;
} }
private List<IBlockState> placable(int size) { private List<IBlockState> approxPlaceable(int size) {
List<IBlockState> result = new ArrayList<>(); List<IBlockState> result = new ArrayList<>();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
ItemStack stack = ctx.player().inventory.mainInventory.get(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 { public class BuilderCalculationContext extends CalculationContext {
private final List<IBlockState> placable; private final List<IBlockState> placeable;
private final ISchematic schematic; private final ISchematic schematic;
private final int originX; private final int originX;
private final int originY; private final int originY;
@ -759,7 +765,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
public BuilderCalculationContext() { public BuilderCalculationContext() {
super(BuilderProcess.this.baritone, true); // wew lad super(BuilderProcess.this.baritone, true); // wew lad
this.placable = placable(9); this.placeable = approxPlaceable(9);
this.schematic = BuilderProcess.this.schematic; this.schematic = BuilderProcess.this.schematic;
this.originX = origin.getX(); this.originX = origin.getX();
this.originY = origin.getY(); 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) { private IBlockState getSchematic(int x, int y, int z, IBlockState current) {
if (schematic.inSchematic(x - originX, y - originY, z - originZ, 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 { } else {
return null; 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 // this won't be a schematic block, this will be a throwaway
return placeBlockCost * 2; // we're going to have to break it eventually 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 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 😎 // 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 // i'm such an idiot that i just tried to copy and paste the epic gamer moment emoji too

View File

@ -87,7 +87,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo
.filter(this::followable) .filter(this::followable)
.filter(this.filter) .filter(this.filter)
.distinct() .distinct()
.collect(Collectors.toCollection(ArrayList::new)); .collect(Collectors.toList());
} }
@Override @Override

View File

@ -320,6 +320,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(block)) { if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(block)) {
BetterBlockPos pf = ctx.baritone.getPlayerContext().playerFeet(); BetterBlockPos pf = ctx.baritone.getPlayerContext().playerFeet();
// maxRegionDistanceSq 2 means adjacent directly or adjacent diagonally; nothing further than that
locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf( locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(
BlockUtils.blockToString(block), BlockUtils.blockToString(block),
Baritone.settings().maxCachedWorldScanCount.value, Baritone.settings().maxCachedWorldScanCount.value,
@ -414,11 +415,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
@Override @Override
public void mineByName(int quantity, String... blocks) { public void mineByName(int quantity, String... blocks) {
mine(quantity, new BlockOptionalMetaLookup( mine(quantity, new BlockOptionalMetaLookup(blocks));
Arrays.stream(Objects.requireNonNull(blocks))
.map(BlockOptionalMeta::new)
.toArray(BlockOptionalMeta[]::new)
));
} }
@Override @Override

View File

@ -3,10 +3,12 @@ package baritone.selection;
import baritone.api.event.events.RenderEvent; import baritone.api.event.events.RenderEvent;
import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.selection.ISelection; import baritone.api.selection.ISelection;
import baritone.api.utils.IRenderer; import baritone.utils.IRenderer;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
public class SelectionRenderer implements IRenderer, AbstractGameEventListener { public class SelectionRenderer implements IRenderer, AbstractGameEventListener {
public static final double SELECTION_BOX_EXPANSION = .005D;
private final SelectionManager manager; private final SelectionManager manager;
SelectionRenderer(SelectionManager manager) { SelectionRenderer(SelectionManager manager) {
@ -26,7 +28,7 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener {
IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth, ignoreDepth); IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth, ignoreDepth);
for (ISelection selection : selections) { for (ISelection selection : selections) {
IRenderer.drawAABB(selection.aabb(), .005f); IRenderer.drawAABB(selection.aabb(), SELECTION_BOX_EXPANSION);
} }
if (settings.renderSelectionCorners.value) { if (settings.renderSelectionCorners.value) {

View File

@ -22,7 +22,6 @@ import baritone.api.BaritoneAPI;
import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalBlock;
import baritone.api.pathing.goals.GoalTwoBlocks; import baritone.api.pathing.goals.GoalTwoBlocks;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.IRenderer;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;

View File

@ -15,11 +15,12 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>. * along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/ */
package baritone.api.utils; package baritone.utils;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.Settings; import baritone.api.Settings;
import baritone.api.utils.Helper;
import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.Tessellator;
@ -110,7 +111,7 @@ public interface IRenderer {
tessellator.draw(); tessellator.draw();
} }
static void drawAABB(AxisAlignedBB aabb, float expand) { static void drawAABB(AxisAlignedBB aabb, double expand) {
drawAABB(aabb.grow(expand, expand, expand)); drawAABB(aabb.grow(expand, expand, expand));
} }
} }

View File

@ -29,7 +29,6 @@ import baritone.api.pathing.goals.GoalXZ;
import baritone.api.pathing.goals.GoalYLevel; import baritone.api.pathing.goals.GoalYLevel;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.Helper; import baritone.api.utils.Helper;
import baritone.api.utils.IRenderer;
import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.api.utils.interfaces.IGoalRenderPos;
import baritone.behavior.PathingBehavior; import baritone.behavior.PathingBehavior;
import baritone.pathing.path.PathExecutor; import baritone.pathing.path.PathExecutor;
@ -205,7 +204,7 @@ public final class PathRenderer implements IRenderer {
toDraw = state.getSelectedBoundingBox(player.world, pos); toDraw = state.getSelectedBoundingBox(player.world, pos);
} }
IRenderer.drawAABB(toDraw, .002f); IRenderer.drawAABB(toDraw, .002D);
}); });
IRenderer.endLines(settings.renderSelectionBoxesIgnoreDepth.value); IRenderer.endLines(settings.renderSelectionBoxesIgnoreDepth.value);

View File

@ -30,7 +30,7 @@ import static java.util.Arrays.asList;
public class AxisCommand extends Command { public class AxisCommand extends Command {
public AxisCommand() { public AxisCommand() {
super(asList("axis", "highway"), "Set a goal to the axes"); super(asList("axis", "highway"));
} }
@Override @Override
@ -46,6 +46,11 @@ public class AxisCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Set a goal to the axes";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -30,7 +30,7 @@ import static java.util.Arrays.asList;
public class BlacklistCommand extends Command { public class BlacklistCommand extends Command {
public BlacklistCommand() { public BlacklistCommand() {
super("blacklist", "Blacklist closest block"); super("blacklist");
} }
@Override @Override
@ -54,6 +54,11 @@ public class BlacklistCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Blacklist closest block";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -37,7 +37,7 @@ public class BuildCommand extends Command {
private static final File schematicsDir = new File(Minecraft.getMinecraft().gameDir, "schematics"); private static final File schematicsDir = new File(Minecraft.getMinecraft().gameDir, "schematics");
public BuildCommand() { public BuildCommand() {
super("build", "Build a schematic"); super("build");
} }
@Override @Override
@ -81,6 +81,11 @@ public class BuildCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Build a schematic";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -28,7 +28,7 @@ import static java.util.Arrays.asList;
public class CancelCommand extends Command { public class CancelCommand extends Command {
public CancelCommand() { public CancelCommand() {
super(asList("cancel", "stop"), "Cancel what Baritone is currently doing"); super(asList("cancel", "stop"));
} }
@Override @Override
@ -43,6 +43,11 @@ public class CancelCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Cancel what Baritone is currently doing";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -36,7 +36,7 @@ import static java.util.Arrays.asList;
public class ChestsCommand extends Command { public class ChestsCommand extends Command {
public ChestsCommand() { public ChestsCommand() {
super("chests", "Display remembered inventories"); super("chests");
} }
@Override @Override
@ -69,6 +69,11 @@ public class ChestsCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Display remembered inventories";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -33,7 +33,7 @@ import static java.util.Arrays.asList;
public class ClearareaCommand extends Command { public class ClearareaCommand extends Command {
public ClearareaCommand() { public ClearareaCommand() {
super("cleararea", "Clear an area of all blocks"); super("cleararea");
} }
@Override @Override
@ -65,6 +65,11 @@ public class ClearareaCommand extends Command {
return args.tabCompleteDatatype(RelativeBlockPos.class); return args.tabCompleteDatatype(RelativeBlockPos.class);
} }
@Override
public String getShortDesc() {
return "Clear an area of all blocks";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -28,7 +28,7 @@ import static java.util.Arrays.asList;
public class ClickCommand extends Command { public class ClickCommand extends Command {
public ClickCommand() { public ClickCommand() {
super("click", "Open click"); super("click");
} }
@Override @Override
@ -43,6 +43,11 @@ public class ClickCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Open click";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -33,7 +33,7 @@ import static java.util.Objects.isNull;
public class ComeCommand extends Command { public class ComeCommand extends Command {
public ComeCommand() { public ComeCommand() {
super("come", "Start heading towards your camera"); super("come");
} }
@Override @Override
@ -54,12 +54,17 @@ public class ComeCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Start heading towards your camera";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(
"The come command tells Baritone to head towards your camera.", "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:", "Usage:",
"> come" "> come"

View File

@ -27,15 +27,18 @@ import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
public class CommandAlias extends Command { public class CommandAlias extends Command {
private final String shortDesc;
public final String target; public final String target;
public CommandAlias(List<String> names, String shortDesc, String target) { public CommandAlias(List<String> names, String shortDesc, String target) {
super(names, shortDesc); super(names);
this.shortDesc = shortDesc;
this.target = target; this.target = target;
} }
public CommandAlias(String name, String shortDesc, String target) { public CommandAlias(String name, String shortDesc, String target) {
super(name, shortDesc); super(name);
this.shortDesc = shortDesc;
this.target = target; this.target = target;
} }
@ -49,6 +52,11 @@ public class CommandAlias extends Command {
return CommandManager.tabComplete(String.format("%s %s", target, args.rawRest())); return CommandManager.tabComplete(String.format("%s %s", target, args.rawRest()));
} }
@Override
public String getShortDesc() {
return shortDesc;
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return Collections.singletonList(String.format("This command is an alias, for: %s ...", target)); return Collections.singletonList(String.format("This command is an alias, for: %s ...", target));

View File

@ -18,7 +18,6 @@
package baritone.utils.command.defaults; package baritone.utils.command.defaults;
import baritone.api.utils.command.Command; import baritone.api.utils.command.Command;
import baritone.api.utils.command.manager.CommandManager;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -26,7 +25,7 @@ import java.util.List;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
public class DefaultCommands { public class DefaultCommands {
public static final List<Command> commands = Collections.unmodifiableList(asList( public static final List<Command> COMMANDS = Collections.unmodifiableList(asList(
new HelpCommand(), new HelpCommand(),
new SetCommand(), new SetCommand(),
new CommandAlias(asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"), new CommandAlias(asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"),

View File

@ -28,7 +28,7 @@ import static java.util.Arrays.asList;
public class EmptyCommand extends Command { public class EmptyCommand extends Command {
public EmptyCommand() { public EmptyCommand() {
super(asList("name1", "name2"), "Short description"); super(asList("name1", "name2"));
} }
@Override @Override
@ -41,6 +41,11 @@ public class EmptyCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Short description";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -30,7 +30,7 @@ import static java.util.Arrays.asList;
public class ExploreCommand extends Command { public class ExploreCommand extends Command {
public ExploreCommand() { public ExploreCommand() {
super("explore", "Explore things"); super("explore");
} }
@Override @Override
@ -58,6 +58,11 @@ public class ExploreCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Explore things";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -34,7 +34,7 @@ import static java.util.Arrays.asList;
public class ExploreFilterCommand extends Command { public class ExploreFilterCommand extends Command {
public ExploreFilterCommand() { public ExploreFilterCommand() {
super("explorefilter", "Explore chunks from a json"); super("explorefilter");
} }
@Override @Override
@ -73,6 +73,11 @@ public class ExploreFilterCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Explore chunks from a json";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -28,7 +28,7 @@ import static java.util.Arrays.asList;
public class FarmCommand extends Command { public class FarmCommand extends Command {
public FarmCommand() { public FarmCommand() {
super("farm", "Farm nearby crops"); super("farm");
} }
@Override @Override
@ -43,6 +43,11 @@ public class FarmCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Farm nearby crops";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -32,7 +32,7 @@ import static java.util.Arrays.asList;
public class FindCommand extends Command { public class FindCommand extends Command {
public FindCommand() { public FindCommand() {
super("find", "Find positions of a certain block"); super("find");
} }
@Override @Override
@ -65,6 +65,11 @@ public class FindCommand extends Command {
return args.tabCompleteDatatype(BlockById.class); return args.tabCompleteDatatype(BlockById.class);
} }
@Override
public String getShortDesc() {
return "Find positions of a certain block";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -44,7 +44,7 @@ import static java.util.Objects.nonNull;
public class FollowCommand extends Command { public class FollowCommand extends Command {
public FollowCommand() { public FollowCommand() {
super("follow", "Follow entity things"); super("follow");
} }
@Override @Override
@ -131,6 +131,11 @@ public class FollowCommand extends Command {
} }
} }
@Override
public String getShortDesc() {
return "Follow entity things";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -29,7 +29,7 @@ import static java.util.Arrays.asList;
public class ForceCancelCommand extends Command { public class ForceCancelCommand extends Command {
public ForceCancelCommand() { public ForceCancelCommand() {
super("forcecancel", "Force cancel"); super("forcecancel");
} }
@Override @Override
@ -46,6 +46,11 @@ public class ForceCancelCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Force cancel";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -28,7 +28,7 @@ import static java.util.Arrays.asList;
public class GcCommand extends Command { public class GcCommand extends Command {
public GcCommand() { public GcCommand() {
super("gc", "Call System.gc()"); super("gc");
} }
@Override @Override
@ -45,6 +45,11 @@ public class GcCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Call System.gc()";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -36,7 +36,7 @@ import static java.util.Objects.nonNull;
public class GoalCommand extends Command { public class GoalCommand extends Command {
public GoalCommand() { public GoalCommand() {
super("goal", "Set or clear the goal"); super("goal");
} }
@Override @Override
@ -86,6 +86,11 @@ public class GoalCommand extends Command {
return helper.filterPrefix(args.getString()).stream(); return helper.filterPrefix(args.getString()).stream();
} }
@Override
public String getShortDesc() {
return "Set or clear the goal";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -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.pagination.Paginator;
import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper;
import baritone.api.utils.command.manager.CommandManager; import baritone.api.utils.command.manager.CommandManager;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.util.text.event.HoverEvent; import net.minecraft.util.text.event.HoverEvent;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -41,7 +41,7 @@ import static java.util.Objects.isNull;
public class HelpCommand extends Command { public class HelpCommand extends Command {
public HelpCommand() { public HelpCommand() {
super(asList("help", "?"), "View all commands or help on specific ones"); super(asList("help", "?"));
} }
@Override @Override
@ -53,40 +53,35 @@ public class HelpCommand extends Command {
args, new Paginator<>( args, new Paginator<>(
CommandManager.REGISTRY.descendingStream() CommandManager.REGISTRY.descendingStream()
.filter(command -> !command.hiddenFromHelp()) .filter(command -> !command.hiddenFromHelp())
.collect(Collectors.toCollection(ArrayList::new)) .collect(Collectors.toList())
), ),
() -> logDirect("All Baritone commands (clickable):"), () -> logDirect("All Baritone commands (clickable):"),
command -> { command -> {
String names = String.join("/", command.names); String names = String.join("/", command.names);
String name = command.names.get(0); String name = command.names.get(0);
return new TextComponentString(name) {{ ITextComponent shortDescComponent = new TextComponentString(" - " + command.getShortDesc());
getStyle() shortDescComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
.setColor(TextFormatting.GRAY)
.setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
new TextComponentString("") {{
getStyle().setColor(TextFormatting.GRAY);
appendSibling(new TextComponentString(names + "\n") {{ ITextComponent namesComponent = new TextComponentString(names);
getStyle().setColor(TextFormatting.WHITE); namesComponent.getStyle().setColor(TextFormatting.WHITE);
}});
appendText(command.shortDesc); ITextComponent hoverComponent = new TextComponentString("");
appendText("\n\nClick to view full help"); hoverComponent.getStyle().setColor(TextFormatting.GRAY);
}} hoverComponent.appendSibling(namesComponent);
)) hoverComponent.appendText("\n" + command.getShortDesc());
.setClickEvent(new ClickEvent( hoverComponent.appendText("\n\nClick to view full help");
ClickEvent.Action.RUN_COMMAND, String clickCommand = FORCE_COMMAND_PREFIX + String.format("%s %s", label, command.names.get(0));
FORCE_COMMAND_PREFIX + String.format("help %s", command.names.get(0))
));
appendSibling(new TextComponentString(" - " + command.shortDesc) {{ ITextComponent component = new TextComponentString(name);
getStyle().setColor(TextFormatting.DARK_GRAY); 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 { } else {
String commandName = args.getString().toLowerCase(); String commandName = args.getString().toLowerCase();
@ -96,16 +91,18 @@ public class HelpCommand extends Command {
throw new CommandNotFoundException(commandName); 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(""); logDirect("");
command.getLongDesc().forEach(this::logDirect); command.getLongDesc().forEach(this::logDirect);
logDirect(""); logDirect("");
logDirect(new TextComponentString("Click to return to the help menu") {{
getStyle().setClickEvent(new ClickEvent( ITextComponent returnComponent = new TextComponentString("Click to return to the help menu");
ClickEvent.Action.RUN_COMMAND, returnComponent.getStyle().setClickEvent(new ClickEvent(
FORCE_COMMAND_PREFIX + "help" ClickEvent.Action.RUN_COMMAND,
)); FORCE_COMMAND_PREFIX + label
}}); ));
logDirect(returnComponent);
} }
} }
@ -118,6 +115,11 @@ public class HelpCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "View all commands or help on specific ones";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -33,7 +33,7 @@ import static java.util.Objects.isNull;
public class InvertCommand extends Command { public class InvertCommand extends Command {
public InvertCommand() { public InvertCommand() {
super("invert", "Run away from the current goal"); super("invert");
} }
@Override @Override
@ -62,6 +62,11 @@ public class InvertCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Run away from the current goal";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -23,6 +23,7 @@ import baritone.api.utils.command.Command;
import baritone.api.utils.command.datatypes.BlockById; import baritone.api.utils.command.datatypes.BlockById;
import baritone.api.utils.command.datatypes.ForBlockOptionalMeta; import baritone.api.utils.command.datatypes.ForBlockOptionalMeta;
import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.arguments.ArgConsumer;
import baritone.cache.WorldScanner;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -32,7 +33,7 @@ import static java.util.Arrays.asList;
public class MineCommand extends Command { public class MineCommand extends Command {
public MineCommand() { public MineCommand() {
super("mine", "Mine some blocks"); super("mine");
} }
@Override @Override
@ -45,6 +46,7 @@ public class MineCommand extends Command {
boms.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); boms.add(args.getDatatypeFor(ForBlockOptionalMeta.class));
} }
WorldScanner.INSTANCE.repack(ctx);
baritone.getMineProcess().mine(quantity, boms.toArray(new BlockOptionalMeta[0])); baritone.getMineProcess().mine(quantity, boms.toArray(new BlockOptionalMeta[0]));
logDirect(String.format("Mining %s", boms.toString())); logDirect(String.format("Mining %s", boms.toString()));
} }
@ -54,13 +56,24 @@ public class MineCommand extends Command {
return args.tabCompleteDatatype(BlockById.class); return args.tabCompleteDatatype(BlockById.class);
} }
@Override
public String getShortDesc() {
return "Mine some blocks";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( 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:", "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."
); );
} }
} }

View File

@ -26,6 +26,7 @@ import baritone.api.utils.command.datatypes.RelativeGoal;
import baritone.api.utils.command.exception.CommandInvalidStateException; import baritone.api.utils.command.exception.CommandInvalidStateException;
import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.arguments.ArgConsumer;
import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper;
import baritone.cache.WorldScanner;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -35,7 +36,7 @@ import static java.util.Objects.isNull;
public class PathCommand extends Command { public class PathCommand extends Command {
public PathCommand() { public PathCommand() {
super("path", "Start heading towards a goal"); super(asList("path", "goto"));
} }
@Override @Override
@ -51,6 +52,7 @@ public class PathCommand extends Command {
} }
args.requireMax(0); args.requireMax(0);
WorldScanner.INSTANCE.repack(ctx);
customGoalProcess.setGoalAndPath(goal); customGoalProcess.setGoalAndPath(goal);
logDirect("Now pathing"); logDirect("Now pathing");
} }
@ -77,6 +79,11 @@ public class PathCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Start heading towards a goal";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -79,7 +79,7 @@ public class PauseResumeCommands {
} }
); );
pauseCommand = new Command("pause", "Pauses Baritone until you use resume") { pauseCommand = new Command("pause") {
@Override @Override
protected void executed(String label, ArgConsumer args, Settings settings) { protected void executed(String label, ArgConsumer args, Settings settings) {
args.requireMax(0); args.requireMax(0);
@ -97,6 +97,11 @@ public class PauseResumeCommands {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Pauses Baritone until you use resume";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(
@ -110,7 +115,7 @@ public class PauseResumeCommands {
} }
}; };
resumeCommand = new Command("resume", "Resumes Baritone after a pause") { resumeCommand = new Command("resume") {
@Override @Override
protected void executed(String label, ArgConsumer args, Settings settings) { protected void executed(String label, ArgConsumer args, Settings settings) {
args.requireMax(0); args.requireMax(0);
@ -128,6 +133,11 @@ public class PauseResumeCommands {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Resumes Baritone after a pause";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(
@ -139,7 +149,7 @@ public class PauseResumeCommands {
} }
}; };
pausedCommand = new Command("paused", "Tells you if Baritone is paused") { pausedCommand = new Command("paused") {
@Override @Override
protected void executed(String label, ArgConsumer args, Settings settings) { protected void executed(String label, ArgConsumer args, Settings settings) {
args.requireMax(0); args.requireMax(0);
@ -152,6 +162,11 @@ public class PauseResumeCommands {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Tells you if Baritone is paused";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -33,7 +33,7 @@ import static java.util.Objects.isNull;
public class ProcCommand extends Command { public class ProcCommand extends Command {
public ProcCommand() { public ProcCommand() {
super("proc", "View process state information"); super("proc");
} }
@Override @Override
@ -69,6 +69,11 @@ public class ProcCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "View process state information";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -28,7 +28,7 @@ import static java.util.Arrays.asList;
public class ReloadAllCommand extends Command { public class ReloadAllCommand extends Command {
public ReloadAllCommand() { public ReloadAllCommand() {
super("reloadall", "Reloads Baritone's cache for this world"); super("reloadall");
} }
@Override @Override
@ -43,6 +43,11 @@ public class ReloadAllCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Reloads Baritone's cache for this world";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -29,7 +29,7 @@ import static java.util.Arrays.asList;
public class RenderCommand extends Command { public class RenderCommand extends Command {
public RenderCommand() { public RenderCommand() {
super("render", "Fix glitched chunks"); super("render");
} }
@Override @Override
@ -55,6 +55,11 @@ public class RenderCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Fix glitched chunks";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -18,47 +18,24 @@
package baritone.utils.command.defaults; package baritone.utils.command.defaults;
import baritone.api.Settings; 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.Command;
import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.arguments.ArgConsumer;
import net.minecraft.world.chunk.Chunk; import baritone.cache.WorldScanner;
import net.minecraft.world.chunk.IChunkProvider;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static java.util.Objects.nonNull;
public class RepackCommand extends Command { public class RepackCommand extends Command {
public RepackCommand() { public RepackCommand() {
super(asList("repack", "rescan"), "Re-cache chunks"); super(asList("repack", "rescan"));
} }
@Override @Override
protected void executed(String label, ArgConsumer args, Settings settings) { protected void executed(String label, ArgConsumer args, Settings settings) {
args.requireMax(0); args.requireMax(0);
logDirect(String.format("Queued %d chunks for repacking", WorldScanner.INSTANCE.repack(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);
}
}
}
logDirect(String.format("Queued %d chunks for repacking", queued));
} }
@Override @Override
@ -66,6 +43,11 @@ public class RepackCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Re-cache chunks";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -28,7 +28,7 @@ import static java.util.Arrays.asList;
public class SaveAllCommand extends Command { public class SaveAllCommand extends Command {
public SaveAllCommand() { public SaveAllCommand() {
super("saveall", "Saves Baritone's cache for this world"); super("saveall");
} }
@Override @Override
@ -43,6 +43,11 @@ public class SaveAllCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Saves Baritone's cache for this world";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -28,7 +28,7 @@ import static java.util.Arrays.asList;
public class SchematicaCommand extends Command { public class SchematicaCommand extends Command {
public SchematicaCommand() { public SchematicaCommand() {
super("schematica", "Opens a Schematica schematic?"); super("schematica");
} }
@Override @Override
@ -42,10 +42,15 @@ public class SchematicaCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Builds the loaded schematic";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(
"I'm not actually sure what this does.", "Builds the schematica currently open in Schematica.",
"", "",
"Usage:", "Usage:",
"> schematica" "> schematica"

View File

@ -20,7 +20,7 @@ package baritone.utils.command.defaults;
import baritone.api.Settings; import baritone.api.Settings;
import baritone.api.event.events.RenderEvent; import baritone.api.event.events.RenderEvent;
import baritone.api.schematic.CompositeSchematic; import baritone.api.schematic.CompositeSchematic;
import baritone.api.schematic.FillBomSchematic; import baritone.api.schematic.FillSchematic;
import baritone.api.schematic.ReplaceSchematic; import baritone.api.schematic.ReplaceSchematic;
import baritone.api.schematic.ShellSchematic; import baritone.api.schematic.ShellSchematic;
import baritone.api.schematic.WallsSchematic; import baritone.api.schematic.WallsSchematic;
@ -29,7 +29,6 @@ import baritone.api.selection.ISelectionManager;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.BlockOptionalMeta;
import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.BlockOptionalMetaLookup;
import baritone.api.utils.IRenderer;
import baritone.api.utils.ISchematic; import baritone.api.utils.ISchematic;
import baritone.api.utils.command.Command; import baritone.api.utils.command.Command;
import baritone.api.utils.command.datatypes.ForBlockOptionalMeta; 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.exception.CommandInvalidTypeException;
import baritone.api.utils.command.helpers.arguments.ArgConsumer; import baritone.api.utils.command.helpers.arguments.ArgConsumer;
import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper;
import baritone.utils.IRenderer;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
@ -59,7 +59,7 @@ public class SelCommand extends Command {
private BetterBlockPos pos1 = null; private BetterBlockPos pos1 = null;
public SelCommand() { public SelCommand() {
super(asList("sel", "selection", "s"), "WorldEdit-like commands"); super(asList("sel", "selection", "s"));
} }
@Override @Override
@ -118,10 +118,13 @@ public class SelCommand extends Command {
List<BlockOptionalMeta> replacesList = new ArrayList<>(); List<BlockOptionalMeta> replacesList = new ArrayList<>();
while (args.has()) { replacesList.add(type);
while (args.has(2)) {
replacesList.add(args.getDatatypeFor(ForBlockOptionalMeta.class)); replacesList.add(args.getDatatypeFor(ForBlockOptionalMeta.class));
} }
type = args.getDatatypeFor(ForBlockOptionalMeta.class);
replaces = new BlockOptionalMetaLookup(replacesList.toArray(new BlockOptionalMeta[0])); replaces = new BlockOptionalMetaLookup(replacesList.toArray(new BlockOptionalMeta[0]));
} else { } else {
args.requireMax(0); args.requireMax(0);
@ -149,7 +152,7 @@ public class SelCommand extends Command {
Vec3i size = selection.size(); Vec3i size = selection.size();
BetterBlockPos min = selection.min(); 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) { if (action == Action.WALLS) {
schematic = new WallsSchematic(baritone, schematic); schematic = new WallsSchematic(baritone, schematic);
@ -242,6 +245,11 @@ public class SelCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "WorldEdit-like commands";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( 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 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 shell/shl [block] - The same as walls, but fills in a ceiling and floor too.",
"> sel cleararea/ca - Basically 'set air'.", "> sel cleararea/ca - Basically 'set air'.",
"> sel replace/r <place> <break...> - Replaces, with 'place', all blocks listed after it.", "> sel replace/r <blocks...> <with> - Replaces blocks with another block.",
"", "",
"> sel expand <target> <direction> <blocks> - Expand the targets.", "> sel expand <target> <direction> <blocks> - Expand the targets.",
"> sel contract <target> <direction> <blocks> - Contract the targets.", "> sel contract <target> <direction> <blocks> - Contract the targets.",

View File

@ -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.arguments.ArgConsumer;
import baritone.api.utils.command.helpers.pagination.Paginator; import baritone.api.utils.command.helpers.pagination.Paginator;
import baritone.api.utils.command.helpers.tabcomplete.TabCompleteHelper; 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.TextComponentString;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.util.text.event.HoverEvent; import net.minecraft.util.text.event.HoverEvent;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; 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.settingTypeToString;
import static baritone.api.utils.SettingsUtil.settingValueToString; import static baritone.api.utils.SettingsUtil.settingValueToString;
import static baritone.api.utils.command.BaritoneChatControl.FORCE_COMMAND_PREFIX; 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 class SetCommand extends Command {
public SetCommand() { public SetCommand() {
super(asList("set", "setting", "settings"), "View or change settings"); super(asList("set", "setting", "settings"));
} }
@Override @Override
@ -71,7 +70,7 @@ public class SetCommand extends Command {
.filter(s -> !s.getName().equals("logger")) .filter(s -> !s.getName().equals("logger"))
.filter(s -> s.getName().toLowerCase(Locale.US).contains(search.toLowerCase(Locale.US))) .filter(s -> s.getName().toLowerCase(Locale.US).contains(search.toLowerCase(Locale.US)))
.sorted((s1, s2) -> String.CASE_INSENSITIVE_ORDER.compare(s1.getName(), s2.getName())) .sorted((s1, s2) -> String.CASE_INSENSITIVE_ORDER.compare(s1.getName(), s2.getName()))
.collect(Collectors.toCollection(ArrayList<Settings.Setting>::new)); .collect(Collectors.toList());
Paginator.paginate( Paginator.paginate(
args, 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 containing the string '%s':", viewModified ? "modified " : "", search)
: String.format("All %ssettings:", viewModified ? "modified " : "") : String.format("All %ssettings:", viewModified ? "modified " : "")
), ),
setting -> new TextComponentString(setting.getName()) {{ setting -> {
getStyle() ITextComponent typeComponent = new TextComponentString(String.format(
.setColor(TextFormatting.GRAY) " (%s)",
.setHoverEvent(new HoverEvent( settingTypeToString(setting)
HoverEvent.Action.SHOW_TEXT, ));
new TextComponentString("") {{ typeComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
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) { ITextComponent hoverComponent = new TextComponentString("");
appendText(String.format("\n\nDefault:\n%s", settingDefaultToString(setting))); 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)));
.setClickEvent(new ClickEvent( String commandSuggestion = settings.prefix.value + String.format("set %s ", setting.getName());
ClickEvent.Action.SUGGEST_COMMAND,
settings.prefix.value + String.format("set %s ", setting.getName())
));
appendSibling(new TextComponentString(String.format(" (%s)", settingTypeToString(setting))) {{ ITextComponent component = new TextComponentString(setting.getName());
getStyle().setColor(TextFormatting.DARK_GRAY); 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 FORCE_COMMAND_PREFIX + "set " + arg + " " + search
); );
@ -187,18 +184,19 @@ public class SetCommand extends Command {
)); ));
} }
logDirect(new TextComponentString(String.format("Old value: %s", oldValue)) {{ ITextComponent oldValueComponent = new TextComponentString(String.format("Old value: %s", oldValue));
getStyle() oldValueComponent.getStyle()
.setColor(TextFormatting.GRAY) .setColor(TextFormatting.GRAY)
.setHoverEvent(new HoverEvent( .setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT, HoverEvent.Action.SHOW_TEXT,
new TextComponentString("Click to set the setting back to this value") new TextComponentString("Click to set the setting back to this value")
)) ))
.setClickEvent(new ClickEvent( .setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND, ClickEvent.Action.RUN_COMMAND,
FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue) FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue)
)); ));
}});
logDirect(oldValueComponent);
if ((setting.getName().equals("chatControl") && !(Boolean) setting.value && !settings.chatControlAnyway.value) || if ((setting.getName().equals("chatControl") && !(Boolean) setting.value && !settings.chatControlAnyway.value) ||
setting.getName().equals("chatControlAnyway") && !(Boolean) setting.value && !settings.chatControl.value) { setting.getName().equals("chatControlAnyway") && !(Boolean) setting.value && !settings.chatControl.value) {
@ -260,6 +258,11 @@ public class SetCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "View or change settings";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -29,7 +29,7 @@ import static java.util.Arrays.asList;
public class ThisWayCommand extends Command { public class ThisWayCommand extends Command {
public ThisWayCommand() { public ThisWayCommand() {
super(asList("thisway", "forward"), "Travel in your current direction"); super(asList("thisway", "forward"));
} }
@Override @Override
@ -51,6 +51,11 @@ public class ThisWayCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Travel in your current direction";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -30,7 +30,7 @@ import static java.util.Arrays.asList;
public class TunnelCommand extends Command { public class TunnelCommand extends Command {
public TunnelCommand() { public TunnelCommand() {
super("tunnel", "Set a goal to tunnel in your current direction"); super("tunnel");
} }
@Override @Override
@ -51,6 +51,11 @@ public class TunnelCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Set a goal to tunnel in your current direction";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -30,7 +30,7 @@ import static java.util.Objects.isNull;
public class VersionCommand extends Command { public class VersionCommand extends Command {
public VersionCommand() { public VersionCommand() {
super("version", "View the Baritone version"); super("version");
} }
@Override @Override
@ -51,6 +51,11 @@ public class VersionCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "View the Baritone version";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -50,7 +50,7 @@ import static java.util.Arrays.asList;
public class WaypointsCommand extends Command { public class WaypointsCommand extends Command {
public WaypointsCommand() { public WaypointsCommand() {
super(asList("waypoints", "waypoint", "wp"), "Manage waypoints"); super(asList("waypoints", "waypoint", "wp"));
} }
@Override @Override
@ -87,7 +87,7 @@ public class WaypointsCommand extends Command {
FORCE_COMMAND_PREFIX, FORCE_COMMAND_PREFIX,
label, label,
_action.names[0], _action.names[0],
waypoint.getTag().names[0], waypoint.getTag().getName(),
waypoint.getCreationTimestamp() waypoint.getCreationTimestamp()
)) ))
); );
@ -99,7 +99,7 @@ public class WaypointsCommand extends Command {
toComponent.apply(waypoint, action == Action.LIST ? Action.INFO : action); toComponent.apply(waypoint, action == Action.LIST ? Action.INFO : action);
if (action == Action.LIST) { 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) { if (tag != null) {
args.get(); args.get();
@ -125,7 +125,7 @@ public class WaypointsCommand extends Command {
FORCE_COMMAND_PREFIX, FORCE_COMMAND_PREFIX,
label, label,
action.names[0], action.names[0],
tag != null ? " " + tag.names[0] : "" tag != null ? " " + tag.getName() : ""
) )
); );
} else { } else {
@ -137,7 +137,7 @@ public class WaypointsCommand extends Command {
); );
} }
} else if (action == Action.SAVE) { } else if (action == Action.SAVE) {
IWaypoint.Tag tag = ForWaypoints.getTagByName(args.getString()); IWaypoint.Tag tag = IWaypoint.Tag.getByName(args.getString());
if (tag == null) { if (tag == null) {
throw new CommandInvalidStateException(String.format("'%s' is not a tag ", args.consumedString())); throw new CommandInvalidStateException(String.format("'%s' is not a tag ", args.consumedString()));
@ -159,7 +159,7 @@ public class WaypointsCommand extends Command {
logDirect(component); logDirect(component);
} else if (action == Action.CLEAR) { } else if (action == Action.CLEAR) {
args.requireMax(1); args.requireMax(1);
IWaypoint.Tag tag = ForWaypoints.getTagByName(args.getString()); IWaypoint.Tag tag = IWaypoint.Tag.getByName(args.getString());
IWaypoint[] waypoints = ForWaypoints.getWaypointsByTag(tag); IWaypoint[] waypoints = ForWaypoints.getWaypointsByTag(tag);
for (IWaypoint waypoint : waypoints) { for (IWaypoint waypoint : waypoints) {
@ -221,7 +221,7 @@ public class WaypointsCommand extends Command {
"%s%s delete %s @ %d", "%s%s delete %s @ %d",
FORCE_COMMAND_PREFIX, FORCE_COMMAND_PREFIX,
label, label,
waypoint.getTag().names[0], waypoint.getTag().getName(),
waypoint.getCreationTimestamp() waypoint.getCreationTimestamp()
) )
)); ));
@ -232,7 +232,7 @@ public class WaypointsCommand extends Command {
"%s%s goal %s @ %d", "%s%s goal %s @ %d",
FORCE_COMMAND_PREFIX, FORCE_COMMAND_PREFIX,
label, label,
waypoint.getTag().names[0], waypoint.getTag().getName(),
waypoint.getCreationTimestamp() waypoint.getCreationTimestamp()
) )
)); ));
@ -275,7 +275,7 @@ public class WaypointsCommand extends Command {
if (args.hasExactlyOne()) { if (args.hasExactlyOne()) {
if (action == Action.LIST || action == Action.SAVE || action == Action.CLEAR) { if (action == Action.LIST || action == Action.SAVE || action == Action.CLEAR) {
return new TabCompleteHelper() return new TabCompleteHelper()
.append(ForWaypoints.getTagNames()) .append(IWaypoint.Tag.getAllNames())
.sortAlphabetically() .sortAlphabetically()
.filterPrefix(args.getString()) .filterPrefix(args.getString())
.stream(); .stream();
@ -293,6 +293,11 @@ public class WaypointsCommand extends Command {
return Stream.empty(); return Stream.empty();
} }
@Override
public String getShortDesc() {
return "Manage waypoints";
}
@Override @Override
public List<String> getLongDesc() { public List<String> getLongDesc() {
return asList( return asList(

View File

@ -19,7 +19,8 @@ package baritone.utils.schematic;
import baritone.api.utils.ISchematic; import baritone.api.utils.ISchematic;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import java.util.List;
public class FillSchematic implements ISchematic { public class FillSchematic implements ISchematic {
private final int widthX; private final int widthX;
@ -35,7 +36,7 @@ public class FillSchematic implements ISchematic {
} }
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
return state; return state;
} }

View File

@ -22,6 +22,8 @@ import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import java.util.List;
public class Schematic implements ISchematic { public class Schematic implements ISchematic {
public final int widthX; public final int widthX;
public final int heightY; public final int heightY;
@ -68,7 +70,7 @@ public class Schematic implements ISchematic {
} }
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
return states[x][z][y]; return states[x][z][y];
} }

View File

@ -23,6 +23,8 @@ import com.github.lunatrius.schematica.client.world.SchematicWorld;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import java.util.List;
public final class SchematicAdapter implements ISchematic { public final class SchematicAdapter implements ISchematic {
private final SchematicWorld schematic; private final SchematicWorld schematic;
@ -31,7 +33,7 @@ public final class SchematicAdapter implements ISchematic {
} }
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
return schematic.getSchematic().getBlockState(new BlockPos(x, y, z)); return schematic.getSchematic().getBlockState(new BlockPos(x, y, z));
} }