Utilize Optional return types where mostly applicable

This commit is contained in:
Brady 2018-08-06 02:21:47 -05:00
parent 091c19ca72
commit e8149f166f
No known key found for this signature in database
GPG Key ID: 73A788379A197567
5 changed files with 64 additions and 66 deletions

View File

@ -28,6 +28,7 @@ import org.lwjgl.opengl.GL11;
import java.awt.*; import java.awt.*;
import java.util.List; import java.util.List;
import java.util.Optional;
public class PathingBehavior extends Behavior { public class PathingBehavior extends Behavior {
@ -55,11 +56,8 @@ public class PathingBehavior extends Behavior {
return current; return current;
} }
public IPath getPath() { public Optional<IPath> getPath() {
if (current == null) { return Optional.ofNullable(current).map(PathExecutor::getPath);
return null;
}
return current.getPath();
} }
@Override @Override
@ -92,10 +90,7 @@ public class PathingBehavior extends Behavior {
} }
try { try {
IPath path = findPath(start); findPath(start).map(PathExecutor::new).ifPresent(path -> current = path);
if (path != null) {
current = new PathExecutor(path);
}
} catch (Exception ignored) {} } catch (Exception ignored) {}
/*isThereAnythingInProgress = false; /*isThereAnythingInProgress = false;
if (!currentPath.goal.isInGoal(currentPath.end)) { if (!currentPath.goal.isInGoal(currentPath.end)) {
@ -115,18 +110,17 @@ public class PathingBehavior extends Behavior {
* @param start * @param start
* @return * @return
*/ */
private IPath findPath(BlockPos start) { private Optional<IPath> findPath(BlockPos start) {
if (goal == null) { if (goal == null) {
displayChatMessageRaw("no goal"); displayChatMessageRaw("no goal");
return null; return Optional.empty();
} }
try { try {
IPathFinder pf = new AStarPathFinder(start, goal); IPathFinder pf = new AStarPathFinder(start, goal);
IPath path = pf.calculate(); return pf.calculate();
return path;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return Optional.empty();
} }
} }
@ -134,22 +128,21 @@ public class PathingBehavior extends Behavior {
public void onRenderPass(RenderEvent event) { public void onRenderPass(RenderEvent event) {
//System.out.println("Render passing"); //System.out.println("Render passing");
//System.out.println(event.getPartialTicks()); //System.out.println(event.getPartialTicks());
IPath path = getPath();
float partialTicks = event.getPartialTicks(); float partialTicks = event.getPartialTicks();
if (path != null) {
drawPath(path, player(), partialTicks, Color.RED); // Render the current path, if there is one
} getPath().ifPresent(path -> drawPath(path, player(), partialTicks, Color.RED));
if (AbstractNodeCostSearch.currentlyRunning != null) {
IPath p = AbstractNodeCostSearch.currentlyRunning.bestPathSoFar(); // If there is a path calculation currently running, render the path calculation process
if (p != null) { AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(currentlyRunning -> {
currentlyRunning.bestPathSoFar().ifPresent(p -> {
drawPath(p, player(), partialTicks, Color.BLUE); drawPath(p, player(), partialTicks, Color.BLUE);
IPath mr = AbstractNodeCostSearch.currentlyRunning.pathToMostRecentNodeConsidered(); currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> {
if (mr != null) {
drawPath(mr, player(), partialTicks, Color.CYAN); drawPath(mr, player(), partialTicks, Color.CYAN);
drawSelectionBox(player(), mr.getDest(), partialTicks, Color.CYAN); drawSelectionBox(player(), mr.getDest(), partialTicks, Color.CYAN);
} });
} });
} });
} }
public void drawPath(IPath path, EntityPlayerSP player, float partialTicks, Color color) { public void drawPath(IPath path, EntityPlayerSP player, float partialTicks, Color color) {

View File

@ -13,6 +13,7 @@ import net.minecraft.client.Minecraft;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.EmptyChunk; import net.minecraft.world.chunk.EmptyChunk;
import java.util.Optional;
import java.util.Random; import java.util.Random;
/** /**
@ -21,12 +22,13 @@ import java.util.Random;
* @author leijurv * @author leijurv
*/ */
public class AStarPathFinder extends AbstractNodeCostSearch { public class AStarPathFinder extends AbstractNodeCostSearch {
public AStarPathFinder(BlockPos start, Goal goal) { public AStarPathFinder(BlockPos start, Goal goal) {
super(start, goal); super(start, goal);
} }
@Override @Override
protected IPath calculate0() { protected Optional<IPath> calculate0() {
startNode = getNodeAtPosition(start); startNode = getNodeAtPosition(start);
startNode.cost = 0; startNode.cost = 0;
startNode.combinedCost = startNode.estimatedCostToGoal; startNode.combinedCost = startNode.estimatedCostToGoal;
@ -64,7 +66,7 @@ public class AStarPathFinder extends AbstractNodeCostSearch {
} }
if (goal.isInGoal(currentNodePos)) { if (goal.isInGoal(currentNodePos)) {
currentlyRunning = null; currentlyRunning = null;
return new Path(startNode, currentNode, goal); return Optional.of(new Path(startNode, currentNode, goal));
} }
//long constructStart = System.nanoTime(); //long constructStart = System.nanoTime();
Movement[] possibleMovements = getConnectedPositions(currentNodePos);//movement that we could take that start at myPos, in random order Movement[] possibleMovements = getConnectedPositions(currentNodePos);//movement that we could take that start at myPos, in random order
@ -125,13 +127,13 @@ public class AStarPathFinder extends AbstractNodeCostSearch {
} }
System.out.println("Path goes for " + dist + " blocks"); System.out.println("Path goes for " + dist + " blocks");
currentlyRunning = null; currentlyRunning = null;
return new Path(startNode, bestSoFar[i], goal); return Optional.of(new Path(startNode, bestSoFar[i], goal));
} }
} }
System.out.println("Even with a cost coefficient of " + COEFFICIENTS[COEFFICIENTS.length - 1] + ", I couldn't get more than " + bestDist + " blocks =("); System.out.println("Even with a cost coefficient of " + COEFFICIENTS[COEFFICIENTS.length - 1] + ", I couldn't get more than " + bestDist + " blocks =(");
System.out.println("No path found =("); System.out.println("No path found =(");
currentlyRunning = null; currentlyRunning = null;
return null; return Optional.empty();
} }

View File

@ -6,6 +6,7 @@ import net.minecraft.util.math.BlockPos;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
/** /**
* Any pathfinding algorithm that keeps track of nodes recursively by their cost (e.g. A*, dijkstra) * Any pathfinding algorithm that keeps track of nodes recursively by their cost (e.g. A*, dijkstra)
@ -16,10 +17,8 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
/** /**
* The currently running search task * The currently running search task
* <p>
* TODO: This shouldn't be necessary, investigate old purpose of this field and determine necessity.
*/ */
public static AbstractNodeCostSearch currentlyRunning = null; protected static AbstractNodeCostSearch currentlyRunning = null;
protected final BlockPos start; protected final BlockPos start;
@ -53,16 +52,16 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
this.map = new HashMap<>(); this.map = new HashMap<>();
} }
public synchronized IPath calculate() { public synchronized Optional<IPath> calculate() {
if (isFinished) { if (isFinished) {
throw new IllegalStateException("Path Finder is currently in use! Wait until complete to reuse!"); throw new IllegalStateException("Path Finder is currently in use! Wait until complete to reuse!");
} }
IPath path = calculate0(); Optional<IPath> path = calculate0();
isFinished = true; isFinished = true;
return path; return path;
} }
protected abstract IPath calculate0(); protected abstract Optional<IPath> calculate0();
/** /**
* Determines the distance squared from the specified node to the start * Determines the distance squared from the specified node to the start
@ -103,16 +102,16 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
} }
@Override @Override
public IPath bestPathSoFar() { public Optional<IPath> pathToMostRecentNodeConsidered() {
if (startNode == null || bestSoFar[0] == null) { return Optional.ofNullable(mostRecentConsidered).map(node -> new Path(startNode, node, goal));
return null;
}
return new Path(startNode, bestSoFar[0], goal);
} }
@Override @Override
public IPath pathToMostRecentNodeConsidered() { public Optional<IPath> bestPathSoFar() {
return mostRecentConsidered == null ? null : new Path(startNode, mostRecentConsidered, goal); if (startNode == null || bestSoFar[0] == null)
return Optional.empty();
return Optional.of(new Path(startNode, bestSoFar[0], goal));
} }
@Override @Override
@ -129,4 +128,8 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
public final BlockPos getStart() { public final BlockPos getStart() {
return start; return start;
} }
public static Optional<AbstractNodeCostSearch> getCurrentlyRunning() {
return Optional.ofNullable(currentlyRunning);
}
} }

View File

@ -4,6 +4,8 @@ import baritone.bot.pathing.goals.Goal;
import baritone.bot.pathing.path.IPath; import baritone.bot.pathing.path.IPath;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import java.util.Optional;
/** /**
* Generic path finder interface * Generic path finder interface
* *
@ -20,7 +22,7 @@ public interface IPathFinder {
* *
* @return The final path * @return The final path
*/ */
IPath calculate(); Optional<IPath> calculate();
/** /**
* Intended to be called concurrently with calculatePath from a different thread to tell if it's finished yet * Intended to be called concurrently with calculatePath from a different thread to tell if it's finished yet
@ -34,7 +36,7 @@ public interface IPathFinder {
* *
* @return The temporary path * @return The temporary path
*/ */
IPath pathToMostRecentNodeConsidered(); Optional<IPath> pathToMostRecentNodeConsidered();
/** /**
* The best path so far, according to the most forgiving coefficient heuristic (the reason being that that path is * The best path so far, according to the most forgiving coefficient heuristic (the reason being that that path is
@ -44,5 +46,5 @@ public interface IPathFinder {
* *
* @return The temporary path * @return The temporary path
*/ */
IPath bestPathSoFar(); Optional<IPath> bestPathSoFar();
} }

View File

@ -11,6 +11,8 @@ import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
import java.util.Optional;
/** /**
* Static helpers for cost calculation * Static helpers for cost calculation
* *
@ -153,41 +155,38 @@ public interface MovementHelper extends ActionCosts, Helper {
* The currently highlighted block. * The currently highlighted block.
* Updated once a tick by Minecraft. * Updated once a tick by Minecraft.
* *
* @return the position of the highlighted block, or null if no block is highlighted * @return the position of the highlighted block
*/ */
static BlockPos whatAmILookingAt() { static Optional<BlockPos> whatAmILookingAt() {
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) { if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) {
return mc.objectMouseOver.getBlockPos(); return Optional.of(mc.objectMouseOver.getBlockPos());
} }
return null; return Optional.empty();
} }
/** /**
* The entity the player is currently looking at * The entity the player is currently looking at
* *
* @return the entity object, or null if the player isn't looking at an entity * @return the entity object
*/ */
static Entity whatEntityAmILookingAt() { static Optional<Entity> whatEntityAmILookingAt() {
Minecraft mc = Minecraft.getMinecraft();
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.ENTITY) { if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.ENTITY) {
return mc.objectMouseOver.entityHit; return Optional.of(mc.objectMouseOver.entityHit);
} }
return null; return Optional.empty();
} }
/** /**
* AutoTool * AutoTool
*/ */
static void switchToBestTool() { static void switchToBestTool() {
BlockPos pos = whatAmILookingAt(); whatAmILookingAt().ifPresent(pos -> {
if (pos == null) {
return;
}
IBlockState state = BlockStateInterface.get(pos); IBlockState state = BlockStateInterface.get(pos);
if (state.getBlock().equals(Blocks.AIR)) { if (state.getBlock().equals(Blocks.AIR)) {
return; return;
} }
switchToBestToolFor(state); switchToBestToolFor(state);
});
} }
/** /**
@ -206,11 +205,10 @@ public interface MovementHelper extends ActionCosts, Helper {
* @param ts previously calculated ToolSet * @param ts previously calculated ToolSet
*/ */
static void switchToBestToolFor(IBlockState b, ToolSet ts) { static void switchToBestToolFor(IBlockState b, ToolSet ts) {
Minecraft.getMinecraft().player.inventory.currentItem = ts.getBestSlot(b); mc.player.inventory.currentItem = ts.getBestSlot(b);
} }
static boolean isAir(BlockPos pos) { static boolean isAir(BlockPos pos) {
return BlockStateInterface.get(pos).getBlock().equals(Blocks.AIR); return BlockStateInterface.get(pos).getBlock().equals(Blocks.AIR);
} }
} }