From 29e03d0439da628f6aeff55ad74b5b1d53e24faf Mon Sep 17 00:00:00 2001
From: Spottedleaf <Spottedleaf@users.noreply.github.com>
Date: Fri, 25 Oct 2024 14:20:40 -0700
Subject: [PATCH] Add startup flag to disable gamerule limits

-DPaper.DisableGameRuleLimits=true will disable gamerule limits

== AT ==
public net.minecraft.server.level.ChunkLevel ENTITY_TICKING_LEVEL
---
 .../server/level/ServerLevel.java.patch       | 85 ++++++++++++-------
 .../world/level/GameRules.java.patch          | 64 +++++++++-----
 2 files changed, 95 insertions(+), 54 deletions(-)

diff --git a/paper-server/patches/sources/net/minecraft/server/level/ServerLevel.java.patch b/paper-server/patches/sources/net/minecraft/server/level/ServerLevel.java.patch
index 764f2ccdd2..7c6302e430 100644
--- a/paper-server/patches/sources/net/minecraft/server/level/ServerLevel.java.patch
+++ b/paper-server/patches/sources/net/minecraft/server/level/ServerLevel.java.patch
@@ -80,7 +80,7 @@
 +    public final UUID uuid;
 +    public boolean hasPhysicsEvent = true; // Paper - BlockPhysicsEvent
 +    public boolean hasEntityMoveEvent; // Paper - Add EntityMoveEvent
-+
+ 
 +    public LevelChunk getChunkIfLoaded(int x, int z) {
 +        return this.chunkSource.getChunkAtIfLoadedImmediately(x, z); // Paper - Use getChunkIfLoadedImmediately
 +    }
@@ -142,7 +142,7 @@
 +
 +        this.loadChunks(minChunkX, minChunkZ, maxChunkX, maxChunkZ, priority, onLoad);
 +    }
- 
++
 +    public final void loadChunks(int minChunkX, int minChunkZ, int maxChunkX, int maxChunkZ,
 +                                 ca.spottedleaf.concurrentutil.util.Priority priority,
 +                                 java.util.function.Consumer<List<net.minecraft.world.level.chunk.ChunkAccess>> onLoad) {
@@ -615,19 +615,18 @@
 +        return this.addFreshEntity(entity, CreatureSpawnEvent.SpawnReason.DEFAULT);
      }
  
--    public boolean addWithUUID(Entity entity) {
--        return this.addEntity(entity);
 +    @Override
 +    public boolean addFreshEntity(Entity entity, CreatureSpawnEvent.SpawnReason reason) {
 +        return this.addEntity(entity, reason);
 +        // CraftBukkit end
-     }
- 
-+    public boolean addWithUUID(Entity entity) {
-+        // CraftBukkit start
-+        return this.addWithUUID(entity, CreatureSpawnEvent.SpawnReason.DEFAULT);
 +    }
 +
+     public boolean addWithUUID(Entity entity) {
+-        return this.addEntity(entity);
++        // CraftBukkit start
++        return this.addWithUUID(entity, CreatureSpawnEvent.SpawnReason.DEFAULT);
+     }
+ 
 +    public boolean addWithUUID(Entity entity, CreatureSpawnEvent.SpawnReason reason) {
 +        return this.addEntity(entity, reason);
 +        // CraftBukkit end
@@ -731,8 +730,8 @@
      public void removePlayerImmediately(ServerPlayer player, Entity.RemovalReason reason) {
 -        player.remove(reason);
 +        player.remove(reason, null); // CraftBukkit - add Bukkit remove cause
-+    }
-+
+     }
+ 
 +    // CraftBukkit start
 +    public boolean strikeLightning(Entity entitylightning) {
 +        return this.strikeLightning(entitylightning, LightningStrikeEvent.Cause.UNKNOWN);
@@ -746,9 +745,9 @@
 +        }
 +
 +        return this.addFreshEntity(entitylightning);
-     }
++    }
 +    // CraftBukkit end
- 
++
      @Override
      public void destroyBlockProgress(int entityId, BlockPos pos, int progress) {
          Iterator iterator = this.server.getPlayerList().getPlayers().iterator();
@@ -930,9 +929,12 @@
  
      public <T extends ParticleOptions> int sendParticles(T parameters, boolean force, boolean important, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double speed) {
 -        ClientboundLevelParticlesPacket packetplayoutworldparticles = new ClientboundLevelParticlesPacket(parameters, force, important, x, y, z, (float) offsetX, (float) offsetY, (float) offsetZ, (float) speed, count);
+-        int j = 0;
 +        return this.sendParticlesSource(null, parameters, force, important, x, y, z, count, offsetX, offsetY, offsetZ, speed); // CraftBukkit - visibility api support
 +    }
-+
+ 
+-        for (int k = 0; k < this.players.size(); ++k) {
+-            ServerPlayer entityplayer = (ServerPlayer) this.players.get(k);
 +    // CraftBukkit start - visibility api support
 +    public <T extends ParticleOptions> int sendParticlesSource(ServerPlayer sender, T t0, boolean flag, boolean flag1, double d0, double d1, double d2, int i, double d3, double d4, double d5, double d6) {
 +        // Paper start - Particle API
@@ -942,15 +944,13 @@
 +        // Paper end - Particle API
 +        // CraftBukkit end
 +        ClientboundLevelParticlesPacket packetplayoutworldparticles = new ClientboundLevelParticlesPacket(t0, flag, flag1, d0, d1, d2, (float) d3, (float) d4, (float) d5, (float) d6, i);
-         int j = 0;
++        int j = 0;
  
--        for (int k = 0; k < this.players.size(); ++k) {
--            ServerPlayer entityplayer = (ServerPlayer) this.players.get(k);
+-            if (this.sendParticles(entityplayer, force, x, y, z, packetplayoutworldparticles)) {
 +        for (Player entityhuman : receivers) { // Paper - Particle API
 +            ServerPlayer entityplayer = (ServerPlayer) entityhuman; // Paper - Particle API
 +            if (sender != null && !entityplayer.getBukkitEntity().canSee(sender.getBukkitEntity())) continue; // CraftBukkit
- 
--            if (this.sendParticles(entityplayer, force, x, y, z, packetplayoutworldparticles)) {
++
 +            if (this.sendParticles(entityplayer, flag, d0, d1, d2, packetplayoutworldparticles)) {
                  ++j;
              }
@@ -1004,7 +1004,7 @@
          this.getServer().overworld().getDataStorage().set(id.key(), state);
      }
  
-@@ -1352,7 +1768,9 @@
+@@ -1352,18 +1768,28 @@
          float f1 = this.levelData.getSpawnAngle();
  
          if (!blockposition1.equals(pos) || f1 != angle) {
@@ -1014,7 +1014,28 @@
              this.getServer().getPlayerList().broadcastAll(new ClientboundSetDefaultSpawnPositionPacket(pos, angle));
          }
  
-@@ -1419,6 +1837,11 @@
+         if (this.lastSpawnChunkRadius > 1) {
+-            this.getChunkSource().removeRegionTicket(TicketType.START, new ChunkPos(blockposition1), this.lastSpawnChunkRadius, Unit.INSTANCE);
++            // Paper start - allow disabling gamerule limits
++            for (ChunkPos chunkPos : io.papermc.paper.util.MCUtil.getSpiralOutChunks(blockposition1, this.lastSpawnChunkRadius - 2)) {
++                this.getChunkSource().removeTicketAtLevel(TicketType.START, chunkPos, net.minecraft.server.level.ChunkLevel.ENTITY_TICKING_LEVEL, Unit.INSTANCE);
++            }
++            // Paper end - allow disabling gamerule limits
+         }
+ 
+         int i = this.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS) + 1;
+ 
+         if (i > 1) {
+-            this.getChunkSource().addRegionTicket(TicketType.START, new ChunkPos(pos), i, Unit.INSTANCE);
++            // Paper start - allow disabling gamerule limits
++            for (ChunkPos chunkPos : io.papermc.paper.util.MCUtil.getSpiralOutChunks(pos, i - 2)) {
++                this.getChunkSource().addTicketAtLevel(TicketType.START, chunkPos, net.minecraft.server.level.ChunkLevel.ENTITY_TICKING_LEVEL, Unit.INSTANCE);
++            }
++            // Paper end - allow disabling gamerule limits
+         }
+ 
+         this.lastSpawnChunkRadius = i;
+@@ -1419,6 +1845,11 @@
              });
              optional1.ifPresent((holder) -> {
                  this.getServer().execute(() -> {
@@ -1026,7 +1047,7 @@
                      this.getPoiManager().add(blockposition1, holder);
                      DebugPackets.sendPoiAddedPacket(this, blockposition1);
                  });
-@@ -1649,6 +2072,11 @@
+@@ -1649,6 +2080,11 @@
      @Override
      public void blockUpdated(BlockPos pos, Block block) {
          if (!this.isDebug()) {
@@ -1038,7 +1059,7 @@
              this.updateNeighborsAt(pos, block);
          }
  
-@@ -1668,12 +2096,12 @@
+@@ -1668,12 +2104,12 @@
      }
  
      public boolean isFlat() {
@@ -1053,7 +1074,7 @@
      }
  
      @Nullable
-@@ -1696,7 +2124,7 @@
+@@ -1696,7 +2132,7 @@
      private static <T> String getTypeCount(Iterable<T> items, Function<T, String> classifier) {
          try {
              Object2IntOpenHashMap<String> object2intopenhashmap = new Object2IntOpenHashMap();
@@ -1062,7 +1083,7 @@
  
              while (iterator.hasNext()) {
                  T t0 = iterator.next();
-@@ -1705,7 +2133,7 @@
+@@ -1705,7 +2141,7 @@
                  object2intopenhashmap.addTo(s, 1);
              }
  
@@ -1071,7 +1092,7 @@
                  String s1 = (String) entry.getKey();
  
                  return s1 + ":" + entry.getIntValue();
-@@ -1717,6 +2145,7 @@
+@@ -1717,6 +2153,7 @@
  
      @Override
      public LevelEntityGetter<Entity> getEntities() {
@@ -1079,7 +1100,7 @@
          return this.entityManager.getEntityGetter();
      }
  
-@@ -1802,6 +2231,27 @@
+@@ -1802,6 +2239,27 @@
          return this.serverLevelData.getGameRules();
      }
  
@@ -1107,7 +1128,7 @@
      @Override
      public CrashReportCategory fillReportDetails(CrashReport report) {
          CrashReportCategory crashreportsystemdetails = super.fillReportDetails(report);
-@@ -1828,6 +2278,7 @@
+@@ -1828,6 +2286,7 @@
          }
  
          public void onTickingStart(Entity entity) {
@@ -1115,7 +1136,7 @@
              ServerLevel.this.entityTickList.add(entity);
          }
  
-@@ -1836,14 +2287,15 @@
+@@ -1836,14 +2295,15 @@
          }
  
          public void onTrackingStart(Entity entity) {
@@ -1133,7 +1154,7 @@
                      String s = "onTrackingStart called during navigation iteration";
  
                      Util.logAndPauseIfInIde("onTrackingStart called during navigation iteration", new IllegalStateException("onTrackingStart called during navigation iteration"));
-@@ -1864,9 +2316,58 @@
+@@ -1864,9 +2324,58 @@
              }
  
              entity.updateDynamicGameEventListener(DynamicGameEventListener::add);
@@ -1192,7 +1213,7 @@
              ServerLevel.this.getChunkSource().removeEntity(entity);
              if (entity instanceof ServerPlayer entityplayer) {
                  ServerLevel.this.players.remove(entityplayer);
-@@ -1874,7 +2375,7 @@
+@@ -1874,7 +2383,7 @@
              }
  
              if (entity instanceof Mob entityinsentient) {
@@ -1201,7 +1222,7 @@
                      String s = "onTrackingStart called during navigation iteration";
  
                      Util.logAndPauseIfInIde("onTrackingStart called during navigation iteration", new IllegalStateException("onTrackingStart called during navigation iteration"));
-@@ -1895,10 +2396,27 @@
+@@ -1895,10 +2404,27 @@
              }
  
              entity.updateDynamicGameEventListener(DynamicGameEventListener::remove);
diff --git a/paper-server/patches/sources/net/minecraft/world/level/GameRules.java.patch b/paper-server/patches/sources/net/minecraft/world/level/GameRules.java.patch
index 1d154faa46..13a583766e 100644
--- a/paper-server/patches/sources/net/minecraft/world/level/GameRules.java.patch
+++ b/paper-server/patches/sources/net/minecraft/world/level/GameRules.java.patch
@@ -1,6 +1,21 @@
 --- a/net/minecraft/world/level/GameRules.java
 +++ b/net/minecraft/world/level/GameRules.java
-@@ -58,7 +58,7 @@
+@@ -36,6 +36,14 @@
+ 
+ public class GameRules {
+ 
++    // Paper start - allow disabling gamerule limits
++    private static final boolean DISABLE_LIMITS = Boolean.getBoolean("paper.disableGameRuleLimits");
++
++    private static int limit(final int limit, final int unlimited) {
++        return DISABLE_LIMITS ? unlimited : limit;
++    }
++    // Paper end - allow disabling gamerule limits
++
+     public static final int DEFAULT_RANDOM_TICK_SPEED = 3;
+     static final Logger LOGGER = LogUtils.getLogger();
+     private static final Map<GameRules.Key<?>, GameRules.Type<?>> GAME_RULE_TYPES = Maps.newTreeMap(Comparator.comparing((gamerules_gamerulekey) -> {
+@@ -58,7 +66,7 @@
      public static final GameRules.Key<GameRules.BooleanValue> RULE_SENDCOMMANDFEEDBACK = GameRules.register("sendCommandFeedback", GameRules.Category.CHAT, GameRules.BooleanValue.create(true));
      public static final GameRules.Key<GameRules.BooleanValue> RULE_REDUCEDDEBUGINFO = GameRules.register("reducedDebugInfo", GameRules.Category.MISC, GameRules.BooleanValue.create(false, (minecraftserver, gamerules_gameruleboolean) -> {
          int i = gamerules_gameruleboolean.get() ? 22 : 23;
@@ -9,7 +24,7 @@
  
          while (iterator.hasNext()) {
              ServerPlayer entityplayer = (ServerPlayer) iterator.next();
-@@ -74,7 +74,7 @@
+@@ -74,7 +82,7 @@
      public static final GameRules.Key<GameRules.IntegerValue> RULE_MAX_ENTITY_CRAMMING = GameRules.register("maxEntityCramming", GameRules.Category.MOBS, GameRules.IntegerValue.create(24));
      public static final GameRules.Key<GameRules.BooleanValue> RULE_WEATHER_CYCLE = GameRules.register("doWeatherCycle", GameRules.Category.UPDATES, GameRules.BooleanValue.create(true));
      public static final GameRules.Key<GameRules.BooleanValue> RULE_LIMITED_CRAFTING = GameRules.register("doLimitedCrafting", GameRules.Category.PLAYER, GameRules.BooleanValue.create(false, (minecraftserver, gamerules_gameruleboolean) -> {
@@ -18,7 +33,7 @@
  
          while (iterator.hasNext()) {
              ServerPlayer entityplayer = (ServerPlayer) iterator.next();
-@@ -90,7 +90,7 @@
+@@ -90,7 +98,7 @@
      public static final GameRules.Key<GameRules.BooleanValue> RULE_DISABLE_RAIDS = GameRules.register("disableRaids", GameRules.Category.MOBS, GameRules.BooleanValue.create(false));
      public static final GameRules.Key<GameRules.BooleanValue> RULE_DOINSOMNIA = GameRules.register("doInsomnia", GameRules.Category.SPAWNING, GameRules.BooleanValue.create(true));
      public static final GameRules.Key<GameRules.BooleanValue> RULE_DO_IMMEDIATE_RESPAWN = GameRules.register("doImmediateRespawn", GameRules.Category.PLAYER, GameRules.BooleanValue.create(false, (minecraftserver, gamerules_gameruleboolean) -> {
@@ -27,11 +42,16 @@
  
          while (iterator.hasNext()) {
              ServerPlayer entityplayer = (ServerPlayer) iterator.next();
-@@ -123,12 +123,13 @@
-     public static final GameRules.Key<GameRules.IntegerValue> RULE_MINECART_MAX_SPEED = GameRules.register("minecartMaxSpeed", GameRules.Category.MISC, GameRules.IntegerValue.create(8, 1, 1000, FeatureFlagSet.of(FeatureFlags.MINECART_IMPROVEMENTS), (minecraftserver, gamerules_gameruleint) -> {
+@@ -120,15 +128,16 @@
+     public static final GameRules.Key<GameRules.BooleanValue> RULE_GLOBAL_SOUND_EVENTS = GameRules.register("globalSoundEvents", GameRules.Category.MISC, GameRules.BooleanValue.create(true));
+     public static final GameRules.Key<GameRules.BooleanValue> RULE_DO_VINES_SPREAD = GameRules.register("doVinesSpread", GameRules.Category.UPDATES, GameRules.BooleanValue.create(true));
+     public static final GameRules.Key<GameRules.BooleanValue> RULE_ENDER_PEARLS_VANISH_ON_DEATH = GameRules.register("enderPearlsVanishOnDeath", GameRules.Category.PLAYER, GameRules.BooleanValue.create(true));
+-    public static final GameRules.Key<GameRules.IntegerValue> RULE_MINECART_MAX_SPEED = GameRules.register("minecartMaxSpeed", GameRules.Category.MISC, GameRules.IntegerValue.create(8, 1, 1000, FeatureFlagSet.of(FeatureFlags.MINECART_IMPROVEMENTS), (minecraftserver, gamerules_gameruleint) -> {
++    public static final GameRules.Key<GameRules.IntegerValue> RULE_MINECART_MAX_SPEED = GameRules.register("minecartMaxSpeed", GameRules.Category.MISC, GameRules.IntegerValue.create(8, 1, limit(1000, Integer.MAX_VALUE), FeatureFlagSet.of(FeatureFlags.MINECART_IMPROVEMENTS), (minecraftserver, gamerules_gameruleint) -> { // Paper - allow disabling gamerule limits
      }));
-     public static final GameRules.Key<GameRules.IntegerValue> RULE_SPAWN_CHUNK_RADIUS = GameRules.register("spawnChunkRadius", GameRules.Category.MISC, GameRules.IntegerValue.create(2, 0, 32, FeatureFlagSet.of(), (minecraftserver, gamerules_gameruleint) -> {
+-    public static final GameRules.Key<GameRules.IntegerValue> RULE_SPAWN_CHUNK_RADIUS = GameRules.register("spawnChunkRadius", GameRules.Category.MISC, GameRules.IntegerValue.create(2, 0, 32, FeatureFlagSet.of(), (minecraftserver, gamerules_gameruleint) -> {
 -        ServerLevel worldserver = minecraftserver.overworld();
++    public static final GameRules.Key<GameRules.IntegerValue> RULE_SPAWN_CHUNK_RADIUS = GameRules.register("spawnChunkRadius", GameRules.Category.MISC, GameRules.IntegerValue.create(2, 0, limit(32, Integer.MAX_VALUE), FeatureFlagSet.of(), (minecraftserver, gamerules_gameruleint) -> { // Paper - allow disabling gamerule limits
 +        ServerLevel worldserver = minecraftserver; // CraftBukkit - per-world
  
          worldserver.setDefaultSpawnPos(worldserver.getSharedSpawnPos(), worldserver.getSharedSpawnAngle());
@@ -42,7 +62,7 @@
  
      private static <T extends GameRules.Value<T>> GameRules.Key<T> register(String name, GameRules.Category category, GameRules.Type<T> type) {
          GameRules.Key<T> gamerules_gamerulekey = new GameRules.Key<>(name, category);
-@@ -161,10 +162,21 @@
+@@ -161,10 +170,21 @@
      private GameRules(Map<GameRules.Key<?>, GameRules.Value<?>> rules, FeatureFlagSet enabledFeatures) {
          this.rules = rules;
          this.enabledFeatures = enabledFeatures;
@@ -65,7 +85,7 @@
  
          if (t0 == null) {
              throw new IllegalArgumentException("Tried to access invalid game rule");
-@@ -184,7 +196,7 @@
+@@ -184,7 +204,7 @@
  
      private void loadFromTag(DynamicLike<?> values) {
          this.rules.forEach((gamerules_gamerulekey, gamerules_gamerulevalue) -> {
@@ -74,7 +94,7 @@
  
              Objects.requireNonNull(gamerules_gamerulevalue);
              dataresult.ifSuccess(gamerules_gamerulevalue::deserialize);
-@@ -205,22 +217,22 @@
+@@ -205,22 +225,22 @@
  
      private <T extends GameRules.Value<T>> void callVisitorCap(GameRules.GameRuleTypeVisitor visitor, GameRules.Key<?> key, GameRules.Type<?> type) {
          if (type.requiredFeatures.isSubsetOf(this.enabledFeatures)) {
@@ -105,7 +125,7 @@
      }
  
      public boolean getBoolean(GameRules.Key<GameRules.BooleanValue> rule) {
-@@ -232,6 +244,10 @@
+@@ -232,6 +252,10 @@
      }
  
      public static final class Key<T extends GameRules.Value<T>> {
@@ -116,7 +136,7 @@
  
          final String id;
          private final GameRules.Category category;
-@@ -285,11 +301,11 @@
+@@ -285,11 +309,11 @@
  
          final Supplier<ArgumentType<?>> argument;
          private final Function<GameRules.Type<T>, T> constructor;
@@ -130,7 +150,7 @@
              this.argument = argumentType;
              this.constructor = ruleFactory;
              this.callback = changeCallback;
-@@ -302,7 +318,7 @@
+@@ -302,7 +326,7 @@
          }
  
          public T createRule() {
@@ -139,7 +159,7 @@
          }
  
          public void callVisitor(GameRules.GameRuleTypeVisitor consumer, GameRules.Key<T> key) {
-@@ -322,21 +338,21 @@
+@@ -322,21 +346,21 @@
              this.type = type;
          }
  
@@ -169,7 +189,7 @@
  
          public abstract String serialize();
  
-@@ -350,7 +366,7 @@
+@@ -350,7 +374,7 @@
  
          protected abstract T copy();
  
@@ -178,7 +198,7 @@
      }
  
      public interface GameRuleTypeVisitor {
-@@ -366,7 +382,7 @@
+@@ -366,7 +390,7 @@
  
          private boolean value;
  
@@ -187,7 +207,7 @@
              return new GameRules.Type<>(BoolArgumentType::bool, (gamerules_gameruledefinition) -> {
                  return new GameRules.BooleanValue(gamerules_gameruledefinition, initialValue);
              }, changeCallback, GameRules.GameRuleTypeVisitor::visitBoolean, FeatureFlagSet.of());
-@@ -383,17 +399,20 @@
+@@ -383,17 +407,20 @@
          }
  
          @Override
@@ -213,7 +233,7 @@
          }
  
          @Override
-@@ -402,7 +421,7 @@
+@@ -402,7 +429,7 @@
          }
  
          @Override
@@ -222,7 +242,7 @@
              this.value = Boolean.parseBoolean(value);
          }
  
-@@ -421,9 +440,9 @@
+@@ -421,9 +448,9 @@
              return new GameRules.BooleanValue(this.type, this.value);
          }
  
@@ -235,7 +255,7 @@
          }
      }
  
-@@ -431,13 +450,13 @@
+@@ -431,13 +458,13 @@
  
          private int value;
  
@@ -251,7 +271,7 @@
              return new GameRules.Type<>(() -> {
                  return IntegerArgumentType.integer(min, max);
              }, (gamerules_gameruledefinition) -> {
-@@ -456,17 +475,20 @@
+@@ -456,17 +483,20 @@
          }
  
          @Override
@@ -277,7 +297,7 @@
          }
  
          @Override
-@@ -475,7 +497,7 @@
+@@ -475,7 +505,7 @@
          }
  
          @Override
@@ -286,7 +306,7 @@
              this.value = IntegerValue.safeParse(value);
          }
  
-@@ -517,9 +539,9 @@
+@@ -517,9 +547,9 @@
              return new GameRules.IntegerValue(this.type, this.value);
          }