mirror of
https://github.com/LeavesMC/Leaves.git
synced 2025-12-21 07:49:35 +00:00
1181 lines
53 KiB
Diff
1181 lines
53 KiB
Diff
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
|
From: violetc <58360096+s-yh-china@users.noreply.github.com>
|
|
Date: Wed, 17 Aug 2022 16:54:54 +0800
|
|
Subject: [PATCH] Async Pathfinding
|
|
|
|
This patch is Powered by Pufferfish(https://github.com/pufferfish-gg/Pufferfish)
|
|
But Pufferfish patch was ported downstream from the Petal fork
|
|
|
|
diff --git a/src/main/java/net/minecraft/world/entity/ai/behavior/AcquirePoi.java b/src/main/java/net/minecraft/world/entity/ai/behavior/AcquirePoi.java
|
|
index 7d8a137068ab2b33690c369f4da46e90b5f98e2e..5052ac5da62d3094b8f495a2a6825c2bd5a94905 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/ai/behavior/AcquirePoi.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/ai/behavior/AcquirePoi.java
|
|
@@ -93,27 +93,60 @@ public class AcquirePoi extends Behavior<PathfinderMob> {
|
|
io.papermc.paper.util.PoiAccess.findNearestPoiPositions(poiManager, this.poiType, predicate, entity.blockPosition(), 48, 48*48, PoiManager.Occupancy.HAS_SPACE, false, 5, poiposes);
|
|
Set<Pair<Holder<PoiType>, BlockPos>> set = new java.util.HashSet<>(poiposes);
|
|
// Paper end - optimise POI access
|
|
- Path path = findPathToPois(entity, set);
|
|
- if (path != null && path.canReach()) {
|
|
- BlockPos blockPos = path.getTarget();
|
|
- poiManager.getType(blockPos).ifPresent((holder) -> {
|
|
- poiManager.take(this.poiType, (holderx, blockPos2) -> {
|
|
- return blockPos2.equals(blockPos);
|
|
- }, blockPos, 1);
|
|
- entity.getBrain().setMemory(this.memoryToAcquire, GlobalPos.of(world.dimension(), blockPos));
|
|
- this.onPoiAcquisitionEvent.ifPresent((byte_) -> {
|
|
- world.broadcastEntityEvent(entity, byte_);
|
|
+ // Leaves start - await on path async
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding) {
|
|
+ Path possiblePath = findPathToPois(entity, set);
|
|
+
|
|
+ // Leaves - wait on the path to be processed
|
|
+ top.leavesmc.leaves.path.AsyncPathProcessor.awaitProcessing(possiblePath, path -> {
|
|
+ // Leaves - readd canReach check
|
|
+ if (path == null || !path.canReach()) {
|
|
+ for(Pair<Holder<PoiType>, BlockPos> pair : set) {
|
|
+ this.batchCache.computeIfAbsent(pair.getSecond().asLong(), (m) -> {
|
|
+ return new AcquirePoi.JitteredLinearRetry(entity.level.random, time);
|
|
+ });
|
|
+ }
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ BlockPos blockPos = path.getTarget();
|
|
+ poiManager.getType(blockPos).ifPresent((holder) -> {
|
|
+ poiManager.take(this.poiType, (holderx, blockPos2) -> {
|
|
+ return blockPos2.equals(blockPos);
|
|
+ }, blockPos, 1);
|
|
+ entity.getBrain().setMemory(this.memoryToAcquire, GlobalPos.of(world.dimension(), blockPos));
|
|
+ this.onPoiAcquisitionEvent.ifPresent((byte_) -> {
|
|
+ world.broadcastEntityEvent(entity, byte_);
|
|
+ });
|
|
+ this.batchCache.clear();
|
|
+ DebugPackets.sendPoiTicketCountPacket(world, blockPos);
|
|
});
|
|
- this.batchCache.clear();
|
|
- DebugPackets.sendPoiTicketCountPacket(world, blockPos);
|
|
});
|
|
} else {
|
|
- for(Pair<Holder<PoiType>, BlockPos> pair : set) {
|
|
- this.batchCache.computeIfAbsent(pair.getSecond().asLong(), (m) -> {
|
|
- return new AcquirePoi.JitteredLinearRetry(entity.level.random, time);
|
|
+ Path path = findPathToPois(entity, set);
|
|
+ if (path != null && path.canReach()) {
|
|
+ BlockPos blockPos = path.getTarget();
|
|
+ poiManager.getType(blockPos).ifPresent((holder) -> {
|
|
+ poiManager.take(this.poiType, (holderx, blockPos2) -> {
|
|
+ return blockPos2.equals(blockPos);
|
|
+ }, blockPos, 1);
|
|
+ entity.getBrain().setMemory(this.memoryToAcquire, GlobalPos.of(world.dimension(), blockPos));
|
|
+ this.onPoiAcquisitionEvent.ifPresent((byte_) -> {
|
|
+ world.broadcastEntityEvent(entity, byte_);
|
|
+ });
|
|
+ this.batchCache.clear();
|
|
+ DebugPackets.sendPoiTicketCountPacket(world, blockPos);
|
|
});
|
|
+ } else {
|
|
+ for(Pair<Holder<PoiType>, BlockPos> pair : set) {
|
|
+ this.batchCache.computeIfAbsent(pair.getSecond().asLong(), (m) -> {
|
|
+ return new AcquirePoi.JitteredLinearRetry(entity.level.random, time);
|
|
+ });
|
|
+ }
|
|
}
|
|
}
|
|
+
|
|
+ // Leaves end - await on path async
|
|
|
|
}
|
|
|
|
diff --git a/src/main/java/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java b/src/main/java/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java
|
|
index 18364ce4c60172529b10bc9e3a813dcedc4b766f..c6fffe29c488126aa9f4ffdba13bc5dabd8148eb 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java
|
|
@@ -21,6 +21,7 @@ public class MoveToTargetSink extends Behavior<Mob> {
|
|
private int remainingCooldown;
|
|
@Nullable
|
|
private Path path;
|
|
+ private boolean finishedProcessing; // Leaves
|
|
@Nullable
|
|
private BlockPos lastTargetPos;
|
|
private float speedModifier;
|
|
@@ -42,9 +43,10 @@ public class MoveToTargetSink extends Behavior<Mob> {
|
|
Brain<?> brain = entity.getBrain();
|
|
WalkTarget walkTarget = brain.getMemory(MemoryModuleType.WALK_TARGET).get();
|
|
boolean bl = this.reachedTarget(entity, walkTarget);
|
|
- if (!bl && this.tryComputePath(entity, walkTarget, world.getGameTime())) {
|
|
+ if (!bl && (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding && this.tryComputePath(entity, walkTarget, world.getGameTime()))) { // Leaves
|
|
this.lastTargetPos = walkTarget.getTarget().currentBlockPosition();
|
|
return true;
|
|
+ } else if (!bl) { return true; // Leaves
|
|
} else {
|
|
brain.eraseMemory(MemoryModuleType.WALK_TARGET);
|
|
if (bl) {
|
|
@@ -58,6 +60,7 @@ public class MoveToTargetSink extends Behavior<Mob> {
|
|
|
|
@Override
|
|
protected boolean canStillUse(ServerLevel serverLevel, Mob mob, long l) {
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding && !finishedProcessing) return true; // Leaves - wait for path to process
|
|
if (this.path != null && this.lastTargetPos != null) {
|
|
Optional<WalkTarget> optional = mob.getBrain().getMemory(MemoryModuleType.WALK_TARGET);
|
|
PathNavigation pathNavigation = mob.getNavigation();
|
|
@@ -81,28 +84,96 @@ public class MoveToTargetSink extends Behavior<Mob> {
|
|
|
|
@Override
|
|
protected void start(ServerLevel serverLevel, Mob mob, long l) {
|
|
+ if (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding) { // Leaves
|
|
mob.getBrain().setMemory(MemoryModuleType.PATH, this.path);
|
|
mob.getNavigation().moveTo(this.path, (double)this.speedModifier);
|
|
+ // Leaves start
|
|
+ } else {
|
|
+ Brain<?> brain = mob.getBrain();
|
|
+ WalkTarget walkTarget = brain.getMemory(MemoryModuleType.WALK_TARGET).get();
|
|
+
|
|
+ this.finishedProcessing = false;
|
|
+ this.lastTargetPos = walkTarget.getTarget().currentBlockPosition();
|
|
+ this.path = this.computePath(mob, walkTarget);
|
|
+ }
|
|
+ // Leaves end
|
|
}
|
|
|
|
@Override
|
|
protected void tick(ServerLevel world, Mob entity, long time) {
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding && this.path != null && !this.path.isProcessed()) return; // Leaves - wait for processing
|
|
+
|
|
+ // Leaves start
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding && !finishedProcessing) {
|
|
+ this.finishedProcessing = true;
|
|
+ Brain<?> brain = entity.getBrain();
|
|
+ boolean canReach = this.path != null && this.path.canReach();
|
|
+ if (canReach) {
|
|
+ brain.eraseMemory(MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE);
|
|
+ } else if (brain.hasMemoryValue(MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE)) {
|
|
+ brain.setMemory(MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE, time);
|
|
+ }
|
|
+
|
|
+ if (!canReach) {
|
|
+ Optional<WalkTarget> walkTarget = brain.getMemory(MemoryModuleType.WALK_TARGET);
|
|
+
|
|
+ if (walkTarget.isPresent()) {
|
|
+ BlockPos blockPos = walkTarget.get().getTarget().currentBlockPosition();
|
|
+ Vec3 vec3 = DefaultRandomPos.getPosTowards((PathfinderMob)entity, 10, 7, Vec3.atBottomCenterOf(blockPos), (double)((float)Math.PI / 2F));
|
|
+ if (vec3 != null) {
|
|
+ // try recalculating the path using a random position
|
|
+ this.path = entity.getNavigation().createPath(vec3.x, vec3.y, vec3.z, 0);
|
|
+ this.finishedProcessing = false;
|
|
+ return;
|
|
+ }
|
|
+ }
|
|
+
|
|
+ brain.eraseMemory(MemoryModuleType.WALK_TARGET);
|
|
+ this.path = null;
|
|
+
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ entity.getBrain().setMemory(MemoryModuleType.PATH, this.path);
|
|
+ entity.getNavigation().moveTo(this.path, (double)this.speedModifier);
|
|
+ }
|
|
+ // Leaves end
|
|
+
|
|
Path path = entity.getNavigation().getPath();
|
|
Brain<?> brain = entity.getBrain();
|
|
- if (this.path != path) {
|
|
+ if (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding && this.path != path) { // Leaves
|
|
this.path = path;
|
|
brain.setMemory(MemoryModuleType.PATH, path);
|
|
}
|
|
|
|
- if (path != null && this.lastTargetPos != null) {
|
|
+ if (path != null && this.lastTargetPos != null && (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding || brain.hasMemoryValue(MemoryModuleType.WALK_TARGET))) { // Leaves
|
|
WalkTarget walkTarget = brain.getMemory(MemoryModuleType.WALK_TARGET).get();
|
|
+ if (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding) { // Leaves
|
|
if (walkTarget.getTarget().currentBlockPosition().distSqr(this.lastTargetPos) > 4.0D && this.tryComputePath(entity, walkTarget, world.getGameTime())) {
|
|
this.lastTargetPos = walkTarget.getTarget().currentBlockPosition();
|
|
this.start(world, entity, time);
|
|
}
|
|
+ // Leaves start
|
|
+ } else {
|
|
+ if (walkTarget.getTarget().currentBlockPosition().distSqr(this.lastTargetPos) > 4.0D) this.start(world, entity, time);
|
|
+ }
|
|
+ // Leaves end
|
|
+
|
|
+ }
|
|
+ }
|
|
|
|
+ // Leaves start
|
|
+ private Path computePath(Mob entity, WalkTarget walkTarget) {
|
|
+ BlockPos blockPos = walkTarget.getTarget().currentBlockPosition();
|
|
+ this.speedModifier = walkTarget.getSpeedModifier();
|
|
+ Brain<?> brain = entity.getBrain();
|
|
+ if (this.reachedTarget(entity, walkTarget)) {
|
|
+ brain.eraseMemory(MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE);
|
|
}
|
|
+
|
|
+ return entity.getNavigation().createPath(blockPos, 0);
|
|
}
|
|
+ // Leaves end
|
|
|
|
private boolean tryComputePath(Mob entity, WalkTarget walkTarget, long time) {
|
|
BlockPos blockPos = walkTarget.getTarget().currentBlockPosition();
|
|
diff --git a/src/main/java/net/minecraft/world/entity/ai/behavior/SetClosestHomeAsWalkTarget.java b/src/main/java/net/minecraft/world/entity/ai/behavior/SetClosestHomeAsWalkTarget.java
|
|
index 9bd6d4f7b86daaaa9cfbad454dde06b797e3f667..7b0e66fcecfc18c77146fcc75e7977cdb8810226 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/ai/behavior/SetClosestHomeAsWalkTarget.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/ai/behavior/SetClosestHomeAsWalkTarget.java
|
|
@@ -71,19 +71,41 @@ public class SetClosestHomeAsWalkTarget extends Behavior<LivingEntity> {
|
|
Set<Pair<Holder<PoiType>, BlockPos>> set = poiManager.findAllWithType((poiType) -> {
|
|
return poiType.is(PoiTypes.HOME);
|
|
}, predicate, entity.blockPosition(), 48, PoiManager.Occupancy.ANY).collect(Collectors.toSet());
|
|
- Path path = AcquirePoi.findPathToPois(pathfinderMob, set);
|
|
- if (path != null && path.canReach()) {
|
|
- BlockPos blockPos = path.getTarget();
|
|
- Optional<Holder<PoiType>> optional = poiManager.getType(blockPos);
|
|
- if (optional.isPresent()) {
|
|
- entity.getBrain().setMemory(MemoryModuleType.WALK_TARGET, new WalkTarget(blockPos, this.speedModifier, 1));
|
|
- DebugPackets.sendPoiTicketCountPacket(world, blockPos);
|
|
- }
|
|
- } else if (this.triedCount < 5) {
|
|
- this.batchCache.long2LongEntrySet().removeIf((entry) -> {
|
|
- return entry.getLongValue() < this.lastUpdate;
|
|
+ // Leaves start - await on path async
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding) {
|
|
+ Path possiblePath = AcquirePoi.findPathToPois(pathfinderMob, set);
|
|
+
|
|
+ // Leaves - wait on the path to be processed
|
|
+ top.leavesmc.leaves.path.AsyncPathProcessor.awaitProcessing(possiblePath, path -> {
|
|
+ if (path == null || !path.canReach() || this.triedCount < 5) { // Leaves - readd canReach check
|
|
+ this.batchCache.long2LongEntrySet().removeIf((entry) -> {
|
|
+ return entry.getLongValue() < this.lastUpdate;
|
|
+ });
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ BlockPos blockPos = path.getTarget();
|
|
+ Optional<Holder<PoiType>> optional = poiManager.getType(blockPos);
|
|
+ if (optional.isPresent()) {
|
|
+ entity.getBrain().setMemory(MemoryModuleType.WALK_TARGET, new WalkTarget(blockPos, this.speedModifier, 1));
|
|
+ DebugPackets.sendPoiTicketCountPacket(world, blockPos);
|
|
+ }
|
|
});
|
|
+ } else {
|
|
+ Path path = AcquirePoi.findPathToPois(pathfinderMob, set);
|
|
+ if (path != null && path.canReach()) {
|
|
+ BlockPos blockPos = path.getTarget();
|
|
+ Optional<Holder<PoiType>> optional = poiManager.getType(blockPos);
|
|
+ if (optional.isPresent()) {
|
|
+ entity.getBrain().setMemory(MemoryModuleType.WALK_TARGET, new WalkTarget(blockPos, this.speedModifier, 1));
|
|
+ DebugPackets.sendPoiTicketCountPacket(world, blockPos);
|
|
+ }
|
|
+ } else if (this.triedCount < 5) {
|
|
+ this.batchCache.long2LongEntrySet().removeIf((entry) -> {
|
|
+ return entry.getLongValue() < this.lastUpdate;
|
|
+ });
|
|
+ }
|
|
}
|
|
-
|
|
+ // Leaves end - await on path async
|
|
}
|
|
}
|
|
diff --git a/src/main/java/net/minecraft/world/entity/ai/navigation/AmphibiousPathNavigation.java b/src/main/java/net/minecraft/world/entity/ai/navigation/AmphibiousPathNavigation.java
|
|
index 29a872393f2f995b13b4ed26b42c6464ab27ca73..a60195bbe6c59bca707ef202c5ee49b6dbf32704 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/ai/navigation/AmphibiousPathNavigation.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/ai/navigation/AmphibiousPathNavigation.java
|
|
@@ -8,6 +8,14 @@ import net.minecraft.world.level.pathfinder.PathFinder;
|
|
import net.minecraft.world.phys.Vec3;
|
|
|
|
public class AmphibiousPathNavigation extends PathNavigation {
|
|
+ // Leaves start
|
|
+ private static final top.leavesmc.leaves.path.NodeEvaluatorGenerator nodeEvaluatorGenerator = () -> {
|
|
+ var nodeEvaluator = new AmphibiousNodeEvaluator(false);
|
|
+ nodeEvaluator.setCanPassDoors(true);
|
|
+ return nodeEvaluator;
|
|
+ };
|
|
+ // Leaves end
|
|
+
|
|
public AmphibiousPathNavigation(Mob mob, Level world) {
|
|
super(mob, world);
|
|
}
|
|
@@ -16,7 +24,13 @@ public class AmphibiousPathNavigation extends PathNavigation {
|
|
protected PathFinder createPathFinder(int range) {
|
|
this.nodeEvaluator = new AmphibiousNodeEvaluator(false);
|
|
this.nodeEvaluator.setCanPassDoors(true);
|
|
- return new PathFinder(this.nodeEvaluator, range);
|
|
+ // Leaves start
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding) {
|
|
+ return new PathFinder(this.nodeEvaluator, range, nodeEvaluatorGenerator);
|
|
+ } else {
|
|
+ return new PathFinder(this.nodeEvaluator, range);
|
|
+ }
|
|
+ // Leaves end
|
|
}
|
|
|
|
@Override
|
|
diff --git a/src/main/java/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java b/src/main/java/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java
|
|
index 27cd393e81f6ef9b5690c051624d8d2af50acd34..87f5fd2c616fbb4e0a3c2f9af49f8c0a866fbc86 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java
|
|
@@ -12,6 +12,15 @@ import net.minecraft.world.level.pathfinder.PathFinder;
|
|
import net.minecraft.world.phys.Vec3;
|
|
|
|
public class FlyingPathNavigation extends PathNavigation {
|
|
+
|
|
+ // Leaves start
|
|
+ private static final top.leavesmc.leaves.path.NodeEvaluatorGenerator nodeEvaluatorGenerator = () -> {
|
|
+ var nodeEvaluator = new FlyNodeEvaluator();
|
|
+ nodeEvaluator.setCanPassDoors(true);
|
|
+ return nodeEvaluator;
|
|
+ };
|
|
+ // Leaves end
|
|
+
|
|
public FlyingPathNavigation(Mob entity, Level world) {
|
|
super(entity, world);
|
|
}
|
|
@@ -20,7 +29,13 @@ public class FlyingPathNavigation extends PathNavigation {
|
|
protected PathFinder createPathFinder(int range) {
|
|
this.nodeEvaluator = new FlyNodeEvaluator();
|
|
this.nodeEvaluator.setCanPassDoors(true);
|
|
- return new PathFinder(this.nodeEvaluator, range);
|
|
+ // Leaves start
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding) {
|
|
+ return new PathFinder(this.nodeEvaluator, range, nodeEvaluatorGenerator);
|
|
+ } else {
|
|
+ return new PathFinder(this.nodeEvaluator, range);
|
|
+ }
|
|
+ // Leaves end
|
|
}
|
|
|
|
@Override
|
|
@@ -45,9 +60,11 @@ public class FlyingPathNavigation extends PathNavigation {
|
|
this.recomputePath();
|
|
}
|
|
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding && this.path != null && !this.path.isProcessed()) return; // Leaves
|
|
+
|
|
if (!this.isDone()) {
|
|
if (this.canUpdatePath()) {
|
|
- this.followThePath();
|
|
+ this.followThePathSuper(); // Leaves
|
|
} else if (this.path != null && !this.path.isDone()) {
|
|
Vec3 vec3 = this.path.getNextEntityPos(this.mob);
|
|
if (this.mob.getBlockX() == Mth.floor(vec3.x) && this.mob.getBlockY() == Mth.floor(vec3.y) && this.mob.getBlockZ() == Mth.floor(vec3.z)) {
|
|
diff --git a/src/main/java/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java b/src/main/java/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java
|
|
index f0248d839255763005ba333b0bfcf691407fb69b..9b1ef3c365d1523ec5dafa6f57b56d7d0f0a0e8a 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java
|
|
@@ -15,6 +15,15 @@ import net.minecraft.world.level.pathfinder.WalkNodeEvaluator;
|
|
import net.minecraft.world.phys.Vec3;
|
|
|
|
public class GroundPathNavigation extends PathNavigation {
|
|
+
|
|
+ // Leaves start
|
|
+ private static final top.leavesmc.leaves.path.NodeEvaluatorGenerator nodeEvaluatorGenerator = () -> {
|
|
+ var nodeEvaluator = new WalkNodeEvaluator();
|
|
+ nodeEvaluator.setCanPassDoors(true);
|
|
+ return nodeEvaluator;
|
|
+ };
|
|
+ // Leaves end
|
|
+
|
|
private boolean avoidSun;
|
|
|
|
public GroundPathNavigation(Mob entity, Level world) {
|
|
@@ -25,7 +34,13 @@ public class GroundPathNavigation extends PathNavigation {
|
|
protected PathFinder createPathFinder(int range) {
|
|
this.nodeEvaluator = new WalkNodeEvaluator();
|
|
this.nodeEvaluator.setCanPassDoors(true);
|
|
- return new PathFinder(this.nodeEvaluator, range);
|
|
+ // Leaves start
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding) {
|
|
+ return new PathFinder(this.nodeEvaluator, range, nodeEvaluatorGenerator);
|
|
+ } else {
|
|
+ return new PathFinder(this.nodeEvaluator, range);
|
|
+ }
|
|
+ // Leaves end
|
|
}
|
|
|
|
@Override
|
|
diff --git a/src/main/java/net/minecraft/world/entity/ai/navigation/PathNavigation.java b/src/main/java/net/minecraft/world/entity/ai/navigation/PathNavigation.java
|
|
index c1781c92ff59f0c9eb47cbbef01e3252c5e1a1bf..6faf6154dcbad4b9c30168612f603fdab6560454 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/ai/navigation/PathNavigation.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/ai/navigation/PathNavigation.java
|
|
@@ -150,6 +150,9 @@ public abstract class PathNavigation {
|
|
return null;
|
|
} else if (!this.canUpdatePath()) {
|
|
return null;
|
|
+ } else if (this.path instanceof top.leavesmc.leaves.path.AsyncPath asyncPath && !asyncPath.isProcessed() && asyncPath.hasSameProcessingPositions(positions)) { // Leaves start - catch early if it's still processing these positions let it keep processing
|
|
+ return this.path;
|
|
+ // Leaves end
|
|
} else if (this.path != null && !this.path.isDone() && positions.contains(this.targetPos)) {
|
|
return this.path;
|
|
} else {
|
|
@@ -176,11 +179,28 @@ public abstract class PathNavigation {
|
|
PathNavigationRegion pathNavigationRegion = new PathNavigationRegion(this.level, blockPos.offset(-i, -i, -i), blockPos.offset(i, i, i));
|
|
Path path = this.pathFinder.findPath(pathNavigationRegion, this.mob, positions, followRange, distance, this.maxVisitedNodesMultiplier);
|
|
this.level.getProfiler().pop();
|
|
- if (path != null && path.getTarget() != null) {
|
|
+
|
|
+ // Leaves start
|
|
+ if (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding) {
|
|
+ if (path != null && path.getTarget() != null) {
|
|
this.targetPos = path.getTarget();
|
|
this.reachRange = distance;
|
|
this.resetStuckTimeout();
|
|
+ }
|
|
+ } else {
|
|
+ if (!positions.isEmpty()) this.targetPos = positions.iterator().next(); // Leaves - assign early a target position. most calls will only have 1 position
|
|
+
|
|
+ top.leavesmc.leaves.path.AsyncPathProcessor.awaitProcessing(path, processedPath -> {
|
|
+ if (processedPath != this.path) return; // Leaves - check that processing didn't take so long that we calculated a new path
|
|
+
|
|
+ if (processedPath != null && processedPath.getTarget() != null) {
|
|
+ this.targetPos = processedPath.getTarget();
|
|
+ this.reachRange = distance;
|
|
+ this.resetStuckTimeout();
|
|
+ }
|
|
+ });
|
|
}
|
|
+ // Leaves end
|
|
|
|
return path;
|
|
}
|
|
@@ -227,8 +247,8 @@ public abstract class PathNavigation {
|
|
if (this.isDone()) {
|
|
return false;
|
|
} else {
|
|
- this.trimPath();
|
|
- if (this.path.getNodeCount() <= 0) {
|
|
+ if (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding || path.isProcessed()) this.trimPath(); // Leaves - only trim if processed
|
|
+ if ((!top.leavesmc.leaves.LeavesConfig.asyncPathfinding || path.isProcessed()) && this.path.getNodeCount() <= 0) { // Leaves - only check node count if processed
|
|
return false;
|
|
} else {
|
|
this.speedModifier = speed;
|
|
@@ -252,9 +272,11 @@ public abstract class PathNavigation {
|
|
this.recomputePath();
|
|
}
|
|
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding && this.path != null && !this.path.isProcessed()) return; // Leaves - skip pathfinding if we're still processing
|
|
+
|
|
if (!this.isDone()) {
|
|
if (this.canUpdatePath()) {
|
|
- this.followThePath();
|
|
+ this.followThePathSuper(); // Leaves
|
|
} else if (this.path != null && !this.path.isDone()) {
|
|
Vec3 vec3 = this.getTempMobPos();
|
|
Vec3 vec32 = this.path.getNextEntityPos(this.mob);
|
|
@@ -276,6 +298,13 @@ public abstract class PathNavigation {
|
|
return this.level.getBlockState(blockPos.below()).isAir() ? pos.y : WalkNodeEvaluator.getFloorLevel(this.level, blockPos);
|
|
}
|
|
|
|
+ // Leaves start - this fixes plugin compat by ensuring the isProcessed check is completed properly.
|
|
+ protected final void followThePathSuper() {
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding && !this.path.isProcessed()) return; // Leaves
|
|
+ followThePath();
|
|
+ }
|
|
+ // Leaves end - this fixes plugin compat by ensuring the isProcessed check is completed properly.
|
|
+
|
|
protected void followThePath() {
|
|
Vec3 vec3 = this.getTempMobPos();
|
|
this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F;
|
|
diff --git a/src/main/java/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java b/src/main/java/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java
|
|
index 8db20db72cd51046213625fac46c35854c59ec5d..28040c76ec4216a425e2c6c7216f96a006f10085 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java
|
|
@@ -57,20 +57,42 @@ public class NearestBedSensor extends Sensor<Mob> {
|
|
java.util.List<Pair<Holder<PoiType>, BlockPos>> poiposes = new java.util.ArrayList<>();
|
|
// don't ask me why it's unbounded. ask mojang.
|
|
io.papermc.paper.util.PoiAccess.findAnyPoiPositions(poiManager, type -> type.is(PoiTypes.HOME), predicate, entity.blockPosition(), 48, PoiManager.Occupancy.ANY, false, Integer.MAX_VALUE, poiposes);
|
|
- Path path = AcquirePoi.findPathToPois(entity, new java.util.HashSet<>(poiposes));
|
|
- // Paper end - optimise POI access
|
|
- if (path != null && path.canReach()) {
|
|
- BlockPos blockPos = path.getTarget();
|
|
- Optional<Holder<PoiType>> optional = poiManager.getType(blockPos);
|
|
- if (optional.isPresent()) {
|
|
- entity.getBrain().setMemory(MemoryModuleType.NEAREST_BED, blockPos);
|
|
- }
|
|
- } else if (this.triedCount < 5) {
|
|
- this.batchCache.long2LongEntrySet().removeIf((entry) -> {
|
|
- return entry.getLongValue() < this.lastUpdate;
|
|
+
|
|
+ // Leaves start - await on path async
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding) {
|
|
+ Path possiblePath = AcquirePoi.findPathToPois(entity, new java.util.HashSet<>(poiposes));
|
|
+ // Paper end - optimise POI access
|
|
+ // Leaves - wait on the path to be processed
|
|
+ top.leavesmc.leaves.path.AsyncPathProcessor.awaitProcessing(possiblePath, path -> {
|
|
+ // Leaves - readd canReach check
|
|
+ if (path == null || !path.canReach()) {
|
|
+ this.batchCache.long2LongEntrySet().removeIf((entry) -> {
|
|
+ return entry.getLongValue() < this.lastUpdate;
|
|
+ });
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ BlockPos blockPos = path.getTarget();
|
|
+ Optional<Holder<PoiType>> optional = poiManager.getType(blockPos);
|
|
+ if (optional.isPresent()) {
|
|
+ entity.getBrain().setMemory(MemoryModuleType.NEAREST_BED, blockPos);
|
|
+ }
|
|
});
|
|
+ } else {
|
|
+ Path path = AcquirePoi.findPathToPois(entity, new java.util.HashSet<>(poiposes));
|
|
+ if (path != null && path.canReach()) {
|
|
+ BlockPos blockPos = path.getTarget();
|
|
+ Optional<Holder<PoiType>> optional = poiManager.getType(blockPos);
|
|
+ if (optional.isPresent()) {
|
|
+ entity.getBrain().setMemory(MemoryModuleType.NEAREST_BED, blockPos);
|
|
+ }
|
|
+ } else if (this.triedCount < 5) {
|
|
+ this.batchCache.long2LongEntrySet().removeIf((entry) -> {
|
|
+ return entry.getLongValue() < this.lastUpdate;
|
|
+ });
|
|
+ }
|
|
}
|
|
-
|
|
+ // Leaves end - await on path async
|
|
}
|
|
}
|
|
}
|
|
diff --git a/src/main/java/net/minecraft/world/entity/animal/Bee.java b/src/main/java/net/minecraft/world/entity/animal/Bee.java
|
|
index a9cdf9034ad269f7a71358443acc053288cfbe6d..de28757a247b2c1e6d78aa2989db50d2137f4a57 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/animal/Bee.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/animal/Bee.java
|
|
@@ -1071,7 +1071,7 @@ public class Bee extends Animal implements NeutralMob, FlyingAnimal {
|
|
} else {
|
|
Bee.this.pathfindRandomlyTowards(Bee.this.hivePos);
|
|
}
|
|
- } else {
|
|
+ } else if (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding || (navigation.getPath() != null && navigation.getPath().isProcessed())) { // Leaves - check processing
|
|
boolean flag = this.pathfindDirectlyTowards(Bee.this.hivePos);
|
|
|
|
if (!flag) {
|
|
@@ -1133,7 +1133,7 @@ public class Bee extends Animal implements NeutralMob, FlyingAnimal {
|
|
} else {
|
|
Path pathentity = Bee.this.navigation.getPath();
|
|
|
|
- return pathentity != null && pathentity.getTarget().equals(pos) && pathentity.canReach() && pathentity.isDone();
|
|
+ return pathentity != null && (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding || pathentity.isProcessed()) && pathentity.getTarget().equals(pos) && pathentity.canReach() && pathentity.isDone(); // Leaves - ensure path is processed
|
|
}
|
|
}
|
|
}
|
|
diff --git a/src/main/java/net/minecraft/world/entity/animal/frog/Frog.java b/src/main/java/net/minecraft/world/entity/animal/frog/Frog.java
|
|
index bb6063ae7f4438916306ce876057f7488537b444..a6dac57da497586d5dada1a03ad96c7b815494e7 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/animal/frog/Frog.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/animal/frog/Frog.java
|
|
@@ -411,6 +411,14 @@ public class Frog extends Animal {
|
|
}
|
|
|
|
static class FrogPathNavigation extends AmphibiousPathNavigation {
|
|
+ // Leaves start
|
|
+ private static final top.leavesmc.leaves.path.NodeEvaluatorGenerator nodeEvaluatorGenerator = () -> {
|
|
+ var nodeEvaluator = new Frog.FrogNodeEvaluator(true);
|
|
+ nodeEvaluator.setCanPassDoors(true);
|
|
+ return nodeEvaluator;
|
|
+ };
|
|
+ // Leaves end
|
|
+
|
|
FrogPathNavigation(Frog frog, Level world) {
|
|
super(frog, world);
|
|
}
|
|
@@ -419,7 +427,13 @@ public class Frog extends Animal {
|
|
protected PathFinder createPathFinder(int range) {
|
|
this.nodeEvaluator = new Frog.FrogNodeEvaluator(true);
|
|
this.nodeEvaluator.setCanPassDoors(true);
|
|
- return new PathFinder(this.nodeEvaluator, range);
|
|
+ // Leaves start
|
|
+ if (top.leavesmc.leaves.LeavesConfig.asyncPathfinding) {
|
|
+ return new PathFinder(this.nodeEvaluator, range, nodeEvaluatorGenerator);
|
|
+ } else {
|
|
+ return new PathFinder(this.nodeEvaluator, range);
|
|
+ }
|
|
+ // Leaves end
|
|
}
|
|
}
|
|
}
|
|
diff --git a/src/main/java/net/minecraft/world/entity/monster/Drowned.java b/src/main/java/net/minecraft/world/entity/monster/Drowned.java
|
|
index 1b1305f5eaf5710b72c57ab4c3953e703a23f1e0..b62adaa514dc47fed866655b8f7046b0657cba73 100644
|
|
--- a/src/main/java/net/minecraft/world/entity/monster/Drowned.java
|
|
+++ b/src/main/java/net/minecraft/world/entity/monster/Drowned.java
|
|
@@ -222,7 +222,7 @@ public class Drowned extends Zombie implements RangedAttackMob {
|
|
protected boolean closeToNextPos() {
|
|
Path pathentity = this.getNavigation().getPath();
|
|
|
|
- if (pathentity != null) {
|
|
+ if (pathentity != null && (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding || pathentity.isProcessed())) { // Leaves - ensure path is processed
|
|
BlockPos blockposition = pathentity.getTarget();
|
|
|
|
if (blockposition != null) {
|
|
diff --git a/src/main/java/net/minecraft/world/level/pathfinder/Path.java b/src/main/java/net/minecraft/world/level/pathfinder/Path.java
|
|
index 2a335f277bd0e4b8ad0f60d8226eb8aaa80a871f..c765c6bdf6fe07495fe0a17d6a5494a72875af18 100644
|
|
--- a/src/main/java/net/minecraft/world/level/pathfinder/Path.java
|
|
+++ b/src/main/java/net/minecraft/world/level/pathfinder/Path.java
|
|
@@ -30,6 +30,17 @@ public class Path {
|
|
this.reached = reachesTarget;
|
|
}
|
|
|
|
+ // Leaves start
|
|
+ /**
|
|
+ * checks if the path is completely processed in the case of it being computed async
|
|
+ *
|
|
+ * @return true if the path is processed
|
|
+ */
|
|
+ public boolean isProcessed() {
|
|
+ return true;
|
|
+ }
|
|
+ // Leaves end
|
|
+
|
|
public void advance() {
|
|
++this.nextNodeIndex;
|
|
}
|
|
@@ -104,6 +115,8 @@ public class Path {
|
|
}
|
|
|
|
public boolean sameAs(@Nullable Path o) {
|
|
+ if (o == this) return true; // Leaves - short circuit
|
|
+
|
|
if (o == null) {
|
|
return false;
|
|
} else if (o.nodes.size() != this.nodes.size()) {
|
|
diff --git a/src/main/java/net/minecraft/world/level/pathfinder/PathFinder.java b/src/main/java/net/minecraft/world/level/pathfinder/PathFinder.java
|
|
index d23481453717f715124156b5d83f6448f720d049..6cc6140f44827ccc055aafdd6bfb3a09d3cdacb4 100644
|
|
--- a/src/main/java/net/minecraft/world/level/pathfinder/PathFinder.java
|
|
+++ b/src/main/java/net/minecraft/world/level/pathfinder/PathFinder.java
|
|
@@ -25,36 +25,75 @@ public class PathFinder {
|
|
private static final boolean DEBUG = false;
|
|
private final BinaryHeap openSet = new BinaryHeap();
|
|
|
|
- public PathFinder(NodeEvaluator pathNodeMaker, int range) {
|
|
+ private final @Nullable top.leavesmc.leaves.path.NodeEvaluatorGenerator nodeEvaluatorGenerator; // Leaves - we use this later to generate an evaluator
|
|
+
|
|
+ // Leaves start - add nodeEvaluatorGenerator as optional param
|
|
+ public PathFinder(NodeEvaluator pathNodeMaker, int range, @Nullable top.leavesmc.leaves.path.NodeEvaluatorGenerator nodeEvaluatorGenerator) {
|
|
this.nodeEvaluator = pathNodeMaker;
|
|
this.maxVisitedNodes = range;
|
|
+ this.nodeEvaluatorGenerator = nodeEvaluatorGenerator;
|
|
+ }
|
|
+
|
|
+ public PathFinder(NodeEvaluator pathNodeMaker, int range) {
|
|
+ this(pathNodeMaker, range, null);
|
|
}
|
|
+ // Leaves end - add nodeEvaluatorGenerator as optional param
|
|
|
|
@Nullable
|
|
public Path findPath(PathNavigationRegion world, Mob mob, Set<BlockPos> positions, float followRange, int distance, float rangeMultiplier) {
|
|
- this.openSet.clear();
|
|
- this.nodeEvaluator.prepare(world, mob);
|
|
- Node node = this.nodeEvaluator.getStart();
|
|
+ if (!top.leavesmc.leaves.LeavesConfig.asyncPathfinding) this.openSet.clear(); // Leaves - it's always cleared in processPath
|
|
+ // Leaves start - use a generated evaluator if we have one otherwise run sync
|
|
+ var nodeEvaluator = this.nodeEvaluatorGenerator == null ? this.nodeEvaluator : top.leavesmc.leaves.path.NodeEvaluatorCache.takeNodeEvaluator(this.nodeEvaluatorGenerator);
|
|
+ nodeEvaluator.prepare(world, mob);
|
|
+ Node node = nodeEvaluator.getStart();
|
|
if (node == null) {
|
|
+ top.leavesmc.leaves.path.NodeEvaluatorCache.removeNodeEvaluator(nodeEvaluator);
|
|
return null;
|
|
} else {
|
|
// Paper start - remove streams - and optimize collection
|
|
List<Map.Entry<Target, BlockPos>> map = Lists.newArrayList();
|
|
for (BlockPos pos : positions) {
|
|
- map.add(new java.util.AbstractMap.SimpleEntry<>(this.nodeEvaluator.getGoal(pos.getX(), pos.getY(), pos.getZ()), pos));
|
|
+ map.add(new java.util.AbstractMap.SimpleEntry<>(nodeEvaluator.getGoal(pos.getX(), pos.getY(), pos.getZ()), pos));
|
|
}
|
|
// Paper end
|
|
- Path path = this.findPath(world.getProfiler(), node, map, followRange, distance, rangeMultiplier);
|
|
- this.nodeEvaluator.done();
|
|
- return path;
|
|
+
|
|
+ // Leaves start
|
|
+ if (this.nodeEvaluatorGenerator == null) {
|
|
+ // run sync :(
|
|
+ top.leavesmc.leaves.path.NodeEvaluatorCache.removeNodeEvaluator(nodeEvaluator);
|
|
+ return this.findPath(world.getProfiler(), node, map, followRange, distance, rangeMultiplier);
|
|
+ }
|
|
+
|
|
+ return new top.leavesmc.leaves.path.AsyncPath(Lists.newArrayList(), positions, () -> {
|
|
+ try {
|
|
+ return this.processPath(nodeEvaluator, node, map, followRange, distance, rangeMultiplier);
|
|
+ } finally {
|
|
+ nodeEvaluator.done();
|
|
+ top.leavesmc.leaves.path.NodeEvaluatorCache.returnNodeEvaluator(nodeEvaluator);
|
|
+ }
|
|
+ });
|
|
+ // Leaves end - use a generated evaluator if we have one otherwise run sync
|
|
}
|
|
}
|
|
|
|
- @Nullable
|
|
+ // Leaves start - split pathfinding into the original sync method for compat and processing for delaying
|
|
// Paper start - optimize collection
|
|
private Path findPath(ProfilerFiller profiler, Node startNode, List<Map.Entry<Target, BlockPos>> positions, float followRange, int distance, float rangeMultiplier) {
|
|
+ // readd the profiler code for sync
|
|
profiler.push("find_path");
|
|
profiler.markForCharting(MetricCategory.PATH_FINDING);
|
|
+
|
|
+ try {
|
|
+ return this.processPath(this.nodeEvaluator, startNode, positions, followRange, distance, rangeMultiplier);
|
|
+ } finally {
|
|
+ this.nodeEvaluator.done();
|
|
+ }
|
|
+ }
|
|
+ // Leaves end - split pathfinding into the original sync method for compat and processing for delaying
|
|
+
|
|
+ private synchronized @org.jetbrains.annotations.NotNull Path processPath(NodeEvaluator nodeEvaluator, Node startNode, List<Map.Entry<Target, BlockPos>> positions, float followRange, int distance, float rangeMultiplier) { // Leaves - sync to only use the caching functions in this class on a single thread
|
|
+ org.apache.commons.lang3.Validate.isTrue(!positions.isEmpty()); // ensure that we have at least one position, which means we'll always return a path
|
|
+
|
|
// Set<Target> set = positions.keySet();
|
|
startNode.g = 0.0F;
|
|
startNode.h = this.getBestH(startNode, positions); // Paper - optimize collection
|
|
@@ -91,7 +130,7 @@ public class PathFinder {
|
|
}
|
|
|
|
if (!(node.distanceTo(startNode) >= followRange)) {
|
|
- int k = this.nodeEvaluator.getNeighbors(this.neighbors, node);
|
|
+ int k = nodeEvaluator.getNeighbors(this.neighbors, node);
|
|
|
|
for(int l = 0; l < k; ++l) {
|
|
Node node2 = this.neighbors[l];
|
|
@@ -123,9 +162,14 @@ public class PathFinder {
|
|
if (best == null || comparator.compare(path, best) < 0)
|
|
best = path;
|
|
}
|
|
+
|
|
+ // Leaves start - ignore this warning, we know that the above loop always runs at least once since positions is not empty
|
|
+ //noinspection ConstantConditions
|
|
return best;
|
|
// Paper end
|
|
+ // Leaves end - ignore this warning, we know that the above loop always runs at least once since positions is not empty
|
|
}
|
|
+ // Leaves end
|
|
|
|
protected float distance(Node a, Node b) {
|
|
return a.distanceTo(b);
|
|
diff --git a/src/main/java/top/leavesmc/leaves/LeavesConfig.java b/src/main/java/top/leavesmc/leaves/LeavesConfig.java
|
|
index 6924ca89da0decc8f861842b770d0cfae7fc0ba1..84bbe8d232be70c87e460b5ef28fca1b7d17f32d 100644
|
|
--- a/src/main/java/top/leavesmc/leaves/LeavesConfig.java
|
|
+++ b/src/main/java/top/leavesmc/leaves/LeavesConfig.java
|
|
@@ -340,6 +340,20 @@ public final class LeavesConfig {
|
|
removeRangeCheckStreams = getBoolean("settings.performance.remove.range-check-streams-and-iterators", removeRangeCheckStreams);
|
|
}
|
|
|
|
+ public static boolean asyncPathfinding = false;
|
|
+ private static boolean asyncPathfindingLock = false;
|
|
+ private static void asyncPathfinding() {
|
|
+ if (!asyncPathfindingLock) {
|
|
+ asyncPathfinding = getBoolean("settings.performance.async-pathfinding", asyncPathfinding);
|
|
+ asyncPathfindingLock = true;
|
|
+ }
|
|
+
|
|
+ if (asyncPathfinding) {
|
|
+ asyncPathfinding = false;
|
|
+ LeavesLogger.LOGGER.severe("Async Pathfinding is updating, it can't work");
|
|
+ }
|
|
+ }
|
|
+
|
|
public static final class WorldConfig {
|
|
|
|
public final String worldName;
|
|
diff --git a/src/main/java/top/leavesmc/leaves/path/AsyncPath.java b/src/main/java/top/leavesmc/leaves/path/AsyncPath.java
|
|
new file mode 100644
|
|
index 0000000000000000000000000000000000000000..6f96acc71bc5470e5a32e5695d28c552df6af23c
|
|
--- /dev/null
|
|
+++ b/src/main/java/top/leavesmc/leaves/path/AsyncPath.java
|
|
@@ -0,0 +1,284 @@
|
|
+package top.leavesmc.leaves.path;
|
|
+
|
|
+import net.minecraft.core.BlockPos;
|
|
+import net.minecraft.world.entity.Entity;
|
|
+import net.minecraft.world.level.pathfinder.Node;
|
|
+import net.minecraft.world.level.pathfinder.Path;
|
|
+import net.minecraft.world.phys.Vec3;
|
|
+import org.jetbrains.annotations.NotNull;
|
|
+import org.jetbrains.annotations.Nullable;
|
|
+
|
|
+import java.util.ArrayList;
|
|
+import java.util.List;
|
|
+import java.util.Set;
|
|
+import java.util.function.Supplier;
|
|
+
|
|
+// Powered by Pufferfish(https://github.com/pufferfish-gg/Pufferfish)
|
|
+
|
|
+/**
|
|
+ * i'll be using this to represent a path that not be processed yet!
|
|
+ */
|
|
+public class AsyncPath extends Path {
|
|
+
|
|
+ /**
|
|
+ * marks whether this async path has been processed
|
|
+ */
|
|
+ private volatile boolean processed = false;
|
|
+
|
|
+ /**
|
|
+ * runnables waiting for path to be processed
|
|
+ */
|
|
+ private final @NotNull List<Runnable> postProcessing = new ArrayList<>();
|
|
+
|
|
+ /**
|
|
+ * a list of positions that this path could path towards
|
|
+ */
|
|
+ private final Set<BlockPos> positions;
|
|
+
|
|
+ /**
|
|
+ * the supplier of the real processed path
|
|
+ */
|
|
+ private final Supplier<Path> pathSupplier;
|
|
+
|
|
+ /*
|
|
+ * Processed values
|
|
+ */
|
|
+
|
|
+ /**
|
|
+ * this is a reference to the nodes list in the parent `Path` object
|
|
+ */
|
|
+ private final List<Node> nodes;
|
|
+ /**
|
|
+ * the block we're trying to path to
|
|
+ * <p>
|
|
+ * while processing, we have no idea where this is so consumers of `Path` should check that the path is processed before checking the target block
|
|
+ */
|
|
+ private @Nullable BlockPos target;
|
|
+ /**
|
|
+ * how far we are to the target
|
|
+ * <p>
|
|
+ * while processing, the target could be anywhere but theoretically we're always "close" to a theoretical target so default is 0
|
|
+ */
|
|
+ private float distToTarget = 0;
|
|
+ /**
|
|
+ * whether we can reach the target
|
|
+ * <p>
|
|
+ * while processing we can always theoretically reach the target so default is true
|
|
+ */
|
|
+ private boolean canReach = true;
|
|
+
|
|
+ public AsyncPath(@NotNull List<Node> emptyNodeList, @NotNull Set<BlockPos> positions, @NotNull Supplier<Path> pathSupplier) {
|
|
+ //noinspection ConstantConditions
|
|
+ super(emptyNodeList, null, false);
|
|
+
|
|
+ this.nodes = emptyNodeList;
|
|
+ this.positions = positions;
|
|
+ this.pathSupplier = pathSupplier;
|
|
+
|
|
+ AsyncPathProcessor.queue(this);
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public boolean isProcessed() {
|
|
+ return this.processed;
|
|
+ }
|
|
+
|
|
+ /**
|
|
+ * add a post-processing action
|
|
+ */
|
|
+ public synchronized void postProcessing(@NotNull Runnable runnable) {
|
|
+ if (processed) runnable.run();
|
|
+ else postProcessing.add(runnable);
|
|
+ }
|
|
+
|
|
+ /**
|
|
+ * an easy way to check if this processing path is the same as an attempted new path
|
|
+ *
|
|
+ * @param positions - the positions to compare against
|
|
+ * @return true if we are processing the same positions
|
|
+ */
|
|
+ public boolean hasSameProcessingPositions(final Set<BlockPos> positions) {
|
|
+ if (this.positions.size() != positions.size()) {
|
|
+ return false;
|
|
+ }
|
|
+
|
|
+ return this.positions.containsAll(positions);
|
|
+ }
|
|
+
|
|
+ /**
|
|
+ * starts processing this path
|
|
+ */
|
|
+ public synchronized void process() {
|
|
+ if (this.processed) {
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ final Path bestPath = this.pathSupplier.get();
|
|
+
|
|
+ this.nodes.addAll(bestPath.nodes); // we mutate this list to reuse the logic in Path
|
|
+ this.target = bestPath.getTarget();
|
|
+ this.distToTarget = bestPath.getDistToTarget();
|
|
+ this.canReach = bestPath.canReach();
|
|
+
|
|
+ this.processed = true;
|
|
+
|
|
+ this.postProcessing.forEach(Runnable::run);
|
|
+ }
|
|
+
|
|
+ /**
|
|
+ * if this path is accessed while it hasn't processed, just process it in-place
|
|
+ */
|
|
+ private void checkProcessed() {
|
|
+ if (!this.processed) {
|
|
+ this.process();
|
|
+ }
|
|
+ }
|
|
+
|
|
+ /*
|
|
+ * overrides we need for final fields that we cannot modify after processing
|
|
+ */
|
|
+
|
|
+ @Override
|
|
+ public @NotNull BlockPos getTarget() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return this.target;
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public float getDistToTarget() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return this.distToTarget;
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public boolean canReach() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return this.canReach;
|
|
+ }
|
|
+
|
|
+ /*
|
|
+ * overrides to ensure we're processed first
|
|
+ */
|
|
+
|
|
+ @Override
|
|
+ public boolean isDone() {
|
|
+ return this.isProcessed() && super.isDone();
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public void advance() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ super.advance();
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public boolean notStarted() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.notStarted();
|
|
+ }
|
|
+
|
|
+ @Nullable
|
|
+ @Override
|
|
+ public Node getEndNode() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.getEndNode();
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public Node getNode(int index) {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.getNode(index);
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public void truncateNodes(int length) {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ super.truncateNodes(length);
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public void replaceNode(int index, Node node) {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ super.replaceNode(index, node);
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public int getNodeCount() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.getNodeCount();
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public int getNextNodeIndex() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.getNextNodeIndex();
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public void setNextNodeIndex(int nodeIndex) {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ super.setNextNodeIndex(nodeIndex);
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public Vec3 getEntityPosAtNode(Entity entity, int index) {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.getEntityPosAtNode(entity, index);
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public BlockPos getNodePos(int index) {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.getNodePos(index);
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public Vec3 getNextEntityPos(Entity entity) {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.getNextEntityPos(entity);
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public BlockPos getNextNodePos() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.getNextNodePos();
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public Node getNextNode() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.getNextNode();
|
|
+ }
|
|
+
|
|
+ @Nullable
|
|
+ @Override
|
|
+ public Node getPreviousNode() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.getPreviousNode();
|
|
+ }
|
|
+
|
|
+ @Override
|
|
+ public boolean hasNext() {
|
|
+ this.checkProcessed();
|
|
+
|
|
+ return super.hasNext();
|
|
+ }
|
|
+}
|
|
diff --git a/src/main/java/top/leavesmc/leaves/path/AsyncPathProcessor.java b/src/main/java/top/leavesmc/leaves/path/AsyncPathProcessor.java
|
|
new file mode 100644
|
|
index 0000000000000000000000000000000000000000..9aa66b327dbbb8624d473e1d9cb6eaab95ecb2dc
|
|
--- /dev/null
|
|
+++ b/src/main/java/top/leavesmc/leaves/path/AsyncPathProcessor.java
|
|
@@ -0,0 +1,46 @@
|
|
+package top.leavesmc.leaves.path;
|
|
+
|
|
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
|
|
+import net.minecraft.server.MinecraftServer;
|
|
+import net.minecraft.world.level.pathfinder.Path;
|
|
+import org.jetbrains.annotations.NotNull;
|
|
+import org.jetbrains.annotations.Nullable;
|
|
+
|
|
+import java.util.concurrent.CompletableFuture;
|
|
+import java.util.concurrent.Executor;
|
|
+import java.util.concurrent.Executors;
|
|
+import java.util.function.Consumer;
|
|
+
|
|
+// Powered by Pufferfish(https://github.com/pufferfish-gg/Pufferfish)
|
|
+
|
|
+/**
|
|
+ * used to handle the scheduling of async path processing
|
|
+ */
|
|
+public class AsyncPathProcessor {
|
|
+
|
|
+ private static final Executor mainThreadExecutor = MinecraftServer.getServer();
|
|
+ private static final Executor pathProcessingExecutor = Executors.newCachedThreadPool(new ThreadFactoryBuilder()
|
|
+ .setNameFormat("puff-path-processor-%d")
|
|
+ .setPriority(Thread.NORM_PRIORITY - 2)
|
|
+ .build());
|
|
+
|
|
+ protected static CompletableFuture<Void> queue(@NotNull AsyncPath path) {
|
|
+ return CompletableFuture.runAsync(path::process, pathProcessingExecutor);
|
|
+ }
|
|
+
|
|
+ /**
|
|
+ * takes a possibly unprocessed path, and waits until it is completed
|
|
+ * the consumer will be immediately invoked if the path is already processed
|
|
+ * the consumer will always be called on the main thread
|
|
+ *
|
|
+ * @param path a path to wait on
|
|
+ * @param afterProcessing a consumer to be called
|
|
+ */
|
|
+ public static void awaitProcessing(@Nullable Path path, Consumer<@Nullable Path> afterProcessing) {
|
|
+ if (path != null && !path.isProcessed() && path instanceof AsyncPath asyncPath) {
|
|
+ asyncPath.postProcessing(() -> mainThreadExecutor.execute(() -> afterProcessing.accept(path)));
|
|
+ } else {
|
|
+ afterProcessing.accept(path);
|
|
+ }
|
|
+ }
|
|
+}
|
|
diff --git a/src/main/java/top/leavesmc/leaves/path/NodeEvaluatorCache.java b/src/main/java/top/leavesmc/leaves/path/NodeEvaluatorCache.java
|
|
new file mode 100644
|
|
index 0000000000000000000000000000000000000000..a8d46e5a234d328e8d934f5c33ac380d82c1e09b
|
|
--- /dev/null
|
|
+++ b/src/main/java/top/leavesmc/leaves/path/NodeEvaluatorCache.java
|
|
@@ -0,0 +1,44 @@
|
|
+package top.leavesmc.leaves.path;
|
|
+
|
|
+import net.minecraft.world.level.pathfinder.NodeEvaluator;
|
|
+import org.apache.commons.lang.Validate;
|
|
+import org.jetbrains.annotations.NotNull;
|
|
+
|
|
+import java.util.Map;
|
|
+import java.util.Queue;
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
+import java.util.concurrent.ConcurrentLinkedQueue;
|
|
+
|
|
+// Powered by Pufferfish(https://github.com/pufferfish-gg/Pufferfish)
|
|
+public class NodeEvaluatorCache {
|
|
+
|
|
+ private static final Map<NodeEvaluatorGenerator, ConcurrentLinkedQueue<NodeEvaluator>> threadLocalNodeEvaluators = new ConcurrentHashMap<>();
|
|
+ private static final Map<NodeEvaluator, NodeEvaluatorGenerator> nodeEvaluatorToGenerator = new ConcurrentHashMap<>();
|
|
+
|
|
+ private static @NotNull Queue<NodeEvaluator> getDequeForGenerator(@NotNull NodeEvaluatorGenerator generator) {
|
|
+ return threadLocalNodeEvaluators.computeIfAbsent(generator, (key) -> new ConcurrentLinkedQueue<>());
|
|
+ }
|
|
+
|
|
+ public static @NotNull NodeEvaluator takeNodeEvaluator(@NotNull NodeEvaluatorGenerator generator) {
|
|
+ var nodeEvaluator = getDequeForGenerator(generator).poll();
|
|
+
|
|
+ if (nodeEvaluator == null) {
|
|
+ nodeEvaluator = generator.generate();
|
|
+ }
|
|
+
|
|
+ nodeEvaluatorToGenerator.put(nodeEvaluator, generator);
|
|
+
|
|
+ return nodeEvaluator;
|
|
+ }
|
|
+
|
|
+ public static void returnNodeEvaluator(@NotNull NodeEvaluator nodeEvaluator) {
|
|
+ final var generator = nodeEvaluatorToGenerator.remove(nodeEvaluator);
|
|
+ Validate.notNull(generator, "NodeEvaluator already returned");
|
|
+
|
|
+ getDequeForGenerator(generator).offer(nodeEvaluator);
|
|
+ }
|
|
+
|
|
+ public static void removeNodeEvaluator(@NotNull NodeEvaluator nodeEvaluator) {
|
|
+ nodeEvaluatorToGenerator.remove(nodeEvaluator);
|
|
+ }
|
|
+}
|
|
diff --git a/src/main/java/top/leavesmc/leaves/path/NodeEvaluatorGenerator.java b/src/main/java/top/leavesmc/leaves/path/NodeEvaluatorGenerator.java
|
|
new file mode 100644
|
|
index 0000000000000000000000000000000000000000..b1ea8440be70802220d7493a0d149a9061855383
|
|
--- /dev/null
|
|
+++ b/src/main/java/top/leavesmc/leaves/path/NodeEvaluatorGenerator.java
|
|
@@ -0,0 +1,9 @@
|
|
+package top.leavesmc.leaves.path;
|
|
+
|
|
+import net.minecraft.world.level.pathfinder.NodeEvaluator;
|
|
+import org.jetbrains.annotations.NotNull;
|
|
+
|
|
+// Powered by Pufferfish(https://github.com/pufferfish-gg/Pufferfish)
|
|
+public interface NodeEvaluatorGenerator {
|
|
+ @NotNull NodeEvaluator generate();
|
|
+}
|