Merge pull request #259 from cabaletta/currentlyticking-solution

currentlyTicking Solution
This commit is contained in:
Leijurv 2018-11-13 15:11:34 -08:00
commit a8f09a7fe9
No known key found for this signature in database
GPG Key ID: 44A3EA646EADAC6A
43 changed files with 852 additions and 664 deletions

View File

@ -27,6 +27,8 @@ import baritone.api.process.ICustomGoalProcess;
import baritone.api.process.IFollowProcess;
import baritone.api.process.IGetToBlockProcess;
import baritone.api.process.IMineProcess;
import baritone.api.utils.IInputOverrideHandler;
import baritone.api.utils.IPlayerContext;
/**
* @author Brady
@ -76,10 +78,14 @@ public interface IBaritone {
*/
IWorldScanner getWorldScanner();
IInputOverrideHandler getInputOverrideHandler();
ICustomGoalProcess getCustomGoalProcess();
IGetToBlockProcess getGetToBlockProcess();
IPlayerContext getPlayerContext();
/**
* Registers a {@link IGameEventListener} with Baritone's "event bus".
*

View File

@ -63,10 +63,12 @@ public interface ICachedWorld {
*
* @param block The special block to search for
* @param maximum The maximum number of position results to receive
* @param centerX The x block coordinate center of the search
* @param centerZ The z block coordinate center of the search
* @param maxRegionDistanceSq The maximum region distance, squared
* @return The locations found that match the special block
*/
LinkedList<BlockPos> getLocationsOf(String block, int maximum, int maxRegionDistanceSq);
LinkedList<BlockPos> getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq);
/**
* Reloads all of the cached regions in this world from disk. Anything that is not saved

View File

@ -17,6 +17,7 @@
package baritone.api.cache;
import baritone.api.utils.IPlayerContext;
import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos;
@ -31,6 +32,8 @@ public interface IWorldScanner {
/**
* Scans the world, up to the specified max chunk radius, for the specified blocks.
*
* @param ctx The {@link IPlayerContext} containing player and world info that the
* scan is based upon
* @param blocks The blocks to scan for
* @param max The maximum number of blocks to scan before cutoff
* @param yLevelThreshold If a block is found within this Y level, the current result will be
@ -38,5 +41,5 @@ public interface IWorldScanner {
* @param maxSearchRadius The maximum chunk search radius
* @return The matching block positions
*/
List<BlockPos> scanChunkRadius(List<Block> blocks, int max, int yLevelThreshold, int maxSearchRadius);
List<BlockPos> scanChunkRadius(IPlayerContext ctx, List<Block> blocks, int max, int yLevelThreshold, int maxSearchRadius);
}

View File

@ -18,6 +18,7 @@
package baritone.api.pathing.movement;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.IPlayerContext;
import net.minecraft.util.math.BlockPos;
import java.util.List;

View File

@ -0,0 +1,39 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.utils;
import baritone.api.behavior.IBehavior;
import baritone.api.utils.input.Input;
import net.minecraft.client.settings.KeyBinding;
/**
* @author Brady
* @since 11/12/2018
*/
public interface IInputOverrideHandler extends IBehavior {
default boolean isInputForcedDown(KeyBinding key) {
return isInputForcedDown(Input.getInputForBind(key));
}
boolean isInputForcedDown(Input input);
void setInputForceState(Input input, boolean forced);
void clearAllKeys();
}

View File

@ -0,0 +1,61 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.utils;
import baritone.api.cache.IWorldData;
import net.minecraft.block.BlockSlab;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
/**
* @author Brady
* @since 11/12/2018
*/
public interface IPlayerContext {
EntityPlayerSP player();
PlayerControllerMP playerController();
World world();
IWorldData worldData();
default BetterBlockPos playerFeet() {
// TODO find a better way to deal with soul sand!!!!!
BetterBlockPos feet = new BetterBlockPos(player().posX, player().posY + 0.1251, player().posZ);
if (world().getBlockState(feet).getBlock() instanceof BlockSlab) {
return feet.up();
}
return feet;
}
default Vec3d playerFeetAsVec() {
return new Vec3d(player().posX, player().posY, player().posZ);
}
default Vec3d playerHead() {
return new Vec3d(player().posX, player().posY + player().getEyeHeight(), player().posZ);
}
default Rotation playerRotations() {
return new Rotation(player().rotationYaw, player().rotationPitch);
}
}

View File

@ -0,0 +1,119 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General 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.input;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.settings.KeyBinding;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* An {@link Enum} representing the inputs that control the player's
* behavior. This includes moving, interacting with blocks, jumping,
* sneaking, and sprinting.
*/
public enum Input {
/**
* The move forward input
*/
MOVE_FORWARD(s -> s.keyBindForward),
/**
* The move back input
*/
MOVE_BACK(s -> s.keyBindBack),
/**
* The move left input
*/
MOVE_LEFT(s -> s.keyBindLeft),
/**
* The move right input
*/
MOVE_RIGHT(s -> s.keyBindRight),
/**
* The attack input
*/
CLICK_LEFT(s -> s.keyBindAttack),
/**
* The use item input
*/
CLICK_RIGHT(s -> s.keyBindUseItem),
/**
* The jump input
*/
JUMP(s -> s.keyBindJump),
/**
* The sneak input
*/
SNEAK(s -> s.keyBindSneak),
/**
* The sprint input
*/
SPRINT(s -> s.keyBindSprint);
/**
* Map of {@link KeyBinding} to {@link Input}. Values should be queried through {@link #getInputForBind(KeyBinding)}
*/
private static final Map<KeyBinding, Input> bindToInputMap = new HashMap<>();
/**
* The actual game {@link KeyBinding} being forced.
*/
private final KeyBinding keyBinding;
Input(Function<GameSettings, KeyBinding> keyBindingMapper) {
/*
Here, a Function is used because referring to a static field in this enum for the game instance,
as it was before, wouldn't be possible in an Enum constructor unless the static field was in an
interface that this class implemented. (Helper acted as this interface) I didn't feel like making
an interface with a game instance field just to not have to do this.
*/
this.keyBinding = keyBindingMapper.apply(Minecraft.getMinecraft().gameSettings);
}
/**
* @return The actual game {@link KeyBinding} being forced.
*/
public final KeyBinding getKeyBinding() {
return this.keyBinding;
}
/**
* Finds the {@link Input} constant that is associated with the specified {@link KeyBinding}.
*
* @param binding The {@link KeyBinding} to find the associated {@link Input} for
* @return The {@link Input} associated with the specified {@link KeyBinding}
*/
public static Input getInputForBind(KeyBinding binding) {
return bindToInputMap.computeIfAbsent(binding, b -> Arrays.stream(values()).filter(input -> input.keyBinding == b).findFirst().orElse(null));
}
}

View File

@ -21,6 +21,7 @@ import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.Settings;
import baritone.api.event.listener.IGameEventListener;
import baritone.api.utils.IPlayerContext;
import baritone.behavior.Behavior;
import baritone.behavior.LookBehavior;
import baritone.behavior.MemoryBehavior;
@ -36,6 +37,7 @@ import baritone.utils.BaritoneAutoTest;
import baritone.utils.ExampleBaritoneControl;
import baritone.utils.InputOverrideHandler;
import baritone.utils.PathingControlManager;
import baritone.utils.player.LocalPlayerContext;
import net.minecraft.client.Minecraft;
import java.io.File;
@ -139,6 +141,7 @@ public enum Baritone implements IBaritone {
return this.gameEventHandler;
}
@Override
public InputOverrideHandler getInputOverrideHandler() {
return this.inputOverrideHandler;
}
@ -162,6 +165,11 @@ public enum Baritone implements IBaritone {
return getToBlockProcess;
}
@Override
public IPlayerContext getPlayerContext() {
return LocalPlayerContext.INSTANCE;
}
@Override
public FollowProcess getFollowProcess() {
return followProcess;
@ -192,6 +200,11 @@ public enum Baritone implements IBaritone {
return worldProvider;
}
/**
* TODO-yeet This shouldn't be baritone-instance specific
*
* @return world scanner instance
*/
@Override
public WorldScanner getWorldScanner() {
return WorldScanner.INSTANCE;

View File

@ -19,6 +19,7 @@ package baritone.behavior;
import baritone.Baritone;
import baritone.api.behavior.IBehavior;
import baritone.api.utils.IPlayerContext;
/**
* A type of game event listener that is given {@link Baritone} instance context.
@ -29,9 +30,11 @@ import baritone.api.behavior.IBehavior;
public class Behavior implements IBehavior {
public final Baritone baritone;
public final IPlayerContext ctx;
protected Behavior(Baritone baritone) {
this.baritone = baritone;
this.ctx = baritone.getPlayerContext();
baritone.registerBehavior(this);
}
}

View File

@ -23,9 +23,8 @@ import baritone.api.behavior.ILookBehavior;
import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.RotationMoveEvent;
import baritone.api.utils.Rotation;
import baritone.utils.Helper;
public final class LookBehavior extends Behavior implements ILookBehavior, Helper {
public final class LookBehavior extends Behavior implements ILookBehavior {
/**
* Target's values are as follows:
@ -69,24 +68,24 @@ public final class LookBehavior extends Behavior implements ILookBehavior, Helpe
switch (event.getState()) {
case PRE: {
if (this.force) {
player().rotationYaw = this.target.getYaw();
float oldPitch = player().rotationPitch;
ctx.player().rotationYaw = this.target.getYaw();
float oldPitch = ctx.player().rotationPitch;
float desiredPitch = this.target.getPitch();
player().rotationPitch = desiredPitch;
ctx.player().rotationPitch = desiredPitch;
if (desiredPitch == oldPitch) {
nudgeToLevel();
}
this.target = null;
}
if (silent) {
this.lastYaw = player().rotationYaw;
player().rotationYaw = this.target.getYaw();
this.lastYaw = ctx.player().rotationYaw;
ctx.player().rotationYaw = this.target.getYaw();
}
break;
}
case POST: {
if (silent) {
player().rotationYaw = this.lastYaw;
ctx.player().rotationYaw = this.lastYaw;
this.target = null;
}
break;
@ -114,10 +113,10 @@ public final class LookBehavior extends Behavior implements ILookBehavior, Helpe
* Nudges the player's pitch to a regular level. (Between {@code -20} and {@code 10}, increments are by {@code 1})
*/
private void nudgeToLevel() {
if (player().rotationPitch < -20) {
player().rotationPitch++;
} else if (player().rotationPitch > 10) {
player().rotationPitch--;
if (ctx.player().rotationPitch < -20) {
ctx.player().rotationPitch++;
} else if (ctx.player().rotationPitch > 10) {
ctx.player().rotationPitch--;
}
}
}

View File

@ -27,7 +27,6 @@ import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.type.EventState;
import baritone.cache.Waypoint;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import net.minecraft.block.BlockBed;
import net.minecraft.item.ItemStack;
import net.minecraft.network.Packet;
@ -45,7 +44,7 @@ import java.util.*;
* @author Brady
* @since 8/6/2018 9:47 PM
*/
public final class MemoryBehavior extends Behavior implements IMemoryBehavior, Helper {
public final class MemoryBehavior extends Behavior implements IMemoryBehavior {
private final Map<IWorldData, WorldDataContainer> worldDataContainers = new HashMap<>();
@ -68,7 +67,7 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H
if (p instanceof CPacketPlayerTryUseItemOnBlock) {
CPacketPlayerTryUseItemOnBlock packet = event.cast();
TileEntity tileEntity = world().getTileEntity(packet.getPos());
TileEntity tileEntity = ctx.world().getTileEntity(packet.getPos());
// Ensure the TileEntity is a container of some sort
if (tileEntity instanceof TileEntityLockable) {
@ -120,14 +119,14 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H
@Override
public void onBlockInteract(BlockInteractEvent event) {
if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(event.getPos()) instanceof BlockBed) {
if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(ctx, event.getPos()) instanceof BlockBed) {
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos()));
}
}
@Override
public void onPlayerDeath() {
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, playerFeet()));
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, ctx.playerFeet()));
}
private Optional<RememberedInventory> getInventoryFromWindow(int windowId) {
@ -135,9 +134,9 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H
}
private void updateInventory() {
getInventoryFromWindow(player().openContainer.windowId).ifPresent(inventory -> {
getInventoryFromWindow(ctx.player().openContainer.windowId).ifPresent(inventory -> {
inventory.items.clear();
inventory.items.addAll(player().openContainer.getInventory().subList(0, inventory.size));
inventory.items.addAll(ctx.player().openContainer.getInventory().subList(0, inventory.size));
});
}

View File

@ -115,13 +115,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
synchronized (pathPlanLock) {
if (current.failed() || current.finished()) {
current = null;
if (goal == null || goal.isInGoal(playerFeet())) {
if (goal == null || goal.isInGoal(ctx.playerFeet())) {
logDebug("All done. At " + goal);
queuePathEvent(PathEvent.AT_GOAL);
next = null;
return;
}
if (next != null && !next.getPath().positions().contains(playerFeet())) {
if (next != null && !next.getPath().positions().contains(ctx.playerFeet())) {
// if the current path failed, we may not actually be on the next one, so make sure
logDebug("Discarding next path as it does not contain current position");
// for example if we had a nicely planned ahead path that starts where current ends
@ -314,7 +314,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
if (goal == null) {
return false;
}
if (goal.isInGoal(playerFeet())) {
if (goal.isInGoal(ctx.playerFeet())) {
return false;
}
synchronized (pathPlanLock) {
@ -338,11 +338,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
* @return The starting {@link BlockPos} for a new path
*/
public BlockPos pathStart() {
BetterBlockPos feet = playerFeet();
if (!MovementHelper.canWalkOn(feet.down())) {
if (player().onGround) {
double playerX = player().posX;
double playerZ = player().posZ;
BetterBlockPos feet = ctx.playerFeet();
if (!MovementHelper.canWalkOn(ctx, feet.down())) {
if (ctx.player().onGround) {
double playerX = ctx.player().posX;
double playerZ = ctx.player().posZ;
ArrayList<BetterBlockPos> closest = new ArrayList<>();
for (int dx = -1; dx <= 1; dx++) {
for (int dz = -1; dz <= 1; dz++) {
@ -358,7 +358,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
// can't possibly be sneaking off of this one, we're too far away
continue;
}
if (MovementHelper.canWalkOn(possibleSupport.down()) && MovementHelper.canWalkThrough(possibleSupport) && MovementHelper.canWalkThrough(possibleSupport.up())) {
if (MovementHelper.canWalkOn(ctx, possibleSupport.down()) && MovementHelper.canWalkThrough(ctx, possibleSupport) && MovementHelper.canWalkThrough(ctx, possibleSupport.up())) {
// this is plausible
logDebug("Faking path start assuming player is standing off the edge of a block");
return possibleSupport;
@ -368,7 +368,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
} else {
// !onGround
// we're in the middle of a jump
if (MovementHelper.canWalkOn(feet.down().down())) {
if (MovementHelper.canWalkOn(ctx, feet.down().down())) {
logDebug("Faking path start assuming player is midair and falling");
return feet.down();
}
@ -390,7 +390,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
}
isPathCalcInProgress = true;
}
CalculationContext context = new CalculationContext(); // not safe to create on the other thread, it looks up a lot of stuff in minecraft
CalculationContext context = new CalculationContext(baritone); // not safe to create on the other thread, it looks up a lot of stuff in minecraft
Baritone.getExecutor().execute(() -> {
if (talkAboutIt) {
logDebug("Starting to search for path from " + start + " to " + goal);
@ -421,7 +421,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
}
return result;
}).map(PathExecutor::new);
}).map(p -> new PathExecutor(this, p));
synchronized (pathPlanLock) {
if (current == null) {

View File

@ -17,7 +17,6 @@
package baritone.cache;
import baritone.utils.Helper;
import baritone.utils.pathing.PathingBlockType;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
@ -30,7 +29,7 @@ import java.util.*;
* @author Brady
* @since 8/3/2018 1:04 AM
*/
public final class CachedChunk implements Helper {
public final class CachedChunk {
public static final Set<Block> BLOCKS_TO_KEEP_TRACK_OF;

View File

@ -106,10 +106,10 @@ public final class CachedWorld implements ICachedWorld, Helper {
}
@Override
public final LinkedList<BlockPos> getLocationsOf(String block, int maximum, int maxRegionDistanceSq) {
public final LinkedList<BlockPos> getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq) {
LinkedList<BlockPos> res = new LinkedList<>();
int playerRegionX = playerFeet().getX() >> 9;
int playerRegionZ = playerFeet().getZ() >> 9;
int centerRegionX = centerX >> 9;
int centerRegionZ = centerZ >> 9;
int searchRadius = 0;
while (searchRadius <= maxRegionDistanceSq) {
@ -119,8 +119,8 @@ public final class CachedWorld implements ICachedWorld, Helper {
if (distance != searchRadius) {
continue;
}
int regionX = xoff + playerRegionX;
int regionZ = zoff + playerRegionZ;
int regionX = xoff + centerRegionX;
int regionZ = zoff + centerRegionZ;
CachedRegion region = getOrCreateRegion(regionX, regionZ);
if (region != null) {
// TODO: 100% verify if this or addAll is faster.
@ -192,7 +192,8 @@ public final class CachedWorld implements ICachedWorld, Helper {
private BlockPos guessPosition() {
WorldData data = Baritone.INSTANCE.getWorldProvider().getCurrentWorld();
if (data != null && data.getCachedWorld() == this) {
return playerFeet();
// TODO-yeet fix
return Baritone.INSTANCE.getPlayerContext().playerFeet();
}
CachedChunk mostRecentlyModified = null;
for (CachedRegion region : allRegions()) {

View File

@ -18,7 +18,6 @@
package baritone.cache;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.Helper;
import baritone.utils.pathing.PathingBlockType;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDoublePlant;
@ -38,7 +37,7 @@ import java.util.*;
* @author Brady
* @since 8/3/2018 1:09 AM
*/
public final class ChunkPacker implements Helper {
public final class ChunkPacker {
private ChunkPacker() {}

View File

@ -18,7 +18,7 @@
package baritone.cache;
import baritone.api.cache.IWorldScanner;
import baritone.utils.Helper;
import baritone.api.utils.IPlayerContext;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.multiplayer.ChunkProviderClient;
@ -30,12 +30,12 @@ import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import java.util.LinkedList;
import java.util.List;
public enum WorldScanner implements IWorldScanner, Helper {
public enum WorldScanner implements IWorldScanner {
INSTANCE;
@Override
public List<BlockPos> scanChunkRadius(List<Block> blocks, int max, int yLevelThreshold, int maxSearchRadius) {
public List<BlockPos> scanChunkRadius(IPlayerContext ctx, List<Block> blocks, int max, int yLevelThreshold, int maxSearchRadius) {
if (blocks.contains(null)) {
throw new IllegalStateException("Invalid block name should have been caught earlier: " + blocks.toString());
}
@ -43,12 +43,12 @@ public enum WorldScanner implements IWorldScanner, Helper {
if (blocks.isEmpty()) {
return res;
}
ChunkProviderClient chunkProvider = world().getChunkProvider();
ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider();
int maxSearchRadiusSq = maxSearchRadius * maxSearchRadius;
int playerChunkX = playerFeet().getX() >> 4;
int playerChunkZ = playerFeet().getZ() >> 4;
int playerY = playerFeet().getY();
int playerChunkX = ctx.playerFeet().getX() >> 4;
int playerChunkZ = ctx.playerFeet().getZ() >> 4;
int playerY = ctx.playerFeet().getY();
int searchRadiusSq = 0;
boolean foundWithinY = false;

View File

@ -129,7 +129,7 @@ class Path extends PathBase {
private Movement runBackwards(BetterBlockPos src, BetterBlockPos dest, double cost) {
for (Moves moves : Moves.values()) {
Movement move = moves.apply0(context, src);
Movement move = moves.apply0(context.getBaritone(), src);
if (move.getDest().equals(dest)) {
// have to calculate the cost at calculation time so we can accurately judge whether a cost increase happened between cached calculation and real execution
move.override(cost);

View File

@ -18,10 +18,10 @@
package baritone.pathing.movement;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.ActionCosts;
import baritone.cache.WorldData;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import baritone.utils.ToolSet;
import baritone.utils.pathing.BetterWorldBorder;
import net.minecraft.block.Block;
@ -42,6 +42,7 @@ public class CalculationContext {
private static final ItemStack STACK_BUCKET_WATER = new ItemStack(Items.WATER_BUCKET);
private final IBaritone baritone;
private final EntityPlayerSP player;
private final World world;
private final WorldData worldData;
@ -58,14 +59,15 @@ public class CalculationContext {
private final double breakBlockAdditionalCost;
private final BetterWorldBorder worldBorder;
public CalculationContext() {
this.player = Helper.HELPER.player();
this.world = Helper.HELPER.world();
this.worldData = Baritone.INSTANCE.getWorldProvider().getCurrentWorld();
public CalculationContext(IBaritone baritone) {
this.baritone = baritone;
this.player = baritone.getPlayerContext().player();
this.world = baritone.getPlayerContext().world();
this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld();
this.bsi = new BlockStateInterface(world, worldData); // TODO TODO TODO
// new CalculationContext() needs to happen, can't add an argument (i'll beat you), can we get the world provider from currentlyTicking?
this.toolSet = new ToolSet(player);
this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(false);
this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(baritone.getPlayerContext(), false);
this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether();
this.canSprint = Baritone.settings().allowSprint.get() && player.getFoodStats().getFoodLevel() > 6;
this.placeBlockCost = Baritone.settings().blockPlacementPenalty.get();
@ -85,6 +87,10 @@ public class CalculationContext {
this.worldBorder = new BetterWorldBorder(world.getWorldBorder());
}
public final IBaritone getBaritone() {
return baritone;
}
public IBlockState get(int x, int y, int z) {
return bsi.get0(x, y, z); // laughs maniacally
}

View File

@ -17,13 +17,12 @@
package baritone.pathing.movement;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.IMovement;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.*;
import baritone.api.utils.input.Input;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import baritone.utils.InputOverrideHandler;
import net.minecraft.block.BlockLiquid;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
@ -34,12 +33,13 @@ import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static baritone.utils.InputOverrideHandler.Input;
public abstract class Movement implements IMovement, Helper, MovementHelper {
public abstract class Movement implements IMovement, MovementHelper {
protected static final EnumFacing[] HORIZONTALS = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST};
protected final IBaritone baritone;
protected final IPlayerContext ctx;
private MovementState currentState = new MovementState().setStatus(MovementStatus.PREPPING);
protected final BetterBlockPos src;
@ -64,21 +64,23 @@ public abstract class Movement implements IMovement, Helper, MovementHelper {
private Boolean calculatedWhileLoaded;
protected Movement(BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak, BetterBlockPos toPlace) {
protected Movement(IBaritone baritone, BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak, BetterBlockPos toPlace) {
this.baritone = baritone;
this.ctx = baritone.getPlayerContext();
this.src = src;
this.dest = dest;
this.positionsToBreak = toBreak;
this.positionToPlace = toPlace;
}
protected Movement(BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak) {
this(src, dest, toBreak, null);
protected Movement(IBaritone baritone, BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak) {
this(baritone, src, dest, toBreak, null);
}
@Override
public double getCost() {
if (cost == null) {
cost = calculateCost(new CalculationContext());
cost = calculateCost(new CalculationContext(baritone));
}
return cost;
}
@ -97,7 +99,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper {
@Override
public double calculateCostWithoutCaching() {
return calculateCost(new CalculationContext());
return calculateCost(new CalculationContext(baritone));
}
/**
@ -108,18 +110,18 @@ public abstract class Movement implements IMovement, Helper, MovementHelper {
*/
@Override
public MovementStatus update() {
player().capabilities.isFlying = false;
ctx.player().capabilities.isFlying = false;
currentState = updateState(currentState);
if (MovementHelper.isLiquid(playerFeet())) {
if (MovementHelper.isLiquid(ctx, ctx.playerFeet())) {
currentState.setInput(Input.JUMP, true);
}
if (player().isEntityInsideOpaqueBlock()) {
if (ctx.player().isEntityInsideOpaqueBlock()) {
currentState.setInput(Input.CLICK_LEFT, true);
}
// If the movement target has to force the new rotations, or we aren't using silent move, then force the rotations
currentState.getTarget().getRotation().ifPresent(rotation ->
Baritone.INSTANCE.getLookBehavior().updateTarget(
baritone.getLookBehavior().updateTarget(
rotation,
currentState.getTarget().hasToForceRotations()));
@ -127,13 +129,13 @@ public abstract class Movement implements IMovement, Helper, MovementHelper {
// latestState.getTarget().position.ifPresent(null); NULL CONSUMER REALLY SHOULDN'T BE THE FINAL THING YOU SHOULD REALLY REPLACE THIS WITH ALMOST ACTUALLY ANYTHING ELSE JUST PLEASE DON'T LEAVE IT AS IT IS THANK YOU KANYE
currentState.getInputStates().forEach((input, forced) -> {
Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(input, forced);
baritone.getInputOverrideHandler().setInputForceState(input, forced);
});
currentState.getInputStates().replaceAll((input, forced) -> false);
// If the current status indicates a completed movement
if (currentState.getStatus().isComplete()) {
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
baritone.getInputOverrideHandler().clearAllKeys();
}
return currentState.getStatus();
@ -145,11 +147,11 @@ public abstract class Movement implements IMovement, Helper, MovementHelper {
}
boolean somethingInTheWay = false;
for (BetterBlockPos blockPos : positionsToBreak) {
if (!MovementHelper.canWalkThrough(blockPos) && !(BlockStateInterface.getBlock(blockPos) instanceof BlockLiquid)) { // can't break liquid, so don't try
if (!MovementHelper.canWalkThrough(ctx, blockPos) && !(BlockStateInterface.getBlock(ctx, blockPos) instanceof BlockLiquid)) { // can't break liquid, so don't try
somethingInTheWay = true;
Optional<Rotation> reachable = RotationUtils.reachable(player(), blockPos, playerController().getBlockReachDistance());
Optional<Rotation> reachable = RotationUtils.reachable(ctx.player(), blockPos, ctx.playerController().getBlockReachDistance());
if (reachable.isPresent()) {
MovementHelper.switchToBestToolFor(BlockStateInterface.get(blockPos));
MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, blockPos));
state.setTarget(new MovementState.MovementTarget(reachable.get(), true));
if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), blockPos)) {
state.setInput(Input.CLICK_LEFT, true);
@ -160,11 +162,11 @@ public abstract class Movement implements IMovement, Helper, MovementHelper {
//i'm doing it anyway
//i dont care if theres snow in the way!!!!!!!
//you dont own me!!!!
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(player().getPositionEyes(1.0F),
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.player().getPositionEyes(1.0F),
VecUtils.getBlockPosCenter(blockPos)), true)
);
// don't check selectedblock on this one, this is a fallback when we can't see any face directly, it's intended to be breaking the "incorrect" block
state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true);
state.setInput(Input.CLICK_LEFT, true);
return false;
}
}
@ -249,7 +251,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper {
}
List<BlockPos> result = new ArrayList<>();
for (BetterBlockPos positionToBreak : positionsToBreak) {
if (!MovementHelper.canWalkThrough(positionToBreak)) {
if (!MovementHelper.canWalkThrough(ctx, positionToBreak)) {
result.add(positionToBreak);
}
}
@ -263,7 +265,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper {
return toPlaceCached;
}
List<BlockPos> result = new ArrayList<>();
if (positionToPlace != null && !MovementHelper.canWalkOn(positionToPlace)) {
if (positionToPlace != null && !MovementHelper.canWalkOn(ctx, positionToPlace)) {
result.add(positionToPlace);
}
toPlaceCached = result;

View File

@ -20,10 +20,10 @@ package baritone.pathing.movement;
import baritone.Baritone;
import baritone.api.pathing.movement.ActionCosts;
import baritone.api.utils.*;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.MovementState.MovementTarget;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import baritone.utils.InputOverrideHandler;
import baritone.utils.ToolSet;
import net.minecraft.block.*;
import net.minecraft.block.properties.PropertyBool;
@ -44,33 +44,27 @@ import net.minecraft.world.chunk.EmptyChunk;
*/
public interface MovementHelper extends ActionCosts, Helper {
static boolean avoidBreaking(CalculationContext context, int x, int y, int z, IBlockState state) {
static boolean avoidBreaking(BlockStateInterface bsi, int x, int y, int z, IBlockState state) {
Block b = state.getBlock();
return b == Blocks.ICE // ice becomes water, and water can mess up the path
|| b instanceof BlockSilverfish // obvious reasons
// call context.get directly with x,y,z. no need to make 5 new BlockPos for no reason
|| context.get(x, y + 1, z).getBlock() instanceof BlockLiquid//don't break anything touching liquid on any side
|| context.get(x + 1, y, z).getBlock() instanceof BlockLiquid
|| context.get(x - 1, y, z).getBlock() instanceof BlockLiquid
|| context.get(x, y, z + 1).getBlock() instanceof BlockLiquid
|| context.get(x, y, z - 1).getBlock() instanceof BlockLiquid;
|| bsi.get0(x, y + 1, z).getBlock() instanceof BlockLiquid//don't break anything touching liquid on any side
|| bsi.get0(x + 1, y, z).getBlock() instanceof BlockLiquid
|| bsi.get0(x - 1, y, z).getBlock() instanceof BlockLiquid
|| bsi.get0(x, y, z + 1).getBlock() instanceof BlockLiquid
|| bsi.get0(x, y, z - 1).getBlock() instanceof BlockLiquid;
}
/**
* Can I walk through this block? e.g. air, saplings, torches, etc
*
* @param pos
* @return
*/
static boolean canWalkThrough(BetterBlockPos pos) {
return canWalkThrough(new CalculationContext(), pos.x, pos.y, pos.z, BlockStateInterface.get(pos));
static boolean canWalkThrough(IPlayerContext ctx, BetterBlockPos pos) {
return canWalkThrough(new BlockStateInterface(ctx), pos.x, pos.y, pos.z);
}
static boolean canWalkThrough(CalculationContext context, int x, int y, int z) {
return canWalkThrough(context, x, y, z, context.get(x, y, z));
static boolean canWalkThrough(BlockStateInterface bsi, int x, int y, int z) {
return canWalkThrough(bsi, x, y, z, bsi.get0(x, y, z));
}
static boolean canWalkThrough(CalculationContext context, int x, int y, int z, IBlockState state) {
static boolean canWalkThrough(BlockStateInterface bsi, int x, int y, int z, IBlockState state) {
Block block = state.getBlock();
if (block == Blocks.AIR) { // early return for most common case
return true;
@ -111,7 +105,7 @@ public interface MovementHelper extends ActionCosts, Helper {
if (Baritone.settings().assumeWalkOnWater.get()) {
return false;
}
IBlockState up = context.get(x, y + 1, z);
IBlockState up = bsi.get0(x, y + 1, z);
if (up.getBlock() instanceof BlockLiquid || up.getBlock() instanceof BlockLilyPad) {
return false;
}
@ -182,12 +176,12 @@ public interface MovementHelper extends ActionCosts, Helper {
return state.getMaterial().isReplaceable();
}
static boolean isDoorPassable(BlockPos doorPos, BlockPos playerPos) {
static boolean isDoorPassable(IPlayerContext ctx, BlockPos doorPos, BlockPos playerPos) {
if (playerPos.equals(doorPos)) {
return false;
}
IBlockState state = BlockStateInterface.get(doorPos);
IBlockState state = BlockStateInterface.get(ctx, doorPos);
if (!(state.getBlock() instanceof BlockDoor)) {
return true;
}
@ -195,12 +189,12 @@ public interface MovementHelper extends ActionCosts, Helper {
return isHorizontalBlockPassable(doorPos, state, playerPos, BlockDoor.OPEN);
}
static boolean isGatePassable(BlockPos gatePos, BlockPos playerPos) {
static boolean isGatePassable(IPlayerContext ctx, BlockPos gatePos, BlockPos playerPos) {
if (playerPos.equals(gatePos)) {
return false;
}
IBlockState state = BlockStateInterface.get(gatePos);
IBlockState state = BlockStateInterface.get(ctx, gatePos);
if (!(state.getBlock() instanceof BlockFenceGate)) {
return true;
}
@ -245,7 +239,7 @@ public interface MovementHelper extends ActionCosts, Helper {
*
* @return
*/
static boolean canWalkOn(CalculationContext context, int x, int y, int z, IBlockState state) {
static boolean canWalkOn(BlockStateInterface bsi, int x, int y, int z, IBlockState state) {
Block block = state.getBlock();
if (block == Blocks.AIR || block == Blocks.MAGMA) {
// early return for most common case (air)
@ -267,7 +261,7 @@ public interface MovementHelper extends ActionCosts, Helper {
if (isWater(block)) {
// since this is called literally millions of times per second, the benefit of not allocating millions of useless "pos.up()"
// BlockPos s that we'd just garbage collect immediately is actually noticeable. I don't even think its a decrease in readability
Block up = context.get(x, y + 1, z).getBlock();
Block up = bsi.get0(x, y + 1, z).getBlock();
if (up == Blocks.WATERLILY) {
return true;
}
@ -294,24 +288,28 @@ public interface MovementHelper extends ActionCosts, Helper {
return block instanceof BlockStairs;
}
static boolean canWalkOn(BetterBlockPos pos, IBlockState state) {
return canWalkOn(new CalculationContext(), pos.x, pos.y, pos.z, state);
static boolean canWalkOn(IPlayerContext ctx, BetterBlockPos pos, IBlockState state) {
return canWalkOn(new BlockStateInterface(ctx), pos.x, pos.y, pos.z, state);
}
static boolean canWalkOn(BetterBlockPos pos) {
return canWalkOn(new CalculationContext(), pos.x, pos.y, pos.z, BlockStateInterface.get(pos));
static boolean canWalkOn(IPlayerContext ctx, BetterBlockPos pos) {
return canWalkOn(new BlockStateInterface(ctx), pos.x, pos.y, pos.z);
}
static boolean canWalkOn(CalculationContext context, int x, int y, int z) {
return canWalkOn(context, x, y, z, context.get(x, y, z));
static boolean canWalkOn(BlockStateInterface bsi, int x, int y, int z) {
return canWalkOn(bsi, x, y, z, bsi.get0(x, y, z));
}
static boolean canPlaceAgainst(CalculationContext context, int x, int y, int z) {
return canPlaceAgainst(context.get(x, y, z));
static boolean canPlaceAgainst(BlockStateInterface bsi, int x, int y, int z) {
return canPlaceAgainst(bsi.get0(x, y, z));
}
static boolean canPlaceAgainst(BlockPos pos) {
return canPlaceAgainst(BlockStateInterface.get(pos));
static boolean canPlaceAgainst(BlockStateInterface bsi, BlockPos pos) {
return canPlaceAgainst(bsi.get0(pos.getX(), pos.getY(), pos.getZ()));
}
static boolean canPlaceAgainst(IPlayerContext ctx, BlockPos pos) {
return canPlaceAgainst(new BlockStateInterface(ctx), pos);
}
static boolean canPlaceAgainst(IBlockState state) {
@ -325,11 +323,11 @@ public interface MovementHelper extends ActionCosts, Helper {
static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) {
Block block = state.getBlock();
if (!canWalkThrough(context, x, y, z, state)) {
if (!canWalkThrough(context.bsi(), x, y, z, state)) {
if (!context.canBreakAt(x, y, z)) {
return COST_INF;
}
if (avoidBreaking(context, x, y, z, state)) {
if (avoidBreaking(context.bsi(), x, y, z, state)) {
return COST_INF;
}
if (block instanceof BlockLiquid) {
@ -360,26 +358,13 @@ public interface MovementHelper extends ActionCosts, Helper {
&& state.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.BOTTOM;
}
/**
* AutoTool
*/
static void switchToBestTool() {
RayTraceUtils.getSelectedBlock().ifPresent(pos -> {
IBlockState state = BlockStateInterface.get(pos);
if (state.getBlock().equals(Blocks.AIR)) {
return;
}
switchToBestToolFor(state);
});
}
/**
* AutoTool for a specific block
*
* @param b the blockstate to mine
*/
static void switchToBestToolFor(IBlockState b) {
switchToBestToolFor(b, new ToolSet(Helper.HELPER.player()));
static void switchToBestToolFor(IPlayerContext ctx, IBlockState b) {
switchToBestToolFor(ctx, b, new ToolSet(ctx.player()));
}
/**
@ -388,12 +373,12 @@ public interface MovementHelper extends ActionCosts, Helper {
* @param b the blockstate to mine
* @param ts previously calculated ToolSet
*/
static void switchToBestToolFor(IBlockState b, ToolSet ts) {
Helper.HELPER.player().inventory.currentItem = ts.getBestSlot(b.getBlock());
static void switchToBestToolFor(IPlayerContext ctx, IBlockState b, ToolSet ts) {
ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock());
}
static boolean throwaway(boolean select) {
EntityPlayerSP p = Helper.HELPER.player();
static boolean throwaway(IPlayerContext ctx, boolean select) {
EntityPlayerSP p = ctx.player();
NonNullList<ItemStack> inv = p.inventory.mainInventory;
for (byte i = 0; i < 9; i++) {
ItemStack item = inv.get(i);
@ -428,14 +413,14 @@ public interface MovementHelper extends ActionCosts, Helper {
return false;
}
static void moveTowards(MovementState state, BlockPos pos) {
EntityPlayerSP player = Helper.HELPER.player();
static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) {
EntityPlayerSP player = ctx.player();
state.setTarget(new MovementTarget(
new Rotation(RotationUtils.calcRotationFromVec3d(player.getPositionEyes(1.0F),
VecUtils.getBlockPosCenter(pos),
new Rotation(player.rotationYaw, player.rotationPitch)).getYaw(), player.rotationPitch),
false
)).setInput(InputOverrideHandler.Input.MOVE_FORWARD, true);
)).setInput(Input.MOVE_FORWARD, true);
}
/**
@ -453,11 +438,12 @@ public interface MovementHelper extends ActionCosts, Helper {
* Returns whether or not the block at the specified pos is
* water, regardless of whether or not it is flowing.
*
* @param ctx The player context
* @param bp The block pos
* @return Whether or not the block is water
*/
static boolean isWater(BlockPos bp) {
return isWater(BlockStateInterface.getBlock(bp));
static boolean isWater(IPlayerContext ctx, BlockPos bp) {
return isWater(BlockStateInterface.getBlock(ctx, bp));
}
static boolean isLava(Block b) {
@ -467,11 +453,12 @@ public interface MovementHelper extends ActionCosts, Helper {
/**
* Returns whether or not the specified pos has a liquid
*
* @param ctx The player context
* @param p The pos
* @return Whether or not the block is a liquid
*/
static boolean isLiquid(BlockPos p) {
return BlockStateInterface.getBlock(p) instanceof BlockLiquid;
static boolean isLiquid(IPlayerContext ctx, BlockPos p) {
return BlockStateInterface.getBlock(ctx, p) instanceof BlockLiquid;
}
static boolean isFlowing(IBlockState state) {

View File

@ -19,7 +19,7 @@ package baritone.pathing.movement;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.Rotation;
import baritone.utils.InputOverrideHandler.Input;
import baritone.api.utils.input.Input;
import net.minecraft.util.math.Vec3d;
import java.util.HashMap;

View File

@ -17,6 +17,7 @@
package baritone.pathing.movement;
import baritone.api.IBaritone;
import baritone.api.utils.BetterBlockPos;
import baritone.pathing.movement.movements.*;
import baritone.utils.pathing.MutableMoveResult;
@ -30,8 +31,8 @@ import net.minecraft.util.EnumFacing;
public enum Moves {
DOWNWARD(0, -1, 0) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementDownward(src, src.down());
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementDownward(baritone, src, src.down());
}
@Override
@ -42,8 +43,8 @@ public enum Moves {
PILLAR(0, +1, 0) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementPillar(src, src.up());
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementPillar(baritone, src, src.up());
}
@Override
@ -54,8 +55,8 @@ public enum Moves {
TRAVERSE_NORTH(0, 0, -1) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementTraverse(src, src.north());
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementTraverse(baritone, src, src.north());
}
@Override
@ -66,8 +67,8 @@ public enum Moves {
TRAVERSE_SOUTH(0, 0, +1) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementTraverse(src, src.south());
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementTraverse(baritone, src, src.south());
}
@Override
@ -78,8 +79,8 @@ public enum Moves {
TRAVERSE_EAST(+1, 0, 0) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementTraverse(src, src.east());
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementTraverse(baritone, src, src.east());
}
@Override
@ -90,8 +91,8 @@ public enum Moves {
TRAVERSE_WEST(-1, 0, 0) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementTraverse(src, src.west());
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementTraverse(baritone, src, src.west());
}
@Override
@ -102,8 +103,8 @@ public enum Moves {
ASCEND_NORTH(0, +1, -1) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementAscend(src, new BetterBlockPos(src.x, src.y + 1, src.z - 1));
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementAscend(baritone, src, new BetterBlockPos(src.x, src.y + 1, src.z - 1));
}
@Override
@ -114,8 +115,8 @@ public enum Moves {
ASCEND_SOUTH(0, +1, +1) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementAscend(src, new BetterBlockPos(src.x, src.y + 1, src.z + 1));
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementAscend(baritone, src, new BetterBlockPos(src.x, src.y + 1, src.z + 1));
}
@Override
@ -126,8 +127,8 @@ public enum Moves {
ASCEND_EAST(+1, +1, 0) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementAscend(src, new BetterBlockPos(src.x + 1, src.y + 1, src.z));
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementAscend(baritone, src, new BetterBlockPos(src.x + 1, src.y + 1, src.z));
}
@Override
@ -138,8 +139,8 @@ public enum Moves {
ASCEND_WEST(-1, +1, 0) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementAscend(src, new BetterBlockPos(src.x - 1, src.y + 1, src.z));
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementAscend(baritone, src, new BetterBlockPos(src.x - 1, src.y + 1, src.z));
}
@Override
@ -150,13 +151,13 @@ public enum Moves {
DESCEND_EAST(+1, -1, 0, false, true) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
MutableMoveResult res = new MutableMoveResult();
apply(context, src.x, src.y, src.z, res);
apply(new CalculationContext(baritone), src.x, src.y, src.z, res);
if (res.y == src.y - 1) {
return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z));
return new MovementDescend(baritone, src, new BetterBlockPos(res.x, res.y, res.z));
} else {
return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z));
return new MovementFall(baritone, src, new BetterBlockPos(res.x, res.y, res.z));
}
}
@ -168,13 +169,13 @@ public enum Moves {
DESCEND_WEST(-1, -1, 0, false, true) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
MutableMoveResult res = new MutableMoveResult();
apply(context, src.x, src.y, src.z, res);
apply(new CalculationContext(baritone), src.x, src.y, src.z, res);
if (res.y == src.y - 1) {
return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z));
return new MovementDescend(baritone, src, new BetterBlockPos(res.x, res.y, res.z));
} else {
return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z));
return new MovementFall(baritone, src, new BetterBlockPos(res.x, res.y, res.z));
}
}
@ -186,13 +187,13 @@ public enum Moves {
DESCEND_NORTH(0, -1, -1, false, true) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
MutableMoveResult res = new MutableMoveResult();
apply(context, src.x, src.y, src.z, res);
apply(new CalculationContext(baritone), src.x, src.y, src.z, res);
if (res.y == src.y - 1) {
return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z));
return new MovementDescend(baritone, src, new BetterBlockPos(res.x, res.y, res.z));
} else {
return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z));
return new MovementFall(baritone, src, new BetterBlockPos(res.x, res.y, res.z));
}
}
@ -204,13 +205,13 @@ public enum Moves {
DESCEND_SOUTH(0, -1, +1, false, true) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
MutableMoveResult res = new MutableMoveResult();
apply(context, src.x, src.y, src.z, res);
apply(new CalculationContext(baritone), src.x, src.y, src.z, res);
if (res.y == src.y - 1) {
return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z));
return new MovementDescend(baritone, src, new BetterBlockPos(res.x, res.y, res.z));
} else {
return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z));
return new MovementFall(baritone, src, new BetterBlockPos(res.x, res.y, res.z));
}
}
@ -222,8 +223,8 @@ public enum Moves {
DIAGONAL_NORTHEAST(+1, 0, -1) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementDiagonal(src, EnumFacing.NORTH, EnumFacing.EAST);
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementDiagonal(baritone, src, EnumFacing.NORTH, EnumFacing.EAST);
}
@Override
@ -234,8 +235,8 @@ public enum Moves {
DIAGONAL_NORTHWEST(-1, 0, -1) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementDiagonal(src, EnumFacing.NORTH, EnumFacing.WEST);
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementDiagonal(baritone, src, EnumFacing.NORTH, EnumFacing.WEST);
}
@Override
@ -246,8 +247,8 @@ public enum Moves {
DIAGONAL_SOUTHEAST(+1, 0, +1) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementDiagonal(src, EnumFacing.SOUTH, EnumFacing.EAST);
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementDiagonal(baritone, src, EnumFacing.SOUTH, EnumFacing.EAST);
}
@Override
@ -258,8 +259,8 @@ public enum Moves {
DIAGONAL_SOUTHWEST(-1, 0, +1) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return new MovementDiagonal(src, EnumFacing.SOUTH, EnumFacing.WEST);
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return new MovementDiagonal(baritone, src, EnumFacing.SOUTH, EnumFacing.WEST);
}
@Override
@ -270,8 +271,8 @@ public enum Moves {
PARKOUR_NORTH(0, 0, -4, true, false) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return MovementParkour.cost(context, src, EnumFacing.NORTH);
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return MovementParkour.cost(baritone, src, EnumFacing.NORTH);
}
@Override
@ -282,8 +283,8 @@ public enum Moves {
PARKOUR_SOUTH(0, 0, +4, true, false) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return MovementParkour.cost(context, src, EnumFacing.SOUTH);
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return MovementParkour.cost(baritone, src, EnumFacing.SOUTH);
}
@Override
@ -294,8 +295,8 @@ public enum Moves {
PARKOUR_EAST(+4, 0, 0, true, false) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return MovementParkour.cost(context, src, EnumFacing.EAST);
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return MovementParkour.cost(baritone, src, EnumFacing.EAST);
}
@Override
@ -306,8 +307,8 @@ public enum Moves {
PARKOUR_WEST(-4, 0, 0, true, false) {
@Override
public Movement apply0(CalculationContext context, BetterBlockPos src) {
return MovementParkour.cost(context, src, EnumFacing.WEST);
public Movement apply0(IBaritone baritone, BetterBlockPos src) {
return MovementParkour.cost(baritone, src, EnumFacing.WEST);
}
@Override
@ -335,7 +336,7 @@ public enum Moves {
this(x, y, z, false, false);
}
public abstract Movement apply0(CalculationContext context, BetterBlockPos src);
public abstract Movement apply0(IBaritone baritone, BetterBlockPos src);
public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) {
if (dynamicXZ || dynamicY) {

View File

@ -18,16 +18,17 @@
package baritone.pathing.movement.movements;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.RayTraceUtils;
import baritone.api.utils.RotationUtils;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface;
import baritone.utils.InputOverrideHandler;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
@ -42,8 +43,8 @@ public class MovementAscend extends Movement {
private int ticksWithoutPlacement = 0;
public MovementAscend(BetterBlockPos src, BetterBlockPos dest) {
super(src, dest, new BetterBlockPos[]{dest, src.up(2), dest.up()}, dest.down());
public MovementAscend(IBaritone baritone, BetterBlockPos src, BetterBlockPos dest) {
super(baritone, src, dest, new BetterBlockPos[]{dest, src.up(2), dest.up()}, dest.down());
}
@Override
@ -71,7 +72,7 @@ public class MovementAscend extends Movement {
return COST_INF;// the only thing we can ascend onto from a bottom slab is another bottom slab
}
boolean hasToPlace = false;
if (!MovementHelper.canWalkOn(context, destX, y, destZ, toPlace)) {
if (!MovementHelper.canWalkOn(context.bsi(), destX, y, destZ, toPlace)) {
if (!context.canPlaceThrowawayAt(destX, y, destZ)) {
return COST_INF;
}
@ -87,7 +88,7 @@ public class MovementAscend extends Movement {
if (againstX == x && againstZ == z) {
continue;
}
if (MovementHelper.canPlaceAgainst(context, againstX, y, againstZ)) {
if (MovementHelper.canPlaceAgainst(context.bsi(), againstX, y, againstZ)) {
hasToPlace = true;
break;
}
@ -97,7 +98,7 @@ public class MovementAscend extends Movement {
}
}
IBlockState srcUp2 = null;
if (context.get(x, y + 3, z).getBlock() instanceof BlockFalling && (MovementHelper.canWalkThrough(context, x, y + 1, z) || !((srcUp2 = context.get(x, y + 2, z)).getBlock() instanceof BlockFalling))) {//it would fall on us and possibly suffocate us
if (context.get(x, y + 3, z).getBlock() instanceof BlockFalling && (MovementHelper.canWalkThrough(context.bsi(), x, y + 1, z) || !((srcUp2 = context.get(x, y + 2, z)).getBlock() instanceof BlockFalling))) {//it would fall on us and possibly suffocate us
// HOWEVER, we assume that we're standing in the start position
// that means that src and src.up(1) are both air
// maybe they aren't now, but they will be by the time this starts
@ -161,40 +162,40 @@ public class MovementAscend extends Movement {
return state;
}
if (playerFeet().equals(dest)) {
if (ctx.playerFeet().equals(dest)) {
return state.setStatus(MovementStatus.SUCCESS);
}
IBlockState jumpingOnto = BlockStateInterface.get(positionToPlace);
if (!MovementHelper.canWalkOn(positionToPlace, jumpingOnto)) {
IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace);
if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) {
for (int i = 0; i < 4; i++) {
BlockPos anAgainst = positionToPlace.offset(HORIZONTALS[i]);
if (anAgainst.equals(src)) {
continue;
}
if (MovementHelper.canPlaceAgainst(anAgainst)) {
if (!MovementHelper.throwaway(true)) {//get ready to place a throwaway block
if (MovementHelper.canPlaceAgainst(ctx, anAgainst)) {
if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block
return state.setStatus(MovementStatus.UNREACHABLE);
}
double faceX = (dest.getX() + anAgainst.getX() + 1.0D) * 0.5D;
double faceY = (dest.getY() + anAgainst.getY()) * 0.5D;
double faceZ = (dest.getZ() + anAgainst.getZ() + 1.0D) * 0.5D;
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true));
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true));
EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit;
RayTraceUtils.getSelectedBlock().ifPresent(selectedBlock -> {
if (Objects.equals(selectedBlock, anAgainst) && selectedBlock.offset(side).equals(positionToPlace)) {
ticksWithoutPlacement++;
state.setInput(InputOverrideHandler.Input.SNEAK, true);
if (player().isSneaking()) {
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
state.setInput(Input.SNEAK, true);
if (ctx.player().isSneaking()) {
state.setInput(Input.CLICK_RIGHT, true);
}
if (ticksWithoutPlacement > 10) {
// After 10 ticks without placement, we might be standing in the way, move back
state.setInput(InputOverrideHandler.Input.MOVE_BACK, true);
state.setInput(Input.MOVE_BACK, true);
}
} else {
state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); // break whatever replaceable block is in the way
state.setInput(Input.CLICK_LEFT, true); // break whatever replaceable block is in the way
}
//System.out.println("Trying to look at " + anAgainst + ", actually looking at" + selectedBlock);
});
@ -203,8 +204,8 @@ public class MovementAscend extends Movement {
}
return state.setStatus(MovementStatus.UNREACHABLE);
}
MovementHelper.moveTowards(state, dest);
if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(BlockStateInterface.get(src.down()))) {
MovementHelper.moveTowards(ctx, state, dest);
if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(BlockStateInterface.get(ctx, src.down()))) {
return state; // don't jump while walking from a non double slab into a bottom slab
}
@ -213,13 +214,13 @@ public class MovementAscend extends Movement {
}
if (headBonkClear()) {
return state.setInput(InputOverrideHandler.Input.JUMP, true);
return state.setInput(Input.JUMP, true);
}
int xAxis = Math.abs(src.getX() - dest.getX()); // either 0 or 1
int zAxis = Math.abs(src.getZ() - dest.getZ()); // either 0 or 1
double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - player().posZ);
double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - player().posZ);
double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
// System.out.println(flatDistToNext + " " + sideDist);
if (flatDistToNext > 1.2 || sideDist > 0.2) {
return state;
@ -228,14 +229,14 @@ public class MovementAscend extends Movement {
// Once we are pointing the right way and moving, start jumping
// This is slightly more efficient because otherwise we might start jumping before moving, and fall down without moving onto the block we want to jump onto
// Also wait until we are close enough, because we might jump and hit our head on an adjacent block
return state.setInput(InputOverrideHandler.Input.JUMP, true);
return state.setInput(Input.JUMP, true);
}
private boolean headBonkClear() {
BetterBlockPos startUp = src.up(2);
for (int i = 0; i < 4; i++) {
BetterBlockPos check = startUp.offset(EnumFacing.byHorizontalIndex(i));
if (!MovementHelper.canWalkThrough(check)) {
if (!MovementHelper.canWalkThrough(ctx, check)) {
// We might bonk our head
return false;
}

View File

@ -18,13 +18,14 @@
package baritone.pathing.movement.movements;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.utils.InputOverrideHandler;
import baritone.utils.pathing.MutableMoveResult;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFalling;
@ -36,8 +37,8 @@ public class MovementDescend extends Movement {
private int numTicks = 0;
public MovementDescend(BetterBlockPos start, BetterBlockPos end) {
super(start, end, new BetterBlockPos[]{end.up(2), end.up(), end}, end.down());
public MovementDescend(IBaritone baritone, BetterBlockPos start, BetterBlockPos end) {
super(baritone, start, end, new BetterBlockPos[]{end.up(2), end.up(), end}, end.down());
}
@Override
@ -88,7 +89,7 @@ public class MovementDescend extends Movement {
//C, D, etc determine the length of the fall
IBlockState below = context.get(destX, y - 2, destZ);
if (!MovementHelper.canWalkOn(context, destX, y - 2, destZ, below)) {
if (!MovementHelper.canWalkOn(context.bsi(), destX, y - 2, destZ, below)) {
dynamicFallCost(context, x, y, z, destX, destZ, totalCost, below, res);
return;
}
@ -117,7 +118,7 @@ public class MovementDescend extends Movement {
// and potentially replace the water we're going to fall into
return;
}
if (!MovementHelper.canWalkThrough(context, destX, y - 2, destZ, below) && below.getBlock() != Blocks.WATER) {
if (!MovementHelper.canWalkThrough(context.bsi(), destX, y - 2, destZ, below) && below.getBlock() != Blocks.WATER) {
return;
}
for (int fallHeight = 3; true; fallHeight++) {
@ -145,10 +146,10 @@ public class MovementDescend extends Movement {
if (ontoBlock.getBlock() == Blocks.FLOWING_WATER) {
return;
}
if (MovementHelper.canWalkThrough(context, destX, newY, destZ, ontoBlock)) {
if (MovementHelper.canWalkThrough(context.bsi(), destX, newY, destZ, ontoBlock)) {
continue;
}
if (!MovementHelper.canWalkOn(context, destX, newY, destZ, ontoBlock)) {
if (!MovementHelper.canWalkOn(context.bsi(), destX, newY, destZ, ontoBlock)) {
return;
}
if (MovementHelper.isBottomSlab(ontoBlock)) {
@ -181,30 +182,30 @@ public class MovementDescend extends Movement {
return state;
}
BlockPos playerFeet = playerFeet();
if (playerFeet.equals(dest) && (MovementHelper.isLiquid(dest) || player().posY - playerFeet.getY() < 0.094)) { // lilypads
BlockPos playerFeet = ctx.playerFeet();
if (playerFeet.equals(dest) && (MovementHelper.isLiquid(ctx, dest) || ctx.player().posY - playerFeet.getY() < 0.094)) { // lilypads
// Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately
return state.setStatus(MovementStatus.SUCCESS);
/* else {
// System.out.println(player().posY + " " + playerFeet.getY() + " " + (player().posY - playerFeet.getY()));
}*/
}
double diffX = player().posX - (dest.getX() + 0.5);
double diffZ = player().posZ - (dest.getZ() + 0.5);
double diffX = ctx.player().posX - (dest.getX() + 0.5);
double diffZ = ctx.player().posZ - (dest.getZ() + 0.5);
double ab = Math.sqrt(diffX * diffX + diffZ * diffZ);
double x = player().posX - (src.getX() + 0.5);
double z = player().posZ - (src.getZ() + 0.5);
double x = ctx.player().posX - (src.getX() + 0.5);
double z = ctx.player().posZ - (src.getZ() + 0.5);
double fromStart = Math.sqrt(x * x + z * z);
if (!playerFeet.equals(dest) || ab > 0.25) {
BlockPos fakeDest = new BlockPos(dest.getX() * 2 - src.getX(), dest.getY(), dest.getZ() * 2 - src.getZ());
if (numTicks++ < 20) {
MovementHelper.moveTowards(state, fakeDest);
MovementHelper.moveTowards(ctx, state, fakeDest);
if (fromStart > 1.25) {
state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, false);
state.setInput(InputOverrideHandler.Input.MOVE_BACK, true);
state.setInput(Input.MOVE_FORWARD, false);
state.setInput(Input.MOVE_BACK, true);
}
} else {
MovementHelper.moveTowards(state, dest);
MovementHelper.moveTowards(ctx, state, dest);
}
}
return state;

View File

@ -17,13 +17,14 @@
package baritone.pathing.movement.movements;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.utils.InputOverrideHandler;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
@ -37,17 +38,17 @@ public class MovementDiagonal extends Movement {
private static final double SQRT_2 = Math.sqrt(2);
public MovementDiagonal(BetterBlockPos start, EnumFacing dir1, EnumFacing dir2) {
this(start, start.offset(dir1), start.offset(dir2), dir2);
public MovementDiagonal(IBaritone baritone, BetterBlockPos start, EnumFacing dir1, EnumFacing dir2) {
this(baritone, start, start.offset(dir1), start.offset(dir2), dir2);
// super(start, start.offset(dir1).offset(dir2), new BlockPos[]{start.offset(dir1), start.offset(dir1).up(), start.offset(dir2), start.offset(dir2).up(), start.offset(dir1).offset(dir2), start.offset(dir1).offset(dir2).up()}, new BlockPos[]{start.offset(dir1).offset(dir2).down()});
}
private MovementDiagonal(BetterBlockPos start, BetterBlockPos dir1, BetterBlockPos dir2, EnumFacing drr2) {
this(start, dir1.offset(drr2), dir1, dir2);
private MovementDiagonal(IBaritone baritone, BetterBlockPos start, BetterBlockPos dir1, BetterBlockPos dir2, EnumFacing drr2) {
this(baritone, start, dir1.offset(drr2), dir1, dir2);
}
private MovementDiagonal(BetterBlockPos start, BetterBlockPos end, BetterBlockPos dir1, BetterBlockPos dir2) {
super(start, end, new BetterBlockPos[]{dir1, dir1.up(), dir2, dir2.up(), end, end.up()});
private MovementDiagonal(IBaritone baritone, BetterBlockPos start, BetterBlockPos end, BetterBlockPos dir1, BetterBlockPos dir2) {
super(baritone, start, end, new BetterBlockPos[]{dir1, dir1.up(), dir2, dir2.up(), end, end.up()});
}
@Override
@ -61,11 +62,11 @@ public class MovementDiagonal extends Movement {
return COST_INF;
}
IBlockState destInto = context.get(destX, y, destZ);
if (!MovementHelper.canWalkThrough(context, destX, y, destZ, destInto) || !MovementHelper.canWalkThrough(context, destX, y + 1, destZ)) {
if (!MovementHelper.canWalkThrough(context.bsi(), destX, y, destZ, destInto) || !MovementHelper.canWalkThrough(context.bsi(), destX, y + 1, destZ)) {
return COST_INF;
}
IBlockState destWalkOn = context.get(destX, y - 1, destZ);
if (!MovementHelper.canWalkOn(context, destX, y - 1, destZ, destWalkOn)) {
if (!MovementHelper.canWalkOn(context.bsi(), destX, y - 1, destZ, destWalkOn)) {
return COST_INF;
}
double multiplier = WALK_ONE_BLOCK_COST;
@ -140,14 +141,14 @@ public class MovementDiagonal extends Movement {
return state;
}
if (playerFeet().equals(dest)) {
if (ctx.playerFeet().equals(dest)) {
state.setStatus(MovementStatus.SUCCESS);
return state;
}
if (!MovementHelper.isLiquid(playerFeet())) {
state.setInput(InputOverrideHandler.Input.SPRINT, true);
if (!MovementHelper.isLiquid(ctx, ctx.playerFeet())) {
state.setInput(Input.SPRINT, true);
}
MovementHelper.moveTowards(state, dest);
MovementHelper.moveTowards(ctx, state, dest);
return state;
}
@ -163,7 +164,7 @@ public class MovementDiagonal extends Movement {
}
List<BlockPos> result = new ArrayList<>();
for (int i = 4; i < 6; i++) {
if (!MovementHelper.canWalkThrough(positionsToBreak[i])) {
if (!MovementHelper.canWalkThrough(ctx, positionsToBreak[i])) {
result.add(positionsToBreak[i]);
}
}
@ -178,7 +179,7 @@ public class MovementDiagonal extends Movement {
}
List<BlockPos> result = new ArrayList<>();
for (int i = 0; i < 4; i++) {
if (!MovementHelper.canWalkThrough(positionsToBreak[i])) {
if (!MovementHelper.canWalkThrough(ctx, positionsToBreak[i])) {
result.add(positionsToBreak[i]);
}
}

View File

@ -17,6 +17,7 @@
package baritone.pathing.movement.movements;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.BetterBlockPos;
import baritone.pathing.movement.CalculationContext;
@ -31,8 +32,8 @@ public class MovementDownward extends Movement {
private int numTicks = 0;
public MovementDownward(BetterBlockPos start, BetterBlockPos end) {
super(start, end, new BetterBlockPos[]{end});
public MovementDownward(IBaritone baritone, BetterBlockPos start, BetterBlockPos end) {
super(baritone, start, end, new BetterBlockPos[]{end});
}
@Override
@ -47,7 +48,7 @@ public class MovementDownward extends Movement {
}
public static double cost(CalculationContext context, int x, int y, int z) {
if (!MovementHelper.canWalkOn(context, x, y - 2, z)) {
if (!MovementHelper.canWalkOn(context.bsi(), x, y - 2, z)) {
return COST_INF;
}
IBlockState d = context.get(x, y - 1, z);
@ -68,17 +69,17 @@ public class MovementDownward extends Movement {
return state;
}
if (playerFeet().equals(dest)) {
if (ctx.playerFeet().equals(dest)) {
return state.setStatus(MovementStatus.SUCCESS);
}
double diffX = player().posX - (dest.getX() + 0.5);
double diffZ = player().posZ - (dest.getZ() + 0.5);
double diffX = ctx.player().posX - (dest.getX() + 0.5);
double diffZ = ctx.player().posZ - (dest.getZ() + 0.5);
double ab = Math.sqrt(diffX * diffX + diffZ * diffZ);
if (numTicks++ < 10 && ab < 0.2) {
return state;
}
MovementHelper.moveTowards(state, positionsToBreak[0]);
MovementHelper.moveTowards(ctx, state, positionsToBreak[0]);
return state;
}
}

View File

@ -18,17 +18,18 @@
package baritone.pathing.movement.movements;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.Rotation;
import baritone.api.utils.RotationUtils;
import baritone.api.utils.VecUtils;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.pathing.movement.MovementState.MovementTarget;
import baritone.utils.InputOverrideHandler;
import baritone.utils.pathing.MutableMoveResult;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Items;
@ -42,8 +43,8 @@ public class MovementFall extends Movement {
private static final ItemStack STACK_BUCKET_WATER = new ItemStack(Items.WATER_BUCKET);
private static final ItemStack STACK_BUCKET_EMPTY = new ItemStack(Items.BUCKET);
public MovementFall(BetterBlockPos src, BetterBlockPos dest) {
super(src, dest, MovementFall.buildPositionsToBreak(src, dest));
public MovementFall(IBaritone baritone, BetterBlockPos src, BetterBlockPos dest) {
super(baritone, src, dest, MovementFall.buildPositionsToBreak(src, dest));
}
@Override
@ -63,22 +64,22 @@ public class MovementFall extends Movement {
return state;
}
BlockPos playerFeet = playerFeet();
Rotation toDest = RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.getBlockPosCenter(dest));
BlockPos playerFeet = ctx.playerFeet();
Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest));
Rotation targetRotation = null;
if (!MovementHelper.isWater(dest) && src.getY() - dest.getY() > Baritone.settings().maxFallHeightNoWater.get() && !playerFeet.equals(dest)) {
if (!InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_WATER)) || world().provider.isNether()) {
if (!MovementHelper.isWater(ctx, dest) && src.getY() - dest.getY() > Baritone.settings().maxFallHeightNoWater.get() && !playerFeet.equals(dest)) {
if (!InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER)) || ctx.world().provider.isNether()) {
return state.setStatus(MovementStatus.UNREACHABLE);
}
if (player().posY - dest.getY() < playerController().getBlockReachDistance() && !player().onGround) {
player().inventory.currentItem = player().inventory.getSlotFor(STACK_BUCKET_WATER);
if (ctx.player().posY - dest.getY() < ctx.playerController().getBlockReachDistance() && !ctx.player().onGround) {
ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER);
targetRotation = new Rotation(toDest.getYaw(), 90.0F);
RayTraceResult trace = mc.objectMouseOver;
if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK && player().rotationPitch > 89.0F) {
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK && ctx.player().rotationPitch > 89.0F) {
state.setInput(Input.CLICK_RIGHT, true);
}
}
}
@ -87,17 +88,17 @@ public class MovementFall extends Movement {
} else {
state.setTarget(new MovementTarget(toDest, false));
}
if (playerFeet.equals(dest) && (player().posY - playerFeet.getY() < 0.094 || MovementHelper.isWater(dest))) { // 0.094 because lilypads
if (MovementHelper.isWater(dest)) {
if (InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) {
player().inventory.currentItem = player().inventory.getSlotFor(STACK_BUCKET_EMPTY);
if (player().motionY >= 0) {
return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || MovementHelper.isWater(ctx, dest))) { // 0.094 because lilypads
if (MovementHelper.isWater(ctx, dest)) {
if (InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) {
ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY);
if (ctx.player().motionY >= 0) {
return state.setInput(Input.CLICK_RIGHT, true);
} else {
return state;
}
} else {
if (player().motionY >= 0) {
if (ctx.player().motionY >= 0) {
return state.setStatus(MovementStatus.SUCCESS);
} // don't else return state; we need to stay centered because this water might be flowing under the surface
}
@ -106,8 +107,8 @@ public class MovementFall extends Movement {
}
}
Vec3d destCenter = VecUtils.getBlockPosCenter(dest); // we are moving to the 0.5 center not the edge (like if we were falling on a ladder)
if (Math.abs(player().posX - destCenter.x) > 0.15 || Math.abs(player().posZ - destCenter.z) > 0.15) {
state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true);
if (Math.abs(ctx.player().posX - destCenter.x) > 0.15 || Math.abs(ctx.player().posZ - destCenter.z) > 0.15) {
state.setInput(Input.MOVE_FORWARD, true);
}
return state;
}
@ -116,7 +117,7 @@ public class MovementFall extends Movement {
public boolean safeToCancel(MovementState state) {
// if we haven't started walking off the edge yet, or if we're in the process of breaking blocks before doing the fall
// then it's safe to cancel this
return playerFeet().equals(src) || state.getStatus() != MovementStatus.RUNNING;
return ctx.playerFeet().equals(src) || state.getStatus() != MovementStatus.RUNNING;
}
private static BetterBlockPos[] buildPositionsToBreak(BetterBlockPos src, BetterBlockPos dest) {
@ -139,7 +140,7 @@ public class MovementFall extends Movement {
// only break if one of the first three needs to be broken
// specifically ignore the last one which might be water
for (int i = 0; i < 4 && i < positionsToBreak.length; i++) {
if (!MovementHelper.canWalkThrough(positionsToBreak[i])) {
if (!MovementHelper.canWalkThrough(ctx, positionsToBreak[i])) {
return super.prepared(state);
}
}

View File

@ -18,18 +18,19 @@
package baritone.pathing.movement.movements;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.RayTraceUtils;
import baritone.api.utils.Rotation;
import baritone.api.utils.RotationUtils;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import baritone.utils.InputOverrideHandler;
import baritone.utils.pathing.MutableMoveResult;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
@ -44,23 +45,23 @@ import java.util.Objects;
public class MovementParkour extends Movement {
private static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN};
private static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = { EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN };
private static final BetterBlockPos[] EMPTY = new BetterBlockPos[]{};
private final EnumFacing direction;
private final int dist;
private MovementParkour(BetterBlockPos src, int dist, EnumFacing dir) {
super(src, src.offset(dir, dist), EMPTY, src.offset(dir, dist).down());
private MovementParkour(IBaritone baritone, BetterBlockPos src, int dist, EnumFacing dir) {
super(baritone, src, src.offset(dir, dist), EMPTY, src.offset(dir, dist).down());
this.direction = dir;
this.dist = dist;
}
public static MovementParkour cost(CalculationContext context, BetterBlockPos src, EnumFacing direction) {
public static MovementParkour cost(IBaritone baritone, BetterBlockPos src, EnumFacing direction) {
MutableMoveResult res = new MutableMoveResult();
cost(context, src.x, src.y, src.z, direction, res);
cost(new CalculationContext(baritone), src.x, src.y, src.z, direction, res);
int dist = Math.abs(res.x - src.x) + Math.abs(res.z - src.z);
return new MovementParkour(src, dist, direction);
return new MovementParkour(baritone, src, dist, direction);
}
public static void cost(CalculationContext context, int x, int y, int z, EnumFacing dir, MutableMoveResult res) {
@ -77,7 +78,7 @@ public class MovementParkour extends Movement {
if (MovementHelper.avoidWalkingInto(adj.getBlock()) && adj.getBlock() != Blocks.WATER && adj.getBlock() != Blocks.FLOWING_WATER) { // magma sucks
return;
}
if (MovementHelper.canWalkOn(context, x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now)
if (MovementHelper.canWalkOn(context.bsi(), x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now)
return;
}
@ -110,7 +111,7 @@ public class MovementParkour extends Movement {
return;
}
}
if (MovementHelper.canWalkOn(context, x + xDiff * i, y - 1, z + zDiff * i)) {
if (MovementHelper.canWalkOn(context.bsi(), x + xDiff * i, y - 1, z + zDiff * i)) {
res.x = x + xDiff * i;
res.y = y;
res.z = z + zDiff * i;
@ -138,12 +139,12 @@ public class MovementParkour extends Movement {
return;
}
for (int i = 0; i < 5; i++) {
int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset();
int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getZOffset();
int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP [i].getXOffset();
int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP [i].getZOffset();
if (againstX == x + xDiff * 3 && againstZ == z + zDiff * 3) { // we can't turn around that fast
continue;
}
if (MovementHelper.canPlaceAgainst(context, againstX, y - 1, againstZ)) {
if (MovementHelper.canPlaceAgainst(context.bsi(), againstX, y - 1, againstZ)) {
res.x = destX;
res.y = y;
res.z = destZ;
@ -191,71 +192,71 @@ public class MovementParkour extends Movement {
if (state.getStatus() != MovementStatus.RUNNING) {
return state;
}
if (player().isHandActive()) {
if (ctx.player().isHandActive()) {
logDebug("Pausing parkour since hand is active");
return state;
}
if (dist >= 4) {
state.setInput(InputOverrideHandler.Input.SPRINT, true);
state.setInput(Input.SPRINT, true);
}
MovementHelper.moveTowards(state, dest);
if (playerFeet().equals(dest)) {
Block d = BlockStateInterface.getBlock(dest);
MovementHelper.moveTowards(ctx, state, dest);
if (ctx.playerFeet().equals(dest)) {
Block d = BlockStateInterface.getBlock(ctx, dest);
if (d == Blocks.VINE || d == Blocks.LADDER) {
// it physically hurt me to add support for parkour jumping onto a vine
// but i did it anyway
return state.setStatus(MovementStatus.SUCCESS);
}
if (player().posY - playerFeet().getY() < 0.094) { // lilypads
if (ctx.player().posY - ctx.playerFeet().getY() < 0.094) { // lilypads
state.setStatus(MovementStatus.SUCCESS);
}
} else if (!playerFeet().equals(src)) {
if (playerFeet().equals(src.offset(direction)) || player().posY - playerFeet().getY() > 0.0001) {
} else if (!ctx.playerFeet().equals(src)) {
if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - ctx.playerFeet().getY() > 0.0001) {
if (!MovementHelper.canWalkOn(dest.down()) && !player().onGround) {
if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround) {
BlockPos positionToPlace = dest.down();
for (int i = 0; i < 5; i++) {
BlockPos against1 = positionToPlace.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]);
BlockPos against1 = positionToPlace.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP [i]);
if (against1.up().equals(src.offset(direction, 3))) { // we can't turn around that fast
continue;
}
if (MovementHelper.canPlaceAgainst(against1)) {
if (!MovementHelper.throwaway(true)) {//get ready to place a throwaway block
if (MovementHelper.canPlaceAgainst(ctx, against1)) {
if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block
return state.setStatus(MovementStatus.UNREACHABLE);
}
double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D;
double faceY = (dest.getY() + against1.getY()) * 0.5D;
double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D;
Rotation place = RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations());
RayTraceResult res = RayTraceUtils.rayTraceTowards(player(), place, playerController().getBlockReachDistance());
Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations());
RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance());
if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(dest.down())) {
state.setTarget(new MovementState.MovementTarget(place, true));
}
RayTraceUtils.getSelectedBlock().ifPresent(selectedBlock -> {
EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit;
if (Objects.equals(selectedBlock, against1) && selectedBlock.offset(side).equals(dest.down())) {
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
state.setInput(Input.CLICK_RIGHT, true);
}
});
}
}
}
if (dist == 3) { // this is a 2 block gap, dest = src + direction * 3
double xDiff = (src.x + 0.5) - player().posX;
double zDiff = (src.z + 0.5) - player().posZ;
double xDiff = (src.x + 0.5) - ctx.player().posX;
double zDiff = (src.z + 0.5) - ctx.player().posZ;
double distFromStart = Math.max(Math.abs(xDiff), Math.abs(zDiff));
if (distFromStart < 0.7) {
return state;
}
}
state.setInput(InputOverrideHandler.Input.JUMP, true);
} else if (!playerFeet().equals(dest.offset(direction, -1))) {
state.setInput(InputOverrideHandler.Input.SPRINT, false);
if (playerFeet().equals(src.offset(direction, -1))) {
MovementHelper.moveTowards(state, src);
state.setInput(Input.JUMP, true);
} else if (!ctx.playerFeet().equals(dest.offset(direction, -1))) {
state.setInput(Input.SPRINT, false);
if (ctx.playerFeet().equals(src.offset(direction, -1))) {
MovementHelper.moveTowards(ctx, state, src);
} else {
MovementHelper.moveTowards(state, src.offset(direction, -1));
MovementHelper.moveTowards(ctx, state, src.offset(direction, -1));
}
}
}

View File

@ -17,17 +17,18 @@
package baritone.pathing.movement.movements;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.Rotation;
import baritone.api.utils.RotationUtils;
import baritone.api.utils.VecUtils;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface;
import baritone.utils.InputOverrideHandler;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
@ -36,8 +37,8 @@ import net.minecraft.util.math.Vec3d;
public class MovementPillar extends Movement {
public MovementPillar(BetterBlockPos start, BetterBlockPos end) {
super(start, end, new BetterBlockPos[]{start.up(2)}, start);
public MovementPillar(IBaritone baritone, BetterBlockPos start, BetterBlockPos end) {
super(baritone, start, end, new BetterBlockPos[]{start.up(2)}, start);
}
@Override
@ -142,41 +143,41 @@ public class MovementPillar extends Movement {
return state;
}
IBlockState fromDown = BlockStateInterface.get(src);
if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(dest)) {
IBlockState fromDown = BlockStateInterface.get(ctx, src);
if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(ctx, dest)) {
// stay centered while swimming up a water column
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.getBlockPosCenter(dest)), false));
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)), false));
Vec3d destCenter = VecUtils.getBlockPosCenter(dest);
if (Math.abs(player().posX - destCenter.x) > 0.2 || Math.abs(player().posZ - destCenter.z) > 0.2) {
state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true);
if (Math.abs(ctx.player().posX - destCenter.x) > 0.2 || Math.abs(ctx.player().posZ - destCenter.z) > 0.2) {
state.setInput(Input.MOVE_FORWARD, true);
}
if (playerFeet().equals(dest)) {
if (ctx.playerFeet().equals(dest)) {
return state.setStatus(MovementStatus.SUCCESS);
}
return state;
}
boolean ladder = fromDown.getBlock() instanceof BlockLadder || fromDown.getBlock() instanceof BlockVine;
boolean vine = fromDown.getBlock() instanceof BlockVine;
Rotation rotation = RotationUtils.calcRotationFromVec3d(player().getPositionEyes(1.0F),
Rotation rotation = RotationUtils.calcRotationFromVec3d(ctx.player().getPositionEyes(1.0F),
VecUtils.getBlockPosCenter(positionToPlace),
new Rotation(player().rotationYaw, player().rotationPitch));
new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch));
if (!ladder) {
state.setTarget(new MovementState.MovementTarget(new Rotation(player().rotationYaw, rotation.getPitch()), true));
state.setTarget(new MovementState.MovementTarget(new Rotation(ctx.player().rotationYaw, rotation.getPitch()), true));
}
boolean blockIsThere = MovementHelper.canWalkOn(src) || ladder;
boolean blockIsThere = MovementHelper.canWalkOn(ctx, src) || ladder;
if (ladder) {
BlockPos against = vine ? getAgainst(new CalculationContext(), src) : src.offset(fromDown.getValue(BlockLadder.FACING).getOpposite());
BlockPos against = vine ? getAgainst(new CalculationContext(baritone), src) : src.offset(fromDown.getValue(BlockLadder.FACING).getOpposite());
if (against == null) {
logDebug("Unable to climb vines");
return state.setStatus(MovementStatus.UNREACHABLE);
}
if (playerFeet().equals(against.up()) || playerFeet().equals(dest)) {
if (ctx.playerFeet().equals(against.up()) || ctx.playerFeet().equals(dest)) {
return state.setStatus(MovementStatus.SUCCESS);
}
if (MovementHelper.isBottomSlab(BlockStateInterface.get(src.down()))) {
state.setInput(InputOverrideHandler.Input.JUMP, true);
if (MovementHelper.isBottomSlab(BlockStateInterface.get(ctx, src.down()))) {
state.setInput(Input.JUMP, true);
}
/*
if (thePlayer.getPosition0().getX() != from.getX() || thePlayer.getPosition0().getZ() != from.getZ()) {
@ -184,49 +185,49 @@ public class MovementPillar extends Movement {
}
*/
MovementHelper.moveTowards(state, against);
MovementHelper.moveTowards(ctx, state, against);
return state;
} else {
// Get ready to place a throwaway block
if (!MovementHelper.throwaway(true)) {
if (!MovementHelper.throwaway(ctx, true)) {
return state.setStatus(MovementStatus.UNREACHABLE);
}
state.setInput(InputOverrideHandler.Input.SNEAK, player().posY > dest.getY()); // delay placement by 1 tick for ncp compatibility
state.setInput(Input.SNEAK, ctx.player().posY > dest.getY()); // delay placement by 1 tick for ncp compatibility
// since (lower down) we only right click once player.isSneaking, and that happens the tick after we request to sneak
double diffX = player().posX - (dest.getX() + 0.5);
double diffZ = player().posZ - (dest.getZ() + 0.5);
double diffX = ctx.player().posX - (dest.getX() + 0.5);
double diffZ = ctx.player().posZ - (dest.getZ() + 0.5);
double dist = Math.sqrt(diffX * diffX + diffZ * diffZ);
if (dist > 0.17) {//why 0.17? because it seemed like a good number, that's why
//[explanation added after baritone port lol] also because it needs to be less than 0.2 because of the 0.3 sneak limit
//and 0.17 is reasonably less than 0.2
// If it's been more than forty ticks of trying to jump and we aren't done yet, go forward, maybe we are stuck
state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true);
state.setInput(Input.MOVE_FORWARD, true);
// revise our target to both yaw and pitch if we're going to be moving forward
state.setTarget(new MovementState.MovementTarget(rotation, true));
} else {
// If our Y coordinate is above our goal, stop jumping
state.setInput(InputOverrideHandler.Input.JUMP, player().posY < dest.getY());
state.setInput(Input.JUMP, ctx.player().posY < dest.getY());
}
if (!blockIsThere) {
Block fr = BlockStateInterface.get(src).getBlock();
if (!(fr instanceof BlockAir || fr.isReplaceable(world(), src))) {
state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true);
Block fr = BlockStateInterface.get(ctx, src).getBlock();
if (!(fr instanceof BlockAir || fr.isReplaceable(ctx.world(), src))) {
state.setInput(Input.CLICK_LEFT, true);
blockIsThere = false;
} else if (player().isSneaking()) { // 1 tick after we're able to place
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
} else if (ctx.player().isSneaking()) { // 1 tick after we're able to place
state.setInput(Input.CLICK_RIGHT, true);
}
}
}
// If we are at our goal and the block below us is placed
if (playerFeet().equals(dest) && blockIsThere) {
if (ctx.playerFeet().equals(dest) && blockIsThere) {
return state.setStatus(MovementStatus.SUCCESS);
}
@ -235,13 +236,13 @@ public class MovementPillar extends Movement {
@Override
protected boolean prepared(MovementState state) {
if (playerFeet().equals(src) || playerFeet().equals(src.down())) {
Block block = BlockStateInterface.getBlock(src.down());
if (ctx.playerFeet().equals(src) || ctx.playerFeet().equals(src.down())) {
Block block = BlockStateInterface.getBlock(ctx, src.down());
if (block == Blocks.LADDER || block == Blocks.VINE) {
state.setInput(InputOverrideHandler.Input.SNEAK, true);
state.setInput(Input.SNEAK, true);
}
}
if (MovementHelper.isWater(dest.up())) {
if (MovementHelper.isWater(ctx, dest.up())) {
return true;
}
return super.prepared(state);

View File

@ -18,14 +18,15 @@
package baritone.pathing.movement.movements;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.*;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface;
import baritone.utils.InputOverrideHandler;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
@ -43,8 +44,8 @@ public class MovementTraverse extends Movement {
*/
private boolean wasTheBridgeBlockAlwaysThere = true;
public MovementTraverse(BetterBlockPos from, BetterBlockPos to) {
super(from, to, new BetterBlockPos[]{to.up(), to}, to.down());
public MovementTraverse(IBaritone baritone, BetterBlockPos from, BetterBlockPos to) {
super(baritone, from, to, new BetterBlockPos[]{to.up(), to}, to.down());
}
@Override
@ -63,7 +64,7 @@ public class MovementTraverse extends Movement {
IBlockState pb1 = context.get(destX, y, destZ);
IBlockState destOn = context.get(destX, y - 1, destZ);
Block srcDown = context.getBlock(x, y - 1, z);
if (MovementHelper.canWalkOn(context, destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge
if (MovementHelper.canWalkOn(context.bsi(), destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge
double WC = WALK_ONE_BLOCK_COST;
boolean water = false;
if (MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock())) {
@ -121,7 +122,7 @@ public class MovementTraverse extends Movement {
if (againstX == x && againstZ == z) {
continue;
}
if (MovementHelper.canPlaceAgainst(context, againstX, y - 1, againstZ)) {
if (MovementHelper.canPlaceAgainst(context.bsi(), againstX, y - 1, againstZ)) {
return WC + context.placeBlockCost() + hardness1 + hardness2;
}
}
@ -152,86 +153,86 @@ public class MovementTraverse extends Movement {
return state;
}
// and if it's fine to walk into the blocks in front
if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(positionsToBreak[0]).getBlock())) {
if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(ctx, positionsToBreak[0]).getBlock())) {
return state;
}
if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(positionsToBreak[1]).getBlock())) {
if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(ctx, positionsToBreak[1]).getBlock())) {
return state;
}
// and we aren't already pressed up against the block
double dist = Math.max(Math.abs(player().posX - (dest.getX() + 0.5D)), Math.abs(player().posZ - (dest.getZ() + 0.5D)));
double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D)));
if (dist < 0.83) {
return state;
}
// combine the yaw to the center of the destination, and the pitch to the specific block we're trying to break
// it's safe to do this since the two blocks we break (in a traverse) are right on top of each other and so will have the same yaw
float yawToDest = RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(dest)).getYaw();
float yawToDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(dest)).getYaw();
float pitchToBreak = state.getTarget().getRotation().get().getPitch();
state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true));
return state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true);
return state.setInput(Input.MOVE_FORWARD, true);
}
//sneak may have been set to true in the PREPPING state while mining an adjacent block
state.setInput(InputOverrideHandler.Input.SNEAK, false);
state.setInput(Input.SNEAK, false);
Block fd = BlockStateInterface.get(src.down()).getBlock();
Block fd = BlockStateInterface.get(ctx, src.down()).getBlock();
boolean ladder = fd instanceof BlockLadder || fd instanceof BlockVine;
IBlockState pb0 = BlockStateInterface.get(positionsToBreak[0]);
IBlockState pb1 = BlockStateInterface.get(positionsToBreak[1]);
IBlockState pb0 = BlockStateInterface.get(ctx, positionsToBreak[0]);
IBlockState pb1 = BlockStateInterface.get(ctx, positionsToBreak[1]);
boolean door = pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor;
if (door) {
boolean isDoorActuallyBlockingUs = false;
if (pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(src, dest)) {
if (pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, src, dest)) {
isDoorActuallyBlockingUs = true;
} else if (pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(dest, src)) {
} else if (pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, dest, src)) {
isDoorActuallyBlockingUs = true;
}
if (isDoorActuallyBlockingUs && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) {
return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(positionsToBreak[0])), true))
.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(positionsToBreak[0])), true))
.setInput(Input.CLICK_RIGHT, true);
}
}
if (pb0.getBlock() instanceof BlockFenceGate || pb1.getBlock() instanceof BlockFenceGate) {
BlockPos blocked = null;
if (!MovementHelper.isGatePassable(positionsToBreak[0], src.up())) {
if (!MovementHelper.isGatePassable(ctx, positionsToBreak[0], src.up())) {
blocked = positionsToBreak[0];
} else if (!MovementHelper.isGatePassable(positionsToBreak[1], src)) {
} else if (!MovementHelper.isGatePassable(ctx, positionsToBreak[1], src)) {
blocked = positionsToBreak[1];
}
if (blocked != null) {
return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(blocked)), true))
.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(blocked)), true))
.setInput(Input.CLICK_RIGHT, true);
}
}
boolean isTheBridgeBlockThere = MovementHelper.canWalkOn(positionToPlace) || ladder;
BlockPos whereAmI = playerFeet();
boolean isTheBridgeBlockThere = MovementHelper.canWalkOn(ctx, positionToPlace) || ladder;
BlockPos whereAmI = ctx.playerFeet();
if (whereAmI.getY() != dest.getY() && !ladder) {
logDebug("Wrong Y coordinate");
if (whereAmI.getY() < dest.getY()) {
state.setInput(InputOverrideHandler.Input.JUMP, true);
state.setInput(Input.JUMP, true);
}
return state;
}
if (isTheBridgeBlockThere) {
if (playerFeet().equals(dest)) {
if (ctx.playerFeet().equals(dest)) {
return state.setStatus(MovementStatus.SUCCESS);
}
if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(playerFeet())) {
state.setInput(InputOverrideHandler.Input.SPRINT, true);
if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(ctx, ctx.playerFeet())) {
state.setInput(Input.SPRINT, true);
}
Block destDown = BlockStateInterface.get(dest.down()).getBlock();
Block destDown = BlockStateInterface.get(ctx, dest.down()).getBlock();
if (whereAmI.getY() != dest.getY() && ladder && (destDown instanceof BlockVine || destDown instanceof BlockLadder)) {
new MovementPillar(dest.down(), dest).updateState(state); // i'm sorry
new MovementPillar(baritone, dest.down(), dest).updateState(state); // i'm sorry
return state;
}
MovementHelper.moveTowards(state, positionsToBreak[0]);
MovementHelper.moveTowards(ctx, state, positionsToBreak[0]);
return state;
} else {
wasTheBridgeBlockAlwaysThere = false;
@ -241,44 +242,44 @@ public class MovementTraverse extends Movement {
continue;
}
against1 = against1.down();
if (MovementHelper.canPlaceAgainst(against1)) {
if (!MovementHelper.throwaway(true)) { // get ready to place a throwaway block
if (MovementHelper.canPlaceAgainst(ctx, against1)) {
if (!MovementHelper.throwaway(ctx, true)) { // get ready to place a throwaway block
logDebug("bb pls get me some blocks. dirt or cobble");
return state.setStatus(MovementStatus.UNREACHABLE);
}
if (!Baritone.settings().assumeSafeWalk.get()) {
state.setInput(InputOverrideHandler.Input.SNEAK, true);
state.setInput(Input.SNEAK, true);
}
Block standingOn = BlockStateInterface.get(playerFeet().down()).getBlock();
Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock();
if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118
double dist = Math.max(Math.abs(dest.getX() + 0.5 - player().posX), Math.abs(dest.getZ() + 0.5 - player().posZ));
double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ));
if (dist < 0.85) { // 0.5 + 0.3 + epsilon
MovementHelper.moveTowards(state, dest);
return state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, false)
.setInput(InputOverrideHandler.Input.MOVE_BACK, true);
MovementHelper.moveTowards(ctx, state, dest);
return state.setInput(Input.MOVE_FORWARD, false)
.setInput(Input.MOVE_BACK, true);
}
}
state.setInput(InputOverrideHandler.Input.MOVE_BACK, false);
state.setInput(Input.MOVE_BACK, false);
double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D;
double faceY = (dest.getY() + against1.getY()) * 0.5D;
double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D;
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true));
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true));
EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit;
if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) {
return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) {
return state.setInput(Input.CLICK_RIGHT, true);
}
//System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock());
return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true);
return state.setInput(Input.CLICK_LEFT, true);
}
}
if (!Baritone.settings().assumeSafeWalk.get()) {
state.setInput(InputOverrideHandler.Input.SNEAK, true);
state.setInput(Input.SNEAK, true);
}
if (whereAmI.equals(dest)) {
// If we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of
// Out.log(from + " " + to + " " + faceX + "," + faceY + "," + faceZ + " " + whereAmI);
if (!MovementHelper.throwaway(true)) {// get ready to place a throwaway block
if (!MovementHelper.throwaway(ctx, true)) {// get ready to place a throwaway block
logDebug("bb pls get me some blocks. dirt or cobble");
return state.setStatus(MovementStatus.UNREACHABLE);
}
@ -288,24 +289,24 @@ public class MovementTraverse extends Movement {
// faceX, faceY, faceZ is the middle of the face between from and to
BlockPos goalLook = src.down(); // this is the block we were just standing on, and the one we want to place against
Rotation backToFace = RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations());
Rotation backToFace = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations());
float pitch = backToFace.getPitch();
double dist = Math.max(Math.abs(player().posX - faceX), Math.abs(player().posZ - faceZ));
double dist = Math.max(Math.abs(ctx.player().posX - faceX), Math.abs(ctx.player().posZ - faceZ));
if (dist < 0.29) {
float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), playerHead(), playerRotations()).getYaw();
float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), ctx.playerHead(), ctx.playerRotations()).getYaw();
state.setTarget(new MovementState.MovementTarget(new Rotation(yaw, pitch), true));
state.setInput(InputOverrideHandler.Input.MOVE_BACK, true);
state.setInput(Input.MOVE_BACK, true);
} else {
state.setTarget(new MovementState.MovementTarget(backToFace, true));
}
state.setInput(InputOverrideHandler.Input.SNEAK, true);
state.setInput(Input.SNEAK, true);
if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), goalLook)) {
return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); // wait to right click until we are able to place
return state.setInput(Input.CLICK_RIGHT, true); // wait to right click until we are able to place
}
// Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt());
return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true);
return state.setInput(Input.CLICK_LEFT, true);
} else {
MovementHelper.moveTowards(state, positionsToBreak[0]);
MovementHelper.moveTowards(ctx, state, positionsToBreak[0]);
return state;
// TODO MovementManager.moveTowardsBlock(to); // move towards not look at because if we are bridging for a couple blocks in a row, it is faster if we dont spin around and walk forwards then spin around and place backwards for every block
}
@ -317,15 +318,15 @@ public class MovementTraverse extends Movement {
// if we're in the process of breaking blocks before walking forwards
// or if this isn't a sneak place (the block is already there)
// then it's safe to cancel this
return state.getStatus() != MovementStatus.RUNNING || MovementHelper.canWalkOn(dest.down());
return state.getStatus() != MovementStatus.RUNNING || MovementHelper.canWalkOn(ctx, dest.down());
}
@Override
protected boolean prepared(MovementState state) {
if (playerFeet().equals(src) || playerFeet().equals(src.down())) {
Block block = BlockStateInterface.getBlock(src.down());
if (ctx.playerFeet().equals(src) || ctx.playerFeet().equals(src.down())) {
Block block = BlockStateInterface.getBlock(ctx, src.down());
if (block == Blocks.LADDER || block == Blocks.VINE) {
state.setInput(InputOverrideHandler.Input.SNEAK, true);
state.setInput(Input.SNEAK, true);
}
}
return super.prepared(state);

View File

@ -24,7 +24,10 @@ import baritone.api.pathing.movement.IMovement;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.pathing.path.IPathExecutor;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.IPlayerContext;
import baritone.api.utils.VecUtils;
import baritone.api.utils.input.Input;
import baritone.behavior.PathingBehavior;
import baritone.pathing.calc.AbstractNodeCostSearch;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.MovementHelper;
@ -32,7 +35,6 @@ import baritone.pathing.movement.movements.*;
import baritone.utils.BlockBreakHelper;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import baritone.utils.InputOverrideHandler;
import net.minecraft.init.Blocks;
import net.minecraft.util.Tuple;
import net.minecraft.util.math.BlockPos;
@ -48,6 +50,7 @@ import static baritone.api.pathing.movement.MovementStatus.*;
* @author leijurv
*/
public class PathExecutor implements IPathExecutor, Helper {
private static final double MAX_MAX_DIST_FROM_PATH = 3;
private static final double MAX_DIST_FROM_PATH = 2;
@ -72,7 +75,12 @@ public class PathExecutor implements IPathExecutor, Helper {
private HashSet<BlockPos> toPlace = new HashSet<>();
private HashSet<BlockPos> toWalkInto = new HashSet<>();
public PathExecutor(IPath path) {
private PathingBehavior behavior;
private IPlayerContext ctx;
public PathExecutor(PathingBehavior behavior, IPath path) {
this.behavior = behavior;
this.ctx = behavior.ctx;
this.path = path;
this.pathPosition = 0;
}
@ -91,18 +99,18 @@ public class PathExecutor implements IPathExecutor, Helper {
return true; // stop bugging me, I'm done
}
BetterBlockPos whereShouldIBe = path.positions().get(pathPosition);
BetterBlockPos whereAmI = playerFeet();
BetterBlockPos whereAmI = ctx.playerFeet();
if (!whereShouldIBe.equals(whereAmI)) {
if (pathPosition == 0 && whereAmI.equals(whereShouldIBe.up()) && Math.abs(player().motionY) < 0.1 && !(path.movements().get(0) instanceof MovementAscend) && !(path.movements().get(0) instanceof MovementPillar)) {
if (pathPosition == 0 && whereAmI.equals(whereShouldIBe.up()) && Math.abs(ctx.player().motionY) < 0.1 && !(path.movements().get(0) instanceof MovementAscend) && !(path.movements().get(0) instanceof MovementPillar)) {
// avoid the Wrong Y coordinate bug
// TODO add a timer here
new MovementDownward(whereAmI, whereShouldIBe).update();
new MovementDownward(behavior.baritone, whereAmI, whereShouldIBe).update();
return false;
}
//System.out.println("Should be at " + whereShouldIBe + " actually am at " + whereAmI);
if (!Blocks.AIR.equals(BlockStateInterface.getBlock(whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip
if (!Blocks.AIR.equals(BlockStateInterface.getBlock(ctx, whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip
for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks
if (whereAmI.equals(path.positions().get(i))) {
logDebug("Skipping back " + (pathPosition - i) + " steps, to " + i);
@ -278,7 +286,7 @@ public class PathExecutor implements IPathExecutor, Helper {
double best = -1;
BlockPos bestPos = null;
for (BlockPos pos : path.positions()) {
double dist = VecUtils.entityDistanceToCenter(player(), pos);
double dist = VecUtils.entityDistanceToCenter(ctx.player(), pos);
if (dist < best || best == -1) {
best = dist;
bestPos = pos;
@ -292,14 +300,14 @@ public class PathExecutor implements IPathExecutor, Helper {
if (!current.isPresent()) {
return false;
}
if (!player().onGround) {
if (!ctx.player().onGround) {
return false;
}
if (!MovementHelper.canWalkOn(playerFeet().down())) {
if (!MovementHelper.canWalkOn(ctx, ctx.playerFeet().down())) {
// we're in some kind of sketchy situation, maybe parkouring
return false;
}
if (!MovementHelper.canWalkThrough(playerFeet()) || !MovementHelper.canWalkThrough(playerFeet().up())) {
if (!MovementHelper.canWalkThrough(ctx, ctx.playerFeet()) || !MovementHelper.canWalkThrough(ctx, ctx.playerFeet().up())) {
// suffocating?
return false;
}
@ -317,7 +325,7 @@ public class PathExecutor implements IPathExecutor, Helper {
// the first block of the next path will always overlap
// no need to pause our very last movement when it would have otherwise cleanly exited with MovementStatus SUCCESS
positions = positions.subList(1, positions.size());
return positions.contains(playerFeet());
return positions.contains(ctx.playerFeet());
}
private boolean possiblyOffPath(Tuple<Double, BlockPos> status, double leniency) {
@ -326,7 +334,7 @@ public class PathExecutor implements IPathExecutor, Helper {
// when we're midair in the middle of a fall, we're very far from both the beginning and the end, but we aren't actually off path
if (path.movements().get(pathPosition) instanceof MovementFall) {
BlockPos fallDest = path.positions().get(pathPosition + 1); // .get(pathPosition) is the block we fell off of
return VecUtils.entityFlatDistanceToCenter(player(), fallDest) >= leniency; // ignore Y by using flat distance
return VecUtils.entityFlatDistanceToCenter(ctx.player(), fallDest) >= leniency; // ignore Y by using flat distance
} else {
return true;
}
@ -339,7 +347,7 @@ public class PathExecutor implements IPathExecutor, Helper {
* Regardless of current path position, snap to the current player feet if possible
*/
public boolean snipsnapifpossible() {
int index = path.positions().indexOf(playerFeet());
int index = path.positions().indexOf(ctx.playerFeet());
if (index == -1) {
return false;
}
@ -349,24 +357,23 @@ public class PathExecutor implements IPathExecutor, Helper {
}
private void sprintIfRequested() {
// first and foremost, if allowSprint is off, or if we don't have enough hunger, don't try and sprint
if (!new CalculationContext().canSprint()) {
Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT, false);
player().setSprinting(false);
if (!new CalculationContext(behavior.baritone).canSprint()) {
behavior.baritone.getInputOverrideHandler().setInputForceState(Input.SPRINT, false);
ctx.player().setSprinting(false);
return;
}
// if the movement requested sprinting, then we're done
if (Baritone.INSTANCE.getInputOverrideHandler().isInputForcedDown(mc.gameSettings.keyBindSprint)) {
if (!player().isSprinting()) {
player().setSprinting(true);
if (behavior.baritone.getInputOverrideHandler().isInputForcedDown(mc.gameSettings.keyBindSprint)) {
if (!ctx.player().isSprinting()) {
ctx.player().setSprinting(true);
}
return;
}
// we'll take it from here, no need for minecraft to see we're holding down control and sprint for us
Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT, false);
behavior.baritone.getInputOverrideHandler().setInputForceState(Input.SPRINT, false);
// however, descend doesn't request sprinting, beceause it doesn't know the context of what movement comes after it
IMovement current = path.movements().get(pathPosition);
@ -377,9 +384,9 @@ public class PathExecutor implements IPathExecutor, Helper {
BlockPos into = current.getDest().subtract(current.getSrc().down()).add(current.getDest());
for (int y = 0; y <= 2; y++) { // we could hit any of the three blocks
if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(into.up(y)))) {
if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(ctx, into.up(y)))) {
logDebug("Sprinting would be unsafe");
player().setSprinting(false);
ctx.player().setSprinting(false);
return;
}
}
@ -387,21 +394,21 @@ public class PathExecutor implements IPathExecutor, Helper {
IMovement next = path.movements().get(pathPosition + 1);
if (next instanceof MovementAscend && current.getDirection().up().equals(next.getDirection().down())) {
// a descend then an ascend in the same direction
if (!player().isSprinting()) {
player().setSprinting(true);
if (!ctx.player().isSprinting()) {
ctx.player().setSprinting(true);
}
pathPosition++;
// okay to skip clearKeys and / or onChangeInPathPosition here since this isn't possible to repeat, since it's asymmetric
logDebug("Skipping descend to straight ascend");
return;
}
if (canSprintInto(current, next)) {
if (playerFeet().equals(current.getDest())) {
if (canSprintInto(ctx, current, next)) {
if (ctx.playerFeet().equals(current.getDest())) {
pathPosition++;
onChangeInPathPosition();
}
if (!player().isSprinting()) {
player().setSprinting(true);
if (!ctx.player().isSprinting()) {
ctx.player().setSprinting(true);
}
return;
}
@ -411,23 +418,23 @@ public class PathExecutor implements IPathExecutor, Helper {
IMovement prev = path.movements().get(pathPosition - 1);
if (prev instanceof MovementDescend && prev.getDirection().up().equals(current.getDirection().down())) {
BlockPos center = current.getSrc().up();
if (player().posY >= center.getY()) { // playerFeet adds 0.1251 to account for soul sand
Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.JUMP, false);
if (!player().isSprinting()) {
player().setSprinting(true);
if (ctx.player().posY >= center.getY()) { // playerFeet adds 0.1251 to account for soul sand
behavior.baritone.getInputOverrideHandler().setInputForceState(Input.JUMP, false);
if (!ctx.player().isSprinting()) {
ctx.player().setSprinting(true);
}
return;
}
}
}
player().setSprinting(false);
ctx.player().setSprinting(false);
}
private static boolean canSprintInto(IMovement current, IMovement next) {
private static boolean canSprintInto(IPlayerContext ctx, IMovement current, IMovement next) {
if (next instanceof MovementDescend && next.getDirection().equals(current.getDirection())) {
return true;
}
if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(next.getDest().down())) {
if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(ctx, next.getDest().down())) {
return true;
}
return next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.get();
@ -438,9 +445,9 @@ public class PathExecutor implements IPathExecutor, Helper {
ticksOnCurrent = 0;
}
private static void clearKeys() {
private void clearKeys() {
// i'm just sick and tired of this snippet being everywhere lol
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
behavior.baritone.getInputOverrideHandler().clearAllKeys();
}
private void cancel() {
@ -462,7 +469,7 @@ public class PathExecutor implements IPathExecutor, Helper {
if (!path.getDest().equals(next.getPath().getDest())) {
throw new IllegalStateException();
}
PathExecutor ret = new PathExecutor(path);
PathExecutor ret = new PathExecutor(behavior, path);
ret.pathPosition = pathPosition;
ret.currentMovementOriginalCostEstimate = currentMovementOriginalCostEstimate;
ret.costEstimateIndex = costEstimateIndex;
@ -479,7 +486,7 @@ public class PathExecutor implements IPathExecutor, Helper {
throw new IllegalStateException();
}
logDebug("Discarding earliest segment movements, length cut from " + path.length() + " to " + newPath.length());
PathExecutor ret = new PathExecutor(newPath);
PathExecutor ret = new PathExecutor(behavior, newPath);
ret.pathPosition = pathPosition - cutoffAmt;
ret.currentMovementOriginalCostEstimate = currentMovementOriginalCostEstimate;
if (costEstimateIndex != null) {

View File

@ -86,7 +86,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG
if (calcFailed) {
onLostControl();
}
if (this.goal == null || this.goal.isInGoal(playerFeet())) {
if (this.goal == null || this.goal.isInGoal(ctx.playerFeet())) {
onLostControl(); // we're there xd
}
return new PathingCommand(this.goal, PathingCommandType.SET_GOAL_AND_PATH);

View File

@ -76,14 +76,14 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo
if (entity.isDead) {
return false;
}
if (entity.equals(player())) {
if (entity.equals(ctx.player())) {
return false;
}
return world().loadedEntityList.contains(entity) || world().playerEntities.contains(entity);
return ctx.world().loadedEntityList.contains(entity) || ctx.world().playerEntities.contains(entity);
}
private void scanWorld() {
cache = Stream.of(world().loadedEntityList, world().playerEntities).flatMap(List::stream).filter(this::followable).filter(this.filter).distinct().collect(Collectors.toCollection(ArrayList::new));
cache = Stream.of(ctx.world().loadedEntityList, ctx.world().playerEntities).flatMap(List::stream).filter(this::followable).filter(this.filter).distinct().collect(Collectors.toCollection(ArrayList::new));
}
@Override

View File

@ -79,7 +79,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
Baritone.getExecutor().execute(() -> rescan(current));
}
Goal goal = new GoalComposite(knownLocations.stream().map(GoalGetToBlock::new).toArray(Goal[]::new));
if (goal.isInGoal(playerFeet())) {
if (goal.isInGoal(ctx.playerFeet())) {
onLostControl();
}
return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH);
@ -97,6 +97,6 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
}
private void rescan(List<BlockPos> known) {
knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64, baritone.getWorldProvider(), world(), known);
knownLocations = MineProcess.searchWorld(ctx, Collections.singletonList(gettingTo), 64, known);
}
}

View File

@ -22,16 +22,14 @@ import baritone.api.pathing.goals.*;
import baritone.api.process.IMineProcess;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.api.utils.IPlayerContext;
import baritone.api.utils.RotationUtils;
import baritone.cache.CachedChunk;
import baritone.cache.ChunkPacker;
import baritone.cache.WorldProvider;
import baritone.cache.WorldScanner;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
@ -74,7 +72,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
if (desiredQuantity > 0) {
Item item = mining.get(0).getItemDropped(mining.get(0).getDefaultState(), new Random(), 0);
int curr = player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum();
int curr = ctx.player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum();
System.out.println("Currently have " + curr + " " + item);
if (curr >= desiredQuantity) {
logDirect("Have " + curr + " " + item.getItemStackDisplayName(new ItemStack(item, 1)));
@ -90,7 +88,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get();
if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain
List<BlockPos> curr = new ArrayList<>(knownOreLocations);
baritone.getExecutor().execute(() -> rescan(curr));
Baritone.getExecutor().execute(() -> rescan(curr));
}
if (Baritone.settings().legitMine.get()) {
addNearby();
@ -118,9 +116,9 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
private Goal updateGoal() {
List<BlockPos> locs = knownOreLocations;
if (!locs.isEmpty()) {
List<BlockPos> locs2 = prune(new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT, world());
List<BlockPos> locs2 = prune(ctx, new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT);
// can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final
Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new));
Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(ctx, loc, locs2)).toArray(Goal[]::new));
knownOreLocations = locs2;
return goal;
}
@ -138,7 +136,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
} else {
return new GoalYLevel(y);
}*/
branchPoint = playerFeet();
branchPoint = ctx.playerFeet();
}
// TODO shaft mode, mine 1x1 shafts to either side
// TODO also, see if the GoalRunAway with maintain Y at 11 works even from the surface
@ -160,8 +158,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
if (Baritone.settings().legitMine.get()) {
return;
}
List<BlockPos> locs = searchWorld(mining, ORE_LOCATIONS_COUNT, baritone.getWorldProvider(), world(), already);
locs.addAll(droppedItemsScan(mining, world()));
List<BlockPos> locs = searchWorld(ctx, mining, ORE_LOCATIONS_COUNT, already);
locs.addAll(droppedItemsScan(mining, ctx.world()));
if (locs.isEmpty()) {
logDebug("No locations for " + mining + " known, cancelling");
cancel();
@ -170,26 +168,15 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
knownOreLocations = locs;
}
private static Goal coalesce(BlockPos loc, List<BlockPos> locs) {
private static Goal coalesce(IPlayerContext ctx, BlockPos loc, List<BlockPos> locs) {
if (!Baritone.settings().forceInternalMining.get()) {
return new GoalTwoBlocks(loc);
}
boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(loc.up()) == Blocks.AIR);
boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(loc.up()) == Blocks.AIR);
if (upwardGoal) {
if (downwardGoal) {
return new GoalTwoBlocks(loc);
} else {
return new GoalBlock(loc);
}
} else {
if (downwardGoal) {
return new GoalBlock(loc.down());
} else {
return new GoalTwoBlocks(loc);
}
}
// Here, BlockStateInterface is used because the position may be in a cached chunk (the targeted block is one that is kept track of)
boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(ctx, loc.up()) == Blocks.AIR);
boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(ctx, loc.down()) == Blocks.AIR);
return upwardGoal == downwardGoal ? new GoalTwoBlocks(loc) : upwardGoal ? new GoalBlock(loc) : new GoalBlock(loc.down());
}
public static List<BlockPos> droppedItemsScan(List<Block> mining, World world) {
@ -218,13 +205,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
/*public static List<BlockPos> searchWorld(List<Block> mining, int max, World world) {
}*/
public static List<BlockPos> searchWorld(List<Block> mining, int max, WorldProvider provider, World world, List<BlockPos> alreadyKnown) {
public static List<BlockPos> searchWorld(IPlayerContext ctx, List<Block> mining, int max, List<BlockPos> alreadyKnown) {
List<BlockPos> locs = new ArrayList<>();
List<Block> uninteresting = new ArrayList<>();
//long b = System.currentTimeMillis();
for (Block m : mining) {
if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(m)) {
locs.addAll(provider.getCurrentWorld().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, 1));
locs.addAll(ctx.worldData().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 1));
} else {
uninteresting.add(m);
}
@ -235,43 +222,45 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
}
if (!uninteresting.isEmpty()) {
//long before = System.currentTimeMillis();
locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(uninteresting, max, 10, 26));
locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx, uninteresting, max, 10, 26));
//System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms");
}
locs.addAll(alreadyKnown);
return prune(locs, mining, max, world);
return prune(ctx, locs, mining, max);
}
public void addNearby() {
knownOreLocations.addAll(droppedItemsScan(mining, world()));
BlockPos playerFeet = playerFeet();
int searchDist = 4;//why four? idk
knownOreLocations.addAll(droppedItemsScan(mining, ctx.world()));
BlockPos playerFeet = ctx.playerFeet();
int searchDist = 4; // why four? idk
for (int x = playerFeet.getX() - searchDist; x <= playerFeet.getX() + searchDist; x++) {
for (int y = playerFeet.getY() - searchDist; y <= playerFeet.getY() + searchDist; y++) {
for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) {
BlockPos pos = new BlockPos(x, y, z);
if (mining.contains(BlockStateInterface.getBlock(pos)) && RotationUtils.reachable(player(), pos, playerController().getBlockReachDistance()).isPresent()) {//crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught
// crucial to only add blocks we can see because otherwise this
// is an x-ray and it'll get caught
if (mining.contains(BlockStateInterface.getBlock(ctx, pos)) && RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()).isPresent()) {
knownOreLocations.add(pos);
}
}
}
}
knownOreLocations = prune(knownOreLocations, mining, ORE_LOCATIONS_COUNT, world());
knownOreLocations = prune(ctx, knownOreLocations, mining, ORE_LOCATIONS_COUNT);
}
public static List<BlockPos> prune(List<BlockPos> locs2, List<Block> mining, int max, World world) {
List<BlockPos> dropped = droppedItemsScan(mining, world);
public static List<BlockPos> prune(IPlayerContext ctx, List<BlockPos> locs2, List<Block> mining, int max) {
List<BlockPos> dropped = droppedItemsScan(mining, ctx.world());
List<BlockPos> locs = locs2
.stream()
.distinct()
// remove any that are within loaded chunks that aren't actually what we want
.filter(pos -> world.getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock()) || dropped.contains(pos))
.filter(pos -> ctx.world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.getBlock(ctx, pos)) || dropped.contains(pos))
// remove any that are implausible to mine (encased in bedrock, or touching lava)
.filter(MineProcess::plausibleToBreak)
.filter(pos -> MineProcess.plausibleToBreak(ctx, pos))
.sorted(Comparator.comparingDouble(Helper.HELPER.playerFeet()::distanceSq))
.sorted(Comparator.comparingDouble(ctx.playerFeet()::distanceSq))
.collect(Collectors.toList());
if (locs.size() > max) {
@ -280,12 +269,12 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
return locs;
}
public static boolean plausibleToBreak(BlockPos pos) {
if (MovementHelper.avoidBreaking(new CalculationContext(), pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(pos))) {
public static boolean plausibleToBreak(IPlayerContext ctx, BlockPos pos) {
if (MovementHelper.avoidBreaking(new BlockStateInterface(ctx), pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(ctx, pos))) {
return false;
}
// bedrock above and below makes it implausible, otherwise we're good
return !(BlockStateInterface.getBlock(pos.up()) == Blocks.BEDROCK && BlockStateInterface.getBlock(pos.down()) == Blocks.BEDROCK);
return !(BlockStateInterface.getBlock(ctx, pos.up()) == Blocks.BEDROCK && BlockStateInterface.getBlock(ctx, pos.down()) == Blocks.BEDROCK);
}
@Override

View File

@ -22,6 +22,7 @@ import baritone.api.event.events.TickEvent;
import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.utils.IPlayerContext;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.settings.GameSettings;
@ -40,6 +41,8 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
private static final BlockPos STARTING_POSITION = new BlockPos(0, 65, 0);
private static final Goal GOAL = new GoalBlock(69, 121, 420);
private static final int MAX_TICKS = 3500;
private static final Baritone baritone = Baritone.INSTANCE;
private static final IPlayerContext ctx = baritone.getPlayerContext();
/**
* Called right after the {@link GameSettings} object is created in the {@link Minecraft} instance.
@ -101,15 +104,15 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
// Print out an update of our position every 5 seconds
if (event.getCount() % 100 == 0) {
System.out.println(playerFeet() + " " + event.getCount());
System.out.println(ctx.playerFeet() + " " + event.getCount());
}
// Setup Baritone's pathing goal and (if needed) begin pathing
Baritone.INSTANCE.getCustomGoalProcess().setGoalAndPath(GOAL);
baritone.getCustomGoalProcess().setGoalAndPath(GOAL);
// If we have reached our goal, print a message and safely close the game
if (GOAL.isInGoal(playerFeet())) {
System.out.println("Successfully pathed to " + playerFeet() + " in " + event.getCount() + " ticks");
if (GOAL.isInGoal(ctx.playerFeet())) {
System.out.println("Successfully pathed to " + ctx.playerFeet() + " in " + event.getCount() + " ticks");
mc.shutdown();
}

View File

@ -19,11 +19,14 @@ package baritone.utils;
import baritone.Baritone;
import baritone.api.process.IBaritoneProcess;
import baritone.api.utils.IPlayerContext;
public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper {
public static final double DEFAULT_PRIORITY = 0;
protected final Baritone baritone;
protected final IPlayerContext ctx;
private final double priority;
public BaritoneProcessHelper(Baritone baritone) {
@ -32,6 +35,7 @@ public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper
public BaritoneProcessHelper(Baritone baritone, double priority) {
this.baritone = baritone;
this.ctx = baritone.getPlayerContext();
this.priority = priority;
baritone.getPathingControlManager().registerProcess(this);
}

View File

@ -18,6 +18,8 @@
package baritone.utils;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.utils.IPlayerContext;
import baritone.cache.CachedRegion;
import baritone.cache.WorldData;
import baritone.pathing.movement.CalculationContext;
@ -33,33 +35,36 @@ import net.minecraft.world.chunk.Chunk;
*
* @author leijurv
*/
public class BlockStateInterface implements Helper {
public class BlockStateInterface {
private final World world;
private final WorldData worldData;
private Chunk prev = null;
private CachedRegion prevCached = null;
private static final IBlockState AIR = Blocks.AIR.getDefaultState();
public BlockStateInterface(IPlayerContext ctx) {
this(ctx.world(), (WorldData) ctx.worldData());
}
public BlockStateInterface(World world, WorldData worldData) {
this.worldData = worldData;
this.world = world;
}
public static Block getBlock(BlockPos pos) { // won't be called from the pathing thread because the pathing thread doesn't make a single blockpos pog
return get(pos).getBlock();
public static Block getBlock(IPlayerContext ctx, BlockPos pos) { // won't be called from the pathing thread because the pathing thread doesn't make a single blockpos pog
return get(ctx, pos).getBlock();
}
public static IBlockState get(BlockPos pos) {
return new CalculationContext().get(pos); // immense iq
public static IBlockState get(IPlayerContext ctx, BlockPos pos) {
return new BlockStateInterface(ctx).get0(pos.getX(), pos.getY(), pos.getZ()); // immense iq
// can't just do world().get because that doesn't work for out of bounds
// and toBreak and stuff fails when the movement is instantiated out of load range but it's not able to BlockStateInterface.get what it's going to walk on
}
public IBlockState get0(int x, int y, int z) {
public IBlockState get0(int x, int y, int z) { // Mickey resigned
// Invalid vertical position
if (y < 0 || y >= 256) {

View File

@ -30,7 +30,6 @@ import baritone.behavior.PathingBehavior;
import baritone.cache.ChunkPacker;
import baritone.cache.Waypoint;
import baritone.pathing.calc.AbstractNodeCostSearch;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.Moves;
import baritone.process.CustomGoalProcess;
@ -165,7 +164,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
try {
switch (params.length) {
case 0:
goal = new GoalBlock(playerFeet());
goal = new GoalBlock(ctx.playerFeet());
break;
case 1:
if (params[0].equals("clear") || params[0].equals("none")) {
@ -195,7 +194,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
if (msg.equals("path")) {
if (pathingBehavior.getGoal() == null) {
logDirect("No goal.");
} else if (pathingBehavior.getGoal().isInGoal(playerFeet())) {
} else if (pathingBehavior.getGoal().isInGoal(ctx.playerFeet())) {
logDirect("Already in goal");
} else if (pathingBehavior.isPathing()) {
logDirect("Currently executing a path. Please cancel it first.");
@ -205,9 +204,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true;
}
if (msg.equals("repack") || msg.equals("rescan")) {
ChunkProviderClient cli = world().getChunkProvider();
int playerChunkX = playerFeet().getX() >> 4;
int playerChunkZ = playerFeet().getZ() >> 4;
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++) {
@ -252,7 +251,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
} else {
logDirect("Goal must be GoalXZ or GoalBlock to invert");
logDirect("Inverting goal of player feet");
runAwayFrom = playerFeet();
runAwayFrom = ctx.playerFeet();
}
customGoalProcess.setGoalAndPath(new GoalRunAway(1, runAwayFrom) {
@Override
@ -273,9 +272,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
if (name.length() == 0) {
toFollow = RayTraceUtils.getSelectedEntity();
} else {
for (EntityPlayer pl : world().playerEntities) {
for (EntityPlayer pl : ctx.world().playerEntities) {
String theirName = pl.getName().trim().toLowerCase();
if (!theirName.equals(player().getName().trim().toLowerCase()) && (theirName.contains(name) || name.contains(theirName))) { // don't follow ourselves lol
if (!theirName.equals(ctx.player().getName().trim().toLowerCase()) && (theirName.contains(name) || name.contains(theirName))) { // don't follow ourselves lol
toFollow = Optional.of(pl);
}
}
@ -301,10 +300,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
}
if (msg.startsWith("find")) {
String blockType = msg.substring(4).trim();
LinkedList<BlockPos> locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, 4);
LinkedList<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 = BlockStateInterface.get(pos).getBlock();
Block actually = BlockStateInterface.get(ctx, pos).getBlock();
if (!ChunkPacker.blockToString(actually).equalsIgnoreCase(blockType)) {
System.out.println("Was looking for " + blockType + " but actually found " + actually + " " + ChunkPacker.blockToString(actually));
}
@ -334,7 +333,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
}
if (msg.startsWith("thisway")) {
try {
Goal goal = GoalXZ.fromDirection(playerFeetAsVec(), player().rotationYaw, Double.parseDouble(msg.substring(7).trim()));
Goal goal = GoalXZ.fromDirection(ctx.playerFeetAsVec(), ctx.player().rotationYaw, Double.parseDouble(msg.substring(7).trim()));
customGoalProcess.setGoal(goal);
logDirect("Goal: " + goal);
} catch (NumberFormatException ex) {
@ -365,7 +364,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
}
if (msg.startsWith("save")) {
String name = msg.substring(4).trim();
BlockPos pos = playerFeet();
BlockPos 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(" ");
@ -421,7 +420,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
if (msg.equals("spawn") || msg.equals("bed")) {
IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(Waypoint.Tag.BED);
if (waypoint == null) {
BlockPos spawnPoint = player().getBedLocation();
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);
@ -434,7 +433,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true;
}
if (msg.equals("sethome")) {
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", Waypoint.Tag.HOME, playerFeet()));
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", Waypoint.Tag.HOME, ctx.playerFeet()));
logDirect("Saved. Say home to set goal.");
return true;
}
@ -450,7 +449,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true;
}
if (msg.equals("costs")) {
List<Movement> moves = Stream.of(Moves.values()).map(x -> x.apply0(new CalculationContext(), playerFeet())).collect(Collectors.toCollection(ArrayList::new));
List<Movement> moves = Stream.of(Moves.values()).map(x -> x.apply0(baritone, ctx.playerFeet())).collect(Collectors.toCollection(ArrayList::new));
while (moves.contains(null)) {
moves.remove(null);
}

View File

@ -18,14 +18,7 @@
package baritone.utils;
import baritone.Baritone;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.Rotation;
import net.minecraft.block.BlockSlab;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
@ -51,48 +44,6 @@ public interface Helper {
Minecraft mc = Minecraft.getMinecraft();
default EntityPlayerSP player() {
if (!mc.isCallingFromMinecraftThread()) {
throw new IllegalStateException("h00000000");
}
return mc.player;
}
default PlayerControllerMP playerController() { // idk
if (!mc.isCallingFromMinecraftThread()) {
throw new IllegalStateException("h00000000");
}
return mc.playerController;
}
default WorldClient world() {
if (!mc.isCallingFromMinecraftThread()) {
throw new IllegalStateException("h00000000");
}
return mc.world;
}
default BetterBlockPos playerFeet() {
// TODO find a better way to deal with soul sand!!!!!
BetterBlockPos feet = new BetterBlockPos(player().posX, player().posY + 0.1251, player().posZ);
if (BlockStateInterface.get(feet).getBlock() instanceof BlockSlab) {
return feet.up();
}
return feet;
}
default Vec3d playerFeetAsVec() {
return new Vec3d(player().posX, player().posY, player().posZ);
}
default Vec3d playerHead() {
return new Vec3d(player().posX, player().posY + player().getEyeHeight(), player().posZ);
}
default Rotation playerRotations() {
return new Rotation(player().rotationYaw, player().rotationPitch);
}
/**
* Send a message to chat only if chatDebug is on
*

View File

@ -19,11 +19,12 @@ package baritone.utils;
import baritone.Baritone;
import baritone.api.event.events.TickEvent;
import baritone.api.utils.IInputOverrideHandler;
import baritone.api.utils.input.Input;
import baritone.behavior.Behavior;
import net.minecraft.client.settings.KeyBinding;
import org.lwjgl.input.Keyboard;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@ -35,7 +36,7 @@ import java.util.Map;
* @author Brady
* @since 7/31/2018 11:20 PM
*/
public final class InputOverrideHandler extends Behavior implements Helper {
public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler {
/**
* Maps inputs to whether or not we are forcing their state down.
@ -52,6 +53,7 @@ public final class InputOverrideHandler extends Behavior implements Helper {
* @param key The KeyBinding object
* @return Whether or not it is being forced down
*/
@Override
public final boolean isInputForcedDown(KeyBinding key) {
return isInputForcedDown(Input.getInputForBind(key));
}
@ -62,6 +64,7 @@ public final class InputOverrideHandler extends Behavior implements Helper {
* @param input The input
* @return Whether or not it is being forced down
*/
@Override
public final boolean isInputForcedDown(Input input) {
return input == null ? false : this.inputForceStateMap.getOrDefault(input, false);
}
@ -72,6 +75,7 @@ public final class InputOverrideHandler extends Behavior implements Helper {
* @param input The {@link Input}
* @param forced Whether or not the state is being forced
*/
@Override
public final void setInputForceState(Input input, boolean forced) {
this.inputForceStateMap.put(input, forced);
}
@ -79,6 +83,7 @@ public final class InputOverrideHandler extends Behavior implements Helper {
/**
* Clears the override state for all keys
*/
@Override
public final void clearAllKeys() {
this.inputForceStateMap.clear();
}
@ -86,7 +91,7 @@ public final class InputOverrideHandler extends Behavior implements Helper {
@Override
public final void onProcessKeyBinds() {
// Simulate the key being held down this tick
for (InputOverrideHandler.Input input : Input.values()) {
for (Input input : Input.values()) {
KeyBinding keyBinding = input.getKeyBinding();
if (isInputForcedDown(keyBinding) && !keyBinding.isKeyDown()) {
@ -105,92 +110,8 @@ public final class InputOverrideHandler extends Behavior implements Helper {
return;
}
if (Baritone.settings().leftClickWorkaround.get()) {
boolean stillClick = BlockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.keyBinding));
boolean stillClick = BlockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.getKeyBinding()));
setInputForceState(Input.CLICK_LEFT, stillClick);
}
}
/**
* An {@link Enum} representing the inputs that control the player's
* behavior. This includes moving, interacting with blocks, jumping,
* sneaking, and sprinting.
*/
public enum Input {
/**
* The move forward input
*/
MOVE_FORWARD(mc.gameSettings.keyBindForward),
/**
* The move back input
*/
MOVE_BACK(mc.gameSettings.keyBindBack),
/**
* The move left input
*/
MOVE_LEFT(mc.gameSettings.keyBindLeft),
/**
* The move right input
*/
MOVE_RIGHT(mc.gameSettings.keyBindRight),
/**
* The attack input
*/
CLICK_LEFT(mc.gameSettings.keyBindAttack),
/**
* The use item input
*/
CLICK_RIGHT(mc.gameSettings.keyBindUseItem),
/**
* The jump input
*/
JUMP(mc.gameSettings.keyBindJump),
/**
* The sneak input
*/
SNEAK(mc.gameSettings.keyBindSneak),
/**
* The sprint input
*/
SPRINT(mc.gameSettings.keyBindSprint);
/**
* Map of {@link KeyBinding} to {@link Input}. Values should be queried through {@link #getInputForBind(KeyBinding)}
*/
private static final Map<KeyBinding, Input> bindToInputMap = new HashMap<>();
/**
* The actual game {@link KeyBinding} being forced.
*/
private final KeyBinding keyBinding;
Input(KeyBinding keyBinding) {
this.keyBinding = keyBinding;
}
/**
* @return The actual game {@link KeyBinding} being forced.
*/
public final KeyBinding getKeyBinding() {
return this.keyBinding;
}
/**
* Finds the {@link Input} constant that is associated with the specified {@link KeyBinding}.
*
* @param binding The {@link KeyBinding} to find the associated {@link Input} for
* @return The {@link Input} associated with the specified {@link KeyBinding}
*/
public static Input getInputForBind(KeyBinding binding) {
return bindToInputMap.computeIfAbsent(binding, b -> Arrays.stream(values()).filter(input -> input.keyBinding == b).findFirst().orElse(null));
}
}
}

View File

@ -206,7 +206,7 @@ public final class PathRenderer implements Helper {
double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks;
double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks;
positions.forEach(pos -> {
IBlockState state = BlockStateInterface.get(pos);
IBlockState state = BlockStateInterface.get(Baritone.INSTANCE.getPlayerContext(), pos);
AxisAlignedBB toDraw;
if (state.getBlock().equals(Blocks.AIR)) {
toDraw = Blocks.DIRT.getDefaultState().getSelectedBoundingBox(Minecraft.getMinecraft().world, pos);

View File

@ -0,0 +1,61 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils.player;
import baritone.Baritone;
import baritone.api.cache.IWorldData;
import baritone.api.utils.IPlayerContext;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.world.World;
/**
* Implementation of {@link IPlayerContext} that provides information about the local player.
*
* @author Brady
* @since 11/12/2018
*/
public final class LocalPlayerContext implements IPlayerContext {
private static final Minecraft mc = Minecraft.getMinecraft();
public static final LocalPlayerContext INSTANCE = new LocalPlayerContext();
private LocalPlayerContext() {}
@Override
public EntityPlayerSP player() {
return mc.player;
}
@Override
public PlayerControllerMP playerController() {
return mc.playerController;
}
@Override
public World world() {
return mc.world;
}
@Override
public IWorldData worldData() {
return Baritone.INSTANCE.getWorldProvider().getCurrentWorld();
}
}