Paper/patches/server/0695-Add-paper-mobcaps-and-paper-playermobcaps.patch

342 lines
16 KiB
Diff
Raw Normal View History

From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Jason Penilla <11360596+jpenilla@users.noreply.github.com>
Date: Mon, 16 Aug 2021 01:31:54 -0500
Subject: [PATCH] Add '/paper mobcaps' and '/paper playermobcaps'
Add commands to get the mobcaps for a world, as well as the mobcaps for
each player when per-player mob spawning is enabled.
Also has a hover text on each mob category listing what entity types are
in said category
diff --git a/src/main/java/io/papermc/paper/command/PaperCommand.java b/src/main/java/io/papermc/paper/command/PaperCommand.java
2023-03-15 13:19:54 +01:00
index 6d56c812262f7f109598ef4a941d0226b1eb638a..db9567711f7e0ad1778d41e79b59e31916aa9f09 100644
--- a/src/main/java/io/papermc/paper/command/PaperCommand.java
+++ b/src/main/java/io/papermc/paper/command/PaperCommand.java
2023-03-15 13:19:54 +01:00
@@ -43,6 +43,7 @@ public final class PaperCommand extends Command {
Rewrite chunk system (#8177) Patch documentation to come Issues with the old system that are fixed now: - World generation does not scale with cpu cores effectively. - Relies on the main thread for scheduling and maintaining chunk state, dropping chunk load/generate rates at lower tps. - Unreliable prioritisation of chunk gen/load calls that block the main thread. - Shutdown logic is utterly unreliable, as it has to wait for all chunks to unload - is it guaranteed that the chunk system is in a state on shutdown that it can reliably do this? Watchdog shutdown also typically failed due to thread checks, which is now resolved. - Saving of data is not unified (i.e can save chunk data without saving entity data, poses problems for desync if shutdown is really abnormal. - Entities are not loaded with chunks. This caused quite a bit of headache for Chunk#getEntities API, but now the new chunk system loads entities with chunks so that they are ready whenever the chunk loads in. Effectively brings the behavior back to 1.16 era, but still storing entities in their own separate regionfiles. The above list is not complete. The patch documentation will complete it. New chunk system hard relies on starlight and dataconverter, and most importantly the new concurrent utilities in ConcurrentUtil. Some of the old async chunk i/o interface (i.e the old file io thread reroutes _some_ calls to the new file io thread) is kept for plugin compat reasons. It will be removed in the next major version of minecraft. The old legacy chunk system patches have been moved to the removed folder in case we need them again.
2022-09-26 10:02:51 +02:00
commands.put(Set.of("debug", "chunkinfo", "holderinfo"), new ChunkDebugCommand());
commands.put(Set.of("syncloadinfo"), new SyncLoadInfoCommand());
commands.put(Set.of("dumpitem"), new DumpItemCommand());
+ commands.put(Set.of("mobcaps", "playermobcaps"), new MobcapsCommand());
return commands.entrySet().stream()
.flatMap(entry -> entry.getKey().stream().map(s -> Map.entry(s, entry.getValue())))
diff --git a/src/main/java/io/papermc/paper/command/subcommands/MobcapsCommand.java b/src/main/java/io/papermc/paper/command/subcommands/MobcapsCommand.java
new file mode 100644
2022-12-08 00:49:41 +01:00
index 0000000000000000000000000000000000000000..99c41a39cdad0271d089c6e03bebfdafba1aaa57
--- /dev/null
+++ b/src/main/java/io/papermc/paper/command/subcommands/MobcapsCommand.java
@@ -0,0 +1,229 @@
+package io.papermc.paper.command.subcommands;
+
+import com.google.common.collect.ImmutableMap;
+import io.papermc.paper.command.CommandUtil;
+import io.papermc.paper.command.PaperSubcommand;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.function.ToIntFunction;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.ComponentLike;
2021-11-28 07:56:41 +01:00
+import net.kyori.adventure.text.JoinConfiguration;
+import net.kyori.adventure.text.TextComponent;
+import net.kyori.adventure.text.format.NamedTextColor;
+import net.kyori.adventure.text.format.TextColor;
2022-12-08 00:49:41 +01:00
+import net.minecraft.core.registries.BuiltInRegistries;
+import net.minecraft.server.level.ServerLevel;
+import net.minecraft.server.level.ServerPlayer;
+import net.minecraft.world.entity.MobCategory;
+import net.minecraft.world.level.NaturalSpawner;
+import org.bukkit.Bukkit;
+import org.bukkit.World;
+import org.bukkit.command.CommandSender;
+import org.bukkit.craftbukkit.CraftWorld;
+import org.bukkit.craftbukkit.entity.CraftPlayer;
+import org.bukkit.entity.Player;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.checkerframework.framework.qual.DefaultQualifier;
+
+@DefaultQualifier(NonNull.class)
+public final class MobcapsCommand implements PaperSubcommand {
+ static final Map<MobCategory, TextColor> MOB_CATEGORY_COLORS = ImmutableMap.<MobCategory, TextColor>builder()
+ .put(MobCategory.MONSTER, NamedTextColor.RED)
+ .put(MobCategory.CREATURE, NamedTextColor.GREEN)
+ .put(MobCategory.AMBIENT, NamedTextColor.GRAY)
+ .put(MobCategory.AXOLOTLS, TextColor.color(0x7324FF))
+ .put(MobCategory.UNDERGROUND_WATER_CREATURE, TextColor.color(0x3541E6))
+ .put(MobCategory.WATER_CREATURE, TextColor.color(0x006EFF))
+ .put(MobCategory.WATER_AMBIENT, TextColor.color(0x00B3FF))
+ .put(MobCategory.MISC, TextColor.color(0x636363))
+ .build();
+
+ @Override
+ public boolean execute(final CommandSender sender, final String subCommand, final String[] args) {
+ switch (subCommand) {
+ case "mobcaps" -> this.printMobcaps(sender, args);
+ case "playermobcaps" -> this.printPlayerMobcaps(sender, args);
+ }
+ return true;
+ }
+
+ @Override
+ public List<String> tabComplete(final CommandSender sender, final String subCommand, final String[] args) {
+ return switch (subCommand) {
+ case "mobcaps" -> CommandUtil.getListMatchingLast(sender, args, this.suggestMobcaps(args));
+ case "playermobcaps" -> CommandUtil.getListMatchingLast(sender, args, this.suggestPlayerMobcaps(sender, args));
+ default -> throw new IllegalArgumentException();
+ };
+ }
+
+ private List<String> suggestMobcaps(final String[] args) {
+ if (args.length == 1) {
+ final List<String> worlds = new ArrayList<>(Bukkit.getWorlds().stream().map(World::getName).toList());
+ worlds.add("*");
+ return worlds;
+ }
+
+ return Collections.emptyList();
+ }
+
+ private List<String> suggestPlayerMobcaps(final CommandSender sender, final String[] args) {
+ if (args.length == 1) {
+ final List<String> list = new ArrayList<>();
+ for (final Player player : Bukkit.getOnlinePlayers()) {
+ if (!(sender instanceof Player senderPlayer) || senderPlayer.canSee(player)) {
+ list.add(player.getName());
+ }
+ }
+ return list;
+ }
+
+ return Collections.emptyList();
+ }
+
+ private void printMobcaps(final CommandSender sender, final String[] args) {
+ final List<World> worlds;
+ if (args.length == 0) {
+ if (sender instanceof Player player) {
+ worlds = List.of(player.getWorld());
+ } else {
+ sender.sendMessage(Component.text("Must specify a world! ex: '/paper mobcaps world'", NamedTextColor.RED));
+ return;
+ }
+ } else if (args.length == 1) {
+ final String input = args[0];
+ if (input.equals("*")) {
+ worlds = Bukkit.getWorlds();
+ } else {
+ final @Nullable World world = Bukkit.getWorld(input);
+ if (world == null) {
+ sender.sendMessage(Component.text("'" + input + "' is not a valid world!", NamedTextColor.RED));
+ return;
+ } else {
+ worlds = List.of(world);
+ }
+ }
+ } else {
+ sender.sendMessage(Component.text("Too many arguments!", NamedTextColor.RED));
+ return;
+ }
+
+ for (final World world : worlds) {
+ final ServerLevel level = ((CraftWorld) world).getHandle();
+ final NaturalSpawner.@Nullable SpawnState state = level.getChunkSource().getLastSpawnState();
+
+ final int chunks;
+ if (state == null) {
+ chunks = 0;
+ } else {
+ chunks = state.getSpawnableChunkCount();
+ }
2021-11-28 07:56:41 +01:00
+ sender.sendMessage(Component.join(JoinConfiguration.noSeparators(),
+ Component.text("Mobcaps for world: "),
+ Component.text(world.getName(), NamedTextColor.AQUA),
+ Component.text(" (" + chunks + " spawnable chunks)")
+ ));
+
+ sender.sendMessage(createMobcapsComponent(
+ category -> {
+ if (state == null) {
+ return 0;
+ } else {
+ return state.getMobCategoryCounts().getOrDefault(category, 0);
+ }
+ },
+ category -> NaturalSpawner.globalLimitForCategory(level, category, chunks)
+ ));
+ }
+ }
+
+ private void printPlayerMobcaps(final CommandSender sender, final String[] args) {
+ final @Nullable Player player;
+ if (args.length == 0) {
+ if (sender instanceof Player pl) {
+ player = pl;
+ } else {
+ sender.sendMessage(Component.text("Must specify a player! ex: '/paper playermobcount playerName'", NamedTextColor.RED));
+ return;
+ }
+ } else if (args.length == 1) {
+ final String input = args[0];
+ player = Bukkit.getPlayerExact(input);
+ if (player == null) {
+ sender.sendMessage(Component.text("Could not find player named '" + input + "'", NamedTextColor.RED));
+ return;
+ }
+ } else {
+ sender.sendMessage(Component.text("Too many arguments!", NamedTextColor.RED));
+ return;
+ }
+
+ final ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle();
+ final ServerLevel level = serverPlayer.getLevel();
+
+ if (!level.paperConfig().entities.spawning.perPlayerMobSpawns) {
+ sender.sendMessage(Component.text("Use '/paper mobcaps' for worlds where per-player mob spawning is disabled.", NamedTextColor.RED));
+ return;
+ }
+
2021-11-28 07:56:41 +01:00
+ sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), Component.text("Mobcaps for player: "), Component.text(player.getName(), NamedTextColor.GREEN)));
+ sender.sendMessage(createMobcapsComponent(
+ category -> level.chunkSource.chunkMap.getMobCountNear(serverPlayer, category),
+ category -> level.getWorld().getSpawnLimitUnsafe(org.bukkit.craftbukkit.util.CraftSpawnCategory.toBukkit(category))
+ ));
+ }
+
+ private static Component createMobcapsComponent(final ToIntFunction<MobCategory> countGetter, final ToIntFunction<MobCategory> limitGetter) {
+ return MOB_CATEGORY_COLORS.entrySet().stream()
+ .map(entry -> {
+ final MobCategory category = entry.getKey();
+ final TextColor color = entry.getValue();
+
2021-11-28 07:56:41 +01:00
+ final Component categoryHover = Component.join(JoinConfiguration.noSeparators(),
+ Component.text("Entity types in category ", TextColor.color(0xE0E0E0)),
+ Component.text(category.getName(), color),
+ Component.text(':', NamedTextColor.GRAY),
+ Component.newline(),
+ Component.newline(),
2022-12-08 00:49:41 +01:00
+ BuiltInRegistries.ENTITY_TYPE.entrySet().stream()
+ .filter(it -> it.getValue().getCategory() == category)
+ .map(it -> Component.translatable(it.getValue().getDescriptionId()))
+ .collect(Component.toComponent(Component.text(", ", NamedTextColor.GRAY)))
+ );
+
+ final Component categoryComponent = Component.text()
+ .content(" " + category.getName())
+ .color(color)
+ .hoverEvent(categoryHover)
+ .build();
+
+ final TextComponent.Builder builder = Component.text()
+ .append(
+ categoryComponent,
+ Component.text(": ", NamedTextColor.GRAY)
+ );
+ final int limit = limitGetter.applyAsInt(category);
+ if (limit != -1) {
+ builder.append(
+ Component.text(countGetter.applyAsInt(category)),
+ Component.text("/", NamedTextColor.GRAY),
+ Component.text(limit)
+ );
+ } else {
+ builder.append(Component.text()
+ .append(
+ Component.text('n'),
+ Component.text("/", NamedTextColor.GRAY),
+ Component.text('a')
+ )
+ .hoverEvent(Component.text("This category does not naturally spawn.")));
+ }
+ return builder;
+ })
+ .map(ComponentLike::asComponent)
+ .collect(Component.toComponent(Component.newline()));
+ }
+}
diff --git a/src/main/java/net/minecraft/world/level/NaturalSpawner.java b/src/main/java/net/minecraft/world/level/NaturalSpawner.java
2023-03-14 21:25:13 +01:00
index a1770e5ae4b3014c3538b52d4912c60864e186a8..906def91bba96bab7c7aea9b87d9ec56374e6588 100644
--- a/src/main/java/net/minecraft/world/level/NaturalSpawner.java
+++ b/src/main/java/net/minecraft/world/level/NaturalSpawner.java
2022-12-07 22:05:01 +01:00
@@ -192,6 +192,16 @@ public final class NaturalSpawner {
world.getProfiler().pop();
}
+ // Paper start
+ public static int globalLimitForCategory(final ServerLevel level, final MobCategory category, final int spawnableChunkCount) {
+ final int categoryLimit = level.getWorld().getSpawnLimitUnsafe(CraftSpawnCategory.toBukkit(category));
+ if (categoryLimit < 1) {
+ return categoryLimit;
+ }
+ return categoryLimit * spawnableChunkCount / NaturalSpawner.MAGIC_NUMBER;
+ }
+ // Paper end
+
public static void spawnCategoryForChunk(MobCategory group, ServerLevel world, LevelChunk chunk, NaturalSpawner.SpawnPredicate checker, NaturalSpawner.AfterSpawnCallback runner) {
// Paper start - add parameters and int ret type
spawnCategoryForChunk(group, world, chunk, checker, runner, Integer.MAX_VALUE, null);
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
index 826e288f633a2a7cea9fa0022b44947f75fc1163..95015ceeb458d44229d7a23bbcb092c07f5d322e 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
@@ -2164,6 +2164,11 @@ public final class CraftServer implements Server {
@Override
public int getSpawnLimit(SpawnCategory spawnCategory) {
+ // Paper start
+ return this.getSpawnLimitUnsafe(spawnCategory);
+ }
+ public int getSpawnLimitUnsafe(final SpawnCategory spawnCategory) {
+ // Paper end
return this.spawnCategoryLimit.getOrDefault(spawnCategory, -1);
}
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
index 53d1dee6e81697ff2d9d498f27b57882a9418702..ea8a372a13b7729121e084a79540b317a4c028e1 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
Updated Upstream (Bukkit/CraftBukkit/Spigot) (#9188) * Updated Upstream (Bukkit/CraftBukkit/Spigot) Upstream has released updates that appear to apply and compile correctly. This update has not been tested by PaperMC and as with ANY update, please do your own testing Bukkit Changes: 2fcba9b2 SPIGOT-7347: Add missing documentation and details to ShapedRecipe c278419d PR-854: Move getHighestBlockYAt methods from World to RegionAccessor 201399fb PR-853: Add API for directly setting Display transformation matrices ecfa559a PR-849: Add InventoryView#setTitle 653d7edb SPIGOT-519: Add TNTPrimeEvent 22fccc09 PR-846: Add method to get chunk load level a070a52c PR-844: Add methods to convert Vector to and from JOML vectors cc7111fe PR-276: Add accessors to Wither's invulnerability ticks 777d24e9 SPIGOT-7209: Accessors and events for player's exp cooldown ccb2d01b SPIGOT-6308: Deprecate the location name property of map items cd04a31b PR-780: Add PlayerSpawnChangeEvent 7d1f5b64 SPIGOT-6780: Improve documentation for World#spawnFallingBlock 5696668a SPIGOT-6885: Add test and easier to debug code for reference in yaml configuration comments 2e13cff7 PR-589: Expand the FishHook API 2c7d3da5 PR-279: Minor edits to various Javadocs CraftBukkit Changes: 01b2e1af4 SPIGOT-7346: Disallow players from executing commands after disconnecting 7fe5ee022 PR-1186: Move getHighestBlockYAt methods from World to RegionAccessor bcc85ef67 PR-1185: Add API for directly setting Display transformation matrices a7cfc778f PR-1176: Add InventoryView#setTitle 563d42226 SPIGOT-519: Add TNTPrimeEvent ccbc6abca Add test for Chunk.LoadLevel mirroring 2926e0513 PR-1171: Add method to get chunk load level 63cad7f84 PR-375: Add accessors to Wither's invulnerability ticks bfd8b1ac8 SPIGOT-7209: Accessors and events for player's exp cooldown f92a41c39 PR-1181: Consolidate Location conversion code 10f866759 SPIGOT-6308: Deprecate the location name property of map items 82f7b658a PR-1095: Add PlayerSpawnChangeEvent b421af7e4 PR-808: Expand the FishHook API 598ad7b3f Increase outdated build delay Spigot Changes: d1bd3bd2 Rebuild patches e4265cc8 SPIGOT-7297: Entity Tracking Range option for Display entities * Work around javac bug * Call PlayerSpawnChangeEvent * Updated Upstream (Bukkit/CraftBukkit/Spigot) Upstream has released updates that appear to apply and compile correctly. This update has not been tested by PaperMC and as with ANY update, please do your own testing Bukkit Changes: 2fcba9b2 SPIGOT-7347: Add missing documentation and details to ShapedRecipe c278419d PR-854: Move getHighestBlockYAt methods from World to RegionAccessor 201399fb PR-853: Add API for directly setting Display transformation matrices CraftBukkit Changes: 01b2e1af4 SPIGOT-7346: Disallow players from executing commands after disconnecting 7fe5ee022 PR-1186: Move getHighestBlockYAt methods from World to RegionAccessor bcc85ef67 PR-1185: Add API for directly setting Display transformation matrices Spigot Changes: 7da74dae Rebuild patches
2023-05-12 13:10:08 +02:00
@@ -1696,9 +1696,14 @@ public class CraftWorld extends CraftRegionAccessor implements World {
Validate.notNull(spawnCategory, "SpawnCategory cannot be null");
Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported.");
+ // Paper start
+ return this.getSpawnLimitUnsafe(spawnCategory);
+ }
+ public final int getSpawnLimitUnsafe(final SpawnCategory spawnCategory) {
int limit = this.spawnCategoryLimit.getOrDefault(spawnCategory, -1);
if (limit < 0) {
- limit = this.server.getSpawnLimit(spawnCategory);
+ limit = this.server.getSpawnLimitUnsafe(spawnCategory);
+ // Paper end
}
return limit;
}
diff --git a/src/test/java/io/papermc/paper/command/subcommands/MobcapsCommandTest.java b/src/test/java/io/papermc/paper/command/subcommands/MobcapsCommandTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..f1dd3bca7fa0df8b6ed177bb435877229af1c0c5
--- /dev/null
+++ b/src/test/java/io/papermc/paper/command/subcommands/MobcapsCommandTest.java
@@ -0,0 +1,20 @@
+package io.papermc.paper.command.subcommands;
+
+import java.util.HashSet;
+import java.util.Set;
+import net.minecraft.world.entity.MobCategory;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class MobcapsCommandTest {
+ @Test
+ public void testMobCategoryColors() {
+ final Set<String> missing = new HashSet<>();
+ for (final MobCategory value : MobCategory.values()) {
+ if (!MobcapsCommand.MOB_CATEGORY_COLORS.containsKey(value)) {
+ missing.add(value.getName());
+ }
+ }
+ Assert.assertTrue("MobcapsCommand.MOB_CATEGORY_COLORS map missing TextColors for [" + String.join(", ", missing + "]"), missing.isEmpty());
+ }
+}