This commit is contained in:
Nassim Jahnke
2024-12-13 21:21:48 +01:00
parent 2509faa08e
commit f73e864f18
15 changed files with 450 additions and 511 deletions

View File

@@ -0,0 +1,23 @@
--- a/net/minecraft/commands/CommandSource.java
+++ b/net/minecraft/commands/CommandSource.java
@@ -22,6 +_,13 @@
public boolean shouldInformAdmins() {
return false;
}
+
+ // CraftBukkit start
+ @Override
+ public org.bukkit.command.CommandSender getBukkitSender(CommandSourceStack stack) {
+ return io.papermc.paper.brigadier.NullCommandSender.INSTANCE; // Paper - expose a no-op CommandSender
+ }
+ // CraftBukkit end
};
void sendSystemMessage(Component component);
@@ -35,4 +_,6 @@
default boolean alwaysAccepts() {
return false;
}
+
+ org.bukkit.command.CommandSender getBukkitSender(CommandSourceStack wrapper); // CraftBukkit
}

View File

@@ -0,0 +1,111 @@
--- a/net/minecraft/commands/CommandSourceStack.java
+++ b/net/minecraft/commands/CommandSourceStack.java
@@ -45,7 +_,7 @@
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
-public class CommandSourceStack implements ExecutionCommandSource<CommandSourceStack>, SharedSuggestionProvider {
+public class CommandSourceStack implements ExecutionCommandSource<CommandSourceStack>, SharedSuggestionProvider, io.papermc.paper.command.brigadier.PaperCommandSourceStack { // Paper - Brigadier API
public static final SimpleCommandExceptionType ERROR_NOT_PLAYER = new SimpleCommandExceptionType(Component.translatable("permissions.requires.player"));
public static final SimpleCommandExceptionType ERROR_NOT_ENTITY = new SimpleCommandExceptionType(Component.translatable("permissions.requires.entity"));
public final CommandSource source;
@@ -63,6 +_,8 @@
private final Vec2 rotation;
private final CommandSigningContext signingContext;
private final TaskChainer chatMessageChainer;
+ public java.util.Map<Thread, com.mojang.brigadier.tree.CommandNode> currentCommand = new java.util.concurrent.ConcurrentHashMap<>(); // CraftBukkit // Paper - Thread Safe Vanilla Command permission checking
+ public boolean bypassSelectorPermissions = false; // Paper - add bypass for selector permissions
public CommandSourceStack(
CommandSource source,
@@ -391,9 +_,44 @@
@Override
public boolean hasPermission(int level) {
+ // CraftBukkit start
+ // Paper start - Thread Safe Vanilla Command permission checking
+ com.mojang.brigadier.tree.CommandNode currentCommand = this.currentCommand.get(Thread.currentThread());
+ if (currentCommand != null) {
+ return this.hasPermission(level, org.bukkit.craftbukkit.command.VanillaCommandWrapper.getPermission(currentCommand));
+ // Paper end - Thread Safe Vanilla Command permission checking
+ }
+ // CraftBukkit end
+
return this.permissionLevel >= level;
}
+ // Paper start - Fix permission levels for command blocks
+ private boolean forceRespectPermissionLevel() {
+ return this.source == CommandSource.NULL || (this.source instanceof final net.minecraft.world.level.BaseCommandBlock commandBlock && commandBlock.getLevel().paperConfig().commandBlocks.forceFollowPermLevel);
+ }
+ // Paper end - Fix permission levels for command blocks
+
+ // CraftBukkit start
+ public boolean hasPermission(int i, String bukkitPermission) {
+ // Paper start - Fix permission levels for command blocks
+ final java.util.function.BooleanSupplier hasBukkitPerm = () -> this.source == CommandSource.NULL /*treat NULL as having all bukkit perms*/ || this.getBukkitSender().hasPermission(bukkitPermission); // lazily check bukkit perms to the benefit of custom permission setups
+ // if the server is null, we must check the vanilla perm level system
+ // if ignoreVanillaPermissions is true, we can skip vanilla perms and just run the bukkit perm check
+ //noinspection ConstantValue
+ if (this.getServer() == null || !this.getServer().server.ignoreVanillaPermissions) { // server & level are null for command function loading
+ final boolean hasPermLevel = this.permissionLevel >= i;
+ if (this.forceRespectPermissionLevel()) { // NULL CommandSource and command blocks (if setting is enabled) should always pass the vanilla perm check
+ return hasPermLevel && hasBukkitPerm.getAsBoolean();
+ } else { // otherwise check vanilla perm first then bukkit perm, matching upstream behavior
+ return hasPermLevel || hasBukkitPerm.getAsBoolean();
+ }
+ }
+ return hasBukkitPerm.getAsBoolean();
+ // Paper end - Fix permission levels for command blocks
+ }
+ // CraftBukkit end
+
public Vec3 getPosition() {
return this.worldPosition;
}
@@ -499,20 +_,25 @@
Component component = Component.translatable("chat.type.admin", this.getDisplayName(), message).withStyle(ChatFormatting.GRAY, ChatFormatting.ITALIC);
if (this.server.getGameRules().getBoolean(GameRules.RULE_SENDCOMMANDFEEDBACK)) {
for (ServerPlayer serverPlayer : this.server.getPlayerList().getPlayers()) {
- if (serverPlayer.commandSource() != this.source && this.server.getPlayerList().isOp(serverPlayer.getGameProfile())) {
+ if (serverPlayer.commandSource() != this.source && serverPlayer.getBukkitEntity().hasPermission("minecraft.admin.command_feedback")) { // CraftBukkit
serverPlayer.sendSystemMessage(component);
}
}
}
- if (this.source != this.server && this.server.getGameRules().getBoolean(GameRules.RULE_LOGADMINCOMMANDS)) {
+ if (this.source != this.server && this.server.getGameRules().getBoolean(GameRules.RULE_LOGADMINCOMMANDS) && !org.spigotmc.SpigotConfig.silentCommandBlocks) { // Spigot
this.server.sendSystemMessage(component);
}
}
public void sendFailure(Component message) {
+ // Paper start - Add UnknownCommandEvent
+ this.sendFailure(message, true);
+ }
+ public void sendFailure(Component message, boolean withStyle) {
+ // Paper end - Add UnknownCommandEvent
if (this.source.acceptsFailure() && !this.silent) {
- this.source.sendSystemMessage(Component.empty().append(message).withStyle(ChatFormatting.RED));
+ this.source.sendSystemMessage(withStyle ? Component.empty().append(message).withStyle(ChatFormatting.RED) : message); // Paper - Add UnknownCommandEvent
}
}
@@ -598,4 +_,16 @@
public boolean isSilent() {
return this.silent;
}
+
+ // Paper start
+ @Override
+ public CommandSourceStack getHandle() {
+ return this;
+ }
+ // Paper end
+ // CraftBukkit start
+ public org.bukkit.command.CommandSender getBukkitSender() {
+ return this.source.getBukkitSender(this);
+ }
+ // CraftBukkit end
}

View File

@@ -0,0 +1,312 @@
--- a/net/minecraft/commands/Commands.java
+++ b/net/minecraft/commands/Commands.java
@@ -139,6 +_,14 @@
import net.minecraft.world.level.GameRules;
import org.slf4j.Logger;
+// CraftBukkit start
+import com.google.common.base.Joiner;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import org.bukkit.event.player.PlayerCommandSendEvent;
+import org.bukkit.event.server.ServerCommandEvent;
+// CraftBukkit end
+
public class Commands {
private static final ThreadLocal<ExecutionContext<CommandSourceStack>> CURRENT_EXECUTION_CONTEXT = new ThreadLocal<>();
private static final Logger LOGGER = LogUtils.getLogger();
@@ -251,6 +_,30 @@
PublishCommand.register(this.dispatcher);
}
+ // Paper start - Vanilla command permission fixes
+ for (final CommandNode<CommandSourceStack> node : this.dispatcher.getRoot().getChildren()) {
+ if (node.getRequirement() == com.mojang.brigadier.builder.ArgumentBuilder.<CommandSourceStack>defaultRequirement()) {
+ node.requirement = stack -> stack.source == CommandSource.NULL || stack.getBukkitSender().hasPermission(org.bukkit.craftbukkit.command.VanillaCommandWrapper.getPermission(node));
+ }
+ }
+ // Paper end - Vanilla command permission fixes
+ // Paper start - Brigadier Command API
+ // Create legacy minecraft namespace commands
+ for (final CommandNode<CommandSourceStack> node : new java.util.ArrayList<>(this.dispatcher.getRoot().getChildren())) {
+ // The brigadier dispatcher is not able to resolve nested redirects.
+ // E.g. registering the alias minecraft:tp cannot redirect to tp, as tp itself redirects to teleport.
+ // Instead, target the first none redirecting node.
+ CommandNode<CommandSourceStack> flattenedAliasTarget = node;
+ while (flattenedAliasTarget.getRedirect() != null) flattenedAliasTarget = flattenedAliasTarget.getRedirect();
+
+ this.dispatcher.register(
+ com.mojang.brigadier.builder.LiteralArgumentBuilder.<CommandSourceStack>literal("minecraft:" + node.getName())
+ .executes(flattenedAliasTarget.getCommand())
+ .requires(flattenedAliasTarget.getRequirement())
+ .redirect(flattenedAliasTarget)
+ );
+ }
+ // Paper end - Brigadier Command API
this.dispatcher.setConsumer(ExecutionCommandSource.resultConsumer());
}
@@ -260,15 +_,58 @@
return new ParseResults<>(commandContextBuilder, parseResults.getReader(), parseResults.getExceptions());
}
+ // CraftBukkit start
+ public void dispatchServerCommand(CommandSourceStack sender, String command) {
+ Joiner joiner = Joiner.on(" ");
+ if (command.startsWith("/")) {
+ command = command.substring(1);
+ }
+
+ ServerCommandEvent event = new ServerCommandEvent(sender.getBukkitSender(), command);
+ org.bukkit.Bukkit.getPluginManager().callEvent(event);
+ if (event.isCancelled()) {
+ return;
+ }
+ command = event.getCommand();
+
+ String[] args = command.split(" ");
+ if (args.length == 0) return; // Paper - empty commands shall not be dispatched
+
+ // Paper - Fix permission levels for command blocks
+
+ // Handle vanilla commands; // Paper - handled in CommandNode/CommandDispatcher
+
+ String newCommand = joiner.join(args);
+ this.performPrefixedCommand(sender, newCommand, newCommand);
+ }
+ // CraftBukkit end
+
public void performPrefixedCommand(CommandSourceStack source, String command) {
+ // CraftBukkit start
+ this.performPrefixedCommand(source, command, command);
+ }
+
+ public void performPrefixedCommand(CommandSourceStack source, String command, String label) {
command = command.startsWith("/") ? command.substring(1) : command;
- this.performCommand(this.dispatcher.parse(command, source), command);
+ this.performCommand(this.dispatcher.parse(command, source), command, label);
+ // CraftBukkit end
}
public void performCommand(ParseResults<CommandSourceStack> parseResults, String command) {
+ // CraftBukkit start
+ this.performCommand(parseResults, command, command);
+ }
+
+ public void performCommand(ParseResults<CommandSourceStack> parseResults, String command, String label) {
+ // CraftBukkit end
+ // Paper start
+ this.performCommand(parseResults, command, label, false);
+ }
+ public void performCommand(ParseResults<CommandSourceStack> parseResults, String command, String label, boolean throwCommandError) {
+ // Paper end
CommandSourceStack commandSourceStack = parseResults.getContext().getSource();
Profiler.get().push(() -> "/" + command);
- ContextChain<CommandSourceStack> contextChain = finishParsing(parseResults, command, commandSourceStack);
+ ContextChain contextChain = this.finishParsing(parseResults, command, commandSourceStack, label); // CraftBukkit // Paper - Add UnknownCommandEvent
try {
if (contextChain != null) {
@@ -280,9 +_,10 @@
);
}
} catch (Exception var12) {
+ if (throwCommandError) throw var12; // Paper
MutableComponent mutableComponent = Component.literal(var12.getMessage() == null ? var12.getClass().getName() : var12.getMessage());
- if (LOGGER.isDebugEnabled()) {
- LOGGER.error("Command exception: /{}", command, var12);
+ Commands.LOGGER.error("Command exception: /{}", command, var12); // Paper - always show execution exception in console log
+ if (commandSourceStack.getServer().isDebugging() || Commands.LOGGER.isDebugEnabled()) { // Paper - Debugging
StackTraceElement[] stackTrace = var12.getStackTrace();
for (int i = 0; i < Math.min(stackTrace.length, 3); i++) {
@@ -309,18 +_,22 @@
}
@Nullable
- private static ContextChain<CommandSourceStack> finishParsing(ParseResults<CommandSourceStack> parseResults, String command, CommandSourceStack source) {
+ private ContextChain<CommandSourceStack> finishParsing(ParseResults<CommandSourceStack> parseResults, String command, CommandSourceStack source, String label) { // CraftBukkit // Paper - Add UnknownCommandEvent
try {
validateParseResults(parseResults);
return ContextChain.tryFlatten(parseResults.getContext().build(command))
.orElseThrow(() -> CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(parseResults.getReader()));
} catch (CommandSyntaxException var7) {
- source.sendFailure(ComponentUtils.fromMessage(var7.getRawMessage()));
+ // Paper start - Add UnknownCommandEvent
+ final net.kyori.adventure.text.TextComponent.Builder builder = net.kyori.adventure.text.Component.text();
+ // source.sendFailure(ComponentUtils.fromMessage(var7.getRawMessage()));
+ builder.color(net.kyori.adventure.text.format.NamedTextColor.RED).append(io.papermc.paper.brigadier.PaperBrigadier.componentFromMessage(var7.getRawMessage()));
+ // Paper end - Add UnknownCommandEvent
if (var7.getInput() != null && var7.getCursor() >= 0) {
int min = Math.min(var7.getInput().length(), var7.getCursor());
MutableComponent mutableComponent = Component.empty()
.withStyle(ChatFormatting.GRAY)
- .withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + command)));
+ .withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + label))); // CraftBukkit // Paper
if (min > 10) {
mutableComponent.append(CommonComponents.ELLIPSIS);
}
@@ -332,7 +_,17 @@
}
mutableComponent.append(Component.translatable("command.context.here").withStyle(ChatFormatting.RED, ChatFormatting.ITALIC));
- source.sendFailure(mutableComponent);
+ // Paper start - Add UnknownCommandEvent
+ // source.sendFailure(mutableComponent);
+ builder
+ .append(net.kyori.adventure.text.Component.newline())
+ .append(io.papermc.paper.adventure.PaperAdventure.asAdventure(mutableComponent));
+ }
+ org.bukkit.event.command.UnknownCommandEvent event = new org.bukkit.event.command.UnknownCommandEvent(source.getBukkitSender(), command, org.spigotmc.SpigotConfig.unknownCommandMessage.isEmpty() ? null : builder.build());
+ org.bukkit.Bukkit.getServer().getPluginManager().callEvent(event);
+ if (event.message() != null) {
+ source.sendFailure(io.papermc.paper.adventure.PaperAdventure.asVanilla(event.message()), false);
+ // Paper end - Add UnknownCommandEvent
}
return null;
@@ -360,25 +_,130 @@
}
public void sendCommands(ServerPlayer player) {
- Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> map = Maps.newHashMap();
+ // Paper start - Send empty commands if tab completion is disabled
+ if (org.spigotmc.SpigotConfig.tabComplete < 0) {
+ player.connection.send(new ClientboundCommandsPacket(new RootCommandNode<>()));
+ return;
+ }
+ // Paper end - Send empty commands if tab completion is disabled
+ // CraftBukkit start
+ // Register Vanilla commands into builtRoot as before
+ // Paper start - Perf: Async command map building
+ // Copy root children to avoid concurrent modification during building
+ final Collection<CommandNode<CommandSourceStack>> commandNodes = new java.util.ArrayList<>(this.dispatcher.getRoot().getChildren());
+ COMMAND_SENDING_POOL.execute(() -> this.sendAsync(player, commandNodes));
+ }
+
+ // Fixed pool, but with discard policy
+ public static final java.util.concurrent.ExecutorService COMMAND_SENDING_POOL = new java.util.concurrent.ThreadPoolExecutor(
+ 2, 2, 0, java.util.concurrent.TimeUnit.MILLISECONDS,
+ new java.util.concurrent.LinkedBlockingQueue<>(),
+ new com.google.common.util.concurrent.ThreadFactoryBuilder()
+ .setNameFormat("Paper Async Command Builder Thread Pool - %1$d")
+ .setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(net.minecraft.server.MinecraftServer.LOGGER))
+ .build(),
+ new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy()
+ );
+
+ private void sendAsync(ServerPlayer player, Collection<CommandNode<CommandSourceStack>> dispatcherRootChildren) {
+ // Paper end - Perf: Async command map building
+ Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> map = Maps.newIdentityHashMap(); // Use identity to prevent aliasing issues
+ // Paper - brigadier API removes the need to fill the map twice
RootCommandNode<SharedSuggestionProvider> rootCommandNode = new RootCommandNode<>();
map.put(this.dispatcher.getRoot(), rootCommandNode);
- this.fillUsableCommands(this.dispatcher.getRoot(), rootCommandNode, player.createCommandSourceStack(), map);
+ this.fillUsableCommands(dispatcherRootChildren, rootCommandNode, player.createCommandSourceStack(), map); // Paper - Perf: Async command map building; pass copy of children
+
+ Collection<String> bukkit = new LinkedHashSet<>();
+ for (CommandNode node : rootCommandNode.getChildren()) {
+ bukkit.add(node.getName());
+ }
+ // Paper start - Perf: Async command map building
+ new com.destroystokyo.paper.event.brigadier.AsyncPlayerSendCommandsEvent<CommandSourceStack>(player.getBukkitEntity(), (RootCommandNode) rootCommandNode, false).callEvent(); // Paper - Brigadier API
+ net.minecraft.server.MinecraftServer.getServer().execute(() -> {
+ runSync(player, bukkit, rootCommandNode);
+ });
+ }
+
+ private void runSync(ServerPlayer player, Collection<String> bukkit, RootCommandNode<SharedSuggestionProvider> rootCommandNode) {
+ // Paper end - Perf: Async command map building
+ new com.destroystokyo.paper.event.brigadier.AsyncPlayerSendCommandsEvent<CommandSourceStack>(player.getBukkitEntity(), (RootCommandNode) rootCommandNode, true).callEvent(); // Paper - Brigadier API
+ PlayerCommandSendEvent event = new PlayerCommandSendEvent(player.getBukkitEntity(), new LinkedHashSet<>(bukkit));
+ event.getPlayer().getServer().getPluginManager().callEvent(event);
+
+ // Remove labels that were removed during the event
+ for (String orig : bukkit) {
+ if (!event.getCommands().contains(orig)) {
+ rootCommandNode.removeCommand(orig);
+ }
+ }
+ // CraftBukkit end
+
player.connection.send(new ClientboundCommandsPacket(rootCommandNode));
}
private void fillUsableCommands(
- CommandNode<CommandSourceStack> rootCommandSource,
+ Collection<CommandNode<CommandSourceStack>> children, // Paper - Perf: Async command map building; pass copy of children
CommandNode<SharedSuggestionProvider> rootSuggestion,
CommandSourceStack source,
Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> commandNodeToSuggestionNode
) {
- for (CommandNode<CommandSourceStack> commandNode : rootCommandSource.getChildren()) {
+ commandNodeToSuggestionNode.keySet().removeIf((node) -> !org.spigotmc.SpigotConfig.sendNamespaced && node.getName().contains(":")); // Paper - Remove namedspaced from result nodes to prevent redirect trimming ~ see comment below
+ for (CommandNode<CommandSourceStack> commandNode : children) { // Paper - Perf: Async command map building; pass copy of children
+ // Paper start - Brigadier API
+ if (commandNode.clientNode != null) {
+ commandNode = commandNode.clientNode;
+ }
+ // Paper end - Brigadier API
+ if (!org.spigotmc.SpigotConfig.sendNamespaced && commandNode.getName().contains(":")) continue; // Spigot
if (commandNode.canUse(source)) {
ArgumentBuilder<SharedSuggestionProvider, ?> argumentBuilder = (ArgumentBuilder) commandNode.createBuilder();
+ // Paper start
+ /*
+ Because of how commands can be yeeted right left and center due to bad bukkit practices
+ we need to be able to ensure that ALL commands are registered (even redirects).
+
+ What this will do is IF the redirect seems to be "dead" it will create a builder and essentially populate (flatten)
+ all the children from the dead redirect to the node.
+
+ So, if minecraft:msg redirects to msg but the original msg node has been overriden minecraft:msg will now act as msg and will explicilty inherit its children.
+
+ The only way to fix this is to either:
+ - Send EVERYTHING flattened, don't use redirects
+ - Don't allow command nodes to be deleted
+ - Do this :)
+ */
+
+ // Is there an invalid command redirect?
+ if (argumentBuilder.getRedirect() != null && commandNodeToSuggestionNode.get(argumentBuilder.getRedirect()) == null) {
+ // Create the argument builder with the same values as the specified node, but with a different literal and populated children
+
+ CommandNode<SharedSuggestionProvider> redirect = argumentBuilder.getRedirect();
+ // Diff copied from LiteralCommand#createBuilder
+ final com.mojang.brigadier.builder.LiteralArgumentBuilder<SharedSuggestionProvider> builder = com.mojang.brigadier.builder.LiteralArgumentBuilder.literal(commandNode.getName());
+ builder.requires(redirect.getRequirement());
+ // builder.forward(redirect.getRedirect(), redirect.getRedirectModifier(), redirect.isFork()); We don't want to migrate the forward, since it's invalid.
+ if (redirect.getCommand() != null) {
+ builder.executes(redirect.getCommand());
+ }
+ // Diff copied from LiteralCommand#createBuilder
+ for (CommandNode<SharedSuggestionProvider> child : redirect.getChildren()) {
+ builder.then(child);
+ }
+
+ argumentBuilder = builder;
+ }
+ // Paper end
argumentBuilder.requires(suggestions -> true);
if (argumentBuilder.getCommand() != null) {
- argumentBuilder.executes(commandContext -> 0);
+ // Paper start - fix suggestions due to falsely equal nodes
+ // Always create a new instance
+ argumentBuilder.executes(new com.mojang.brigadier.Command<>() {
+ @Override
+ public int run(com.mojang.brigadier.context.CommandContext<SharedSuggestionProvider> commandContext) {
+ return 0;
+ }
+ });
+ // Paper end - fix suggestions due to falsely equal nodes
}
if (argumentBuilder instanceof RequiredArgumentBuilder) {
@@ -396,7 +_,7 @@
commandNodeToSuggestionNode.put(commandNode, commandNode1);
rootSuggestion.addChild(commandNode1);
if (!commandNode.getChildren().isEmpty()) {
- this.fillUsableCommands(commandNode, commandNode1, source, commandNodeToSuggestionNode);
+ this.fillUsableCommands(commandNode.getChildren(), commandNode1, source, commandNodeToSuggestionNode); // Paper - Perf: Async command map building; pass copy of children
}
}
}

View File

@@ -1,8 +1,8 @@
--- a/net/minecraft/world/CompoundContainer.java
+++ b/net/minecraft/world/CompoundContainer.java
@@ -7,6 +_,48 @@
private final Container container1;
private final Container container2;
public final Container container1;
public final Container container2;
+ // Paper start - add fields and methods
+ public java.util.List<org.bukkit.entity.HumanEntity> transaction = new java.util.ArrayList<org.bukkit.entity.HumanEntity>();

View File

@@ -0,0 +1,11 @@
--- a/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java
+++ b/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java
@@ -39,7 +_,7 @@
@Override
public Path createPath(Entity entity, int i) {
- return this.createPath(entity.blockPosition(), i);
+ return this.createPath(entity.blockPosition(), entity, i); // Paper - EntityPathfindEvent
}
@Override

View File

@@ -0,0 +1,46 @@
--- a/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java
+++ b/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java
@@ -41,7 +_,7 @@
}
@Override
- public Path createPath(BlockPos pos, int accuracy) {
+ public Path createPath(BlockPos pos, @javax.annotation.Nullable Entity entity, int accuracy) { // Paper - EntityPathfindEvent
LevelChunk chunkNow = this.level.getChunkSource().getChunkNow(SectionPos.blockToSectionCoord(pos.getX()), SectionPos.blockToSectionCoord(pos.getZ()));
if (chunkNow == null) {
return null;
@@ -54,7 +_,7 @@
}
if (mutableBlockPos.getY() > this.level.getMinY()) {
- return super.createPath(mutableBlockPos.above(), accuracy);
+ return super.createPath(mutableBlockPos.above(), entity, accuracy); // Paper - EntityPathfindEvent
}
mutableBlockPos.setY(pos.getY() + 1);
@@ -67,7 +_,7 @@
}
if (!chunkNow.getBlockState(pos).isSolid()) {
- return super.createPath(pos, accuracy);
+ return super.createPath(pos, entity, accuracy); // Paper - EntityPathfindEvent
} else {
BlockPos.MutableBlockPos mutableBlockPos = pos.mutable().move(Direction.UP);
@@ -75,14 +_,14 @@
mutableBlockPos.move(Direction.UP);
}
- return super.createPath(mutableBlockPos.immutable(), accuracy);
+ return super.createPath(mutableBlockPos.immutable(), entity, accuracy); // Paper - EntityPathfindEvent
}
}
}
@Override
public Path createPath(Entity entity, int i) {
- return this.createPath(entity.blockPosition(), i);
+ return this.createPath(entity.blockPosition(), entity, i); // Paper - EntityPathfindEvent
}
private int getSurfaceY() {

View File

@@ -0,0 +1,106 @@
--- a/net/minecraft/world/entity/ai/navigation/PathNavigation.java
+++ b/net/minecraft/world/entity/ai/navigation/PathNavigation.java
@@ -125,7 +_,13 @@
@Nullable
public Path createPath(BlockPos pos, int accuracy) {
- return this.createPath(ImmutableSet.of(pos), 8, false, accuracy);
+ // Paper start - EntityPathfindEvent
+ return this.createPath(pos, null, accuracy);
+ }
+ @Nullable
+ public Path createPath(BlockPos target, @Nullable Entity entity, int accuracy) {
+ return this.createPath(ImmutableSet.of(target), entity, 8, false, accuracy);
+ // Paper end - EntityPathfindEvent
}
@Nullable
@@ -135,7 +_,7 @@
@Nullable
public Path createPath(Entity entity, int accuracy) {
- return this.createPath(ImmutableSet.of(entity.blockPosition()), 16, true, accuracy);
+ return this.createPath(ImmutableSet.of(entity.blockPosition()), entity, 16, true, accuracy); // Paper - EntityPathfindEvent
}
@Nullable
@@ -145,6 +_,18 @@
@Nullable
protected Path createPath(Set<BlockPos> targets, int regionOffset, boolean offsetUpward, int accuracy, float followRange) {
+ // Paper start - EntityPathfindEvent
+ return this.createPath(targets, null, regionOffset, offsetUpward, accuracy, followRange);
+ }
+
+ @Nullable
+ protected Path createPath(Set<BlockPos> targets, @Nullable Entity target, int regionOffset, boolean offsetUpward, int accuracy) {
+ return this.createPath(targets, target, regionOffset, offsetUpward, accuracy, (float) this.mob.getAttributeValue(Attributes.FOLLOW_RANGE));
+ }
+
+ @Nullable
+ protected Path createPath(Set<BlockPos> targets, @Nullable Entity target, int regionOffset, boolean offsetUpward, int accuracy, float followRange) {
+ // Paper end - EntityPathfindEvent
if (targets.isEmpty()) {
return null;
} else if (this.mob.getY() < this.level.getMinY()) {
@@ -154,6 +_,23 @@
} else if (this.path != null && !this.path.isDone() && targets.contains(this.targetPos)) {
return this.path;
} else {
+ // Paper start - EntityPathfindEvent
+ boolean copiedSet = false;
+ for (BlockPos possibleTarget : targets) {
+ if (!this.mob.getCommandSenderWorld().getWorldBorder().isWithinBounds(possibleTarget) || !new com.destroystokyo.paper.event.entity.EntityPathfindEvent(this.mob.getBukkitEntity(), // Paper - don't path out of world border
+ io.papermc.paper.util.MCUtil.toLocation(this.mob.level(), possibleTarget), target == null ? null : target.getBukkitEntity()).callEvent()) {
+ if (!copiedSet) {
+ copiedSet = true;
+ targets = new java.util.HashSet<>(targets);
+ }
+ // note: since we copy the set this remove call is safe, since we're iterating over the old copy
+ targets.remove(possibleTarget);
+ if (targets.isEmpty()) {
+ return null;
+ }
+ }
+ }
+ // Paper end - EntityPathfindEvent
ProfilerFiller profilerFiller = Profiler.get();
profilerFiller.push("pathfind");
BlockPos blockPos = offsetUpward ? this.mob.blockPosition().above() : this.mob.blockPosition();
@@ -171,6 +_,11 @@
}
}
+ // Paper start - Perf: Optimise pathfinding
+ private int lastFailure = 0;
+ private int pathfindFailures = 0;
+ // Paper end - Perf: Optimise pathfinding
+
public boolean moveTo(double x, double y, double z, double speed) {
return this.moveTo(this.createPath(x, y, z, 1), speed);
}
@@ -180,8 +_,23 @@
}
public boolean moveTo(Entity entity, double speed) {
+ // Paper start - Perf: Optimise pathfinding
+ if (this.pathfindFailures > 10 && this.path == null && net.minecraft.server.MinecraftServer.currentTick < this.lastFailure + 40) {
+ return false;
+ }
+ // Paper end - Perf: Optimise pathfinding
Path path = this.createPath(entity, 1);
- return path != null && this.moveTo(path, speed);
+ // Paper start - Perf: Optimise pathfinding
+ if (path != null && this.moveTo(path, speed)) {
+ this.lastFailure = 0;
+ this.pathfindFailures = 0;
+ return true;
+ } else {
+ this.pathfindFailures++;
+ this.lastFailure = net.minecraft.server.MinecraftServer.currentTick;
+ return false;
+ }
+ // Paper end - Perf: Optimise pathfinding
}
public boolean moveTo(@Nullable Path pathentity, double speed) {

View File

@@ -0,0 +1,14 @@
--- a/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java
+++ b/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java
@@ -16,9 +_,9 @@
}
@Override
- public Path createPath(BlockPos pos, int accuracy) {
+ public Path createPath(BlockPos pos, @Nullable Entity entity, int accuracy) {
this.pathToPosition = pos;
- return super.createPath(pos, accuracy);
+ return super.createPath(pos, entity, accuracy); // Paper - EntityPathfindEvent
}
@Override

View File

@@ -83,7 +83,7 @@
@@ -340,7 +_,7 @@
protected void createInventory() {
public void createInventory() {
SimpleContainer simpleContainer = this.inventory;
- this.inventory = new SimpleContainer(this.getInventorySize());
+ this.inventory = new SimpleContainer(this.getInventorySize(), (org.bukkit.entity.AbstractHorse) this.getBukkitEntity()); // CraftBukkit

View File

@@ -39,5 +39,5 @@
+ }
+ // CraftBukkit end
private NonNullList<ItemStack> items = NonNullList.withSize(27, ItemStack.EMPTY);
private final ContainerOpenersCounter openersCounter = new ContainerOpenersCounter() {
public final ContainerOpenersCounter openersCounter = new ContainerOpenersCounter() {
@Override

View File

@@ -2,7 +2,7 @@
+++ b/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.java
@@ -27,6 +_,42 @@
private final NonNullList<ItemStack> items = NonNullList.withSize(6, ItemStack.EMPTY);
private int lastInteractedSlot = -1;
public int lastInteractedSlot = -1;
+ // CraftBukkit start - add fields and methods
+ public java.util.List<org.bukkit.entity.HumanEntity> transaction = new java.util.ArrayList<>();

View File

@@ -2,10 +2,10 @@
+++ b/net/minecraft/world/level/dimension/end/EndDragonFight.java
@@ -92,7 +_,7 @@
@Nullable
private BlockPos portalLocation;
public BlockPos portalLocation;
@Nullable
- private DragonRespawnAnimation respawnStage;
- public DragonRespawnAnimation respawnStage;
+ public DragonRespawnAnimation respawnStage;// Paper-At: public net.minecraft.world.level.dimension.end.EndDragonFight respawnStage
private int respawnTime;
@Nullable
private List<EndCrystal> respawnCrystals;
public List<EndCrystal> respawnCrystals;