Push forward

This commit is contained in:
2026-07-14 13:29:52 +08:00
parent 969cd5c5f8
commit dd3efffa76
246 changed files with 69 additions and 69 deletions
@@ -0,0 +1,42 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 20:49:06 +0800
Subject: [PATCH] Config system framework
diff --git a/net/minecraft/server/Main.java b/net/minecraft/server/Main.java
index a4d608d64b7d3477c9144d93547fd3b4f39a1b02..8cb1cfefa0deb78c1773ba9913138f31ac1e5c92 100644
--- a/net/minecraft/server/Main.java
+++ b/net/minecraft/server/Main.java
@@ -107,6 +107,7 @@ public class Main {
JvmProfiler.INSTANCE.start(Environment.SERVER);
}
+ io.nanachiyo0721.shiroha.config.ConfigManager.initConfigs(); // Shiroha - Config system framework - pre load config file
io.papermc.paper.plugin.PluginInitializerManager.load(options); // Paper
Bootstrap.bootStrap();
Bootstrap.validate();
diff --git a/net/minecraft/server/MinecraftServer.java b/net/minecraft/server/MinecraftServer.java
index c6a4d52f76e10fcc57b2c49b07fbc2ef9bb90822..e305fd5850d333eb1a30572076b6475e4428f7a7 100644
--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -1169,6 +1169,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
ca.spottedleaf.moonrise.common.util.MoonriseCommon.haltExecutors();
}
// Paper end - rewrite chunk system
+ io.nanachiyo0721.shiroha.config.ConfigManager.saveConfigs(false); // Shiroha - Config system framework - save config file
// Paper start - Improved watchdog support - move final shutdown items here
Util.shutdownExecutors();
this.onServerExit();
diff --git a/net/minecraft/server/dedicated/DedicatedServer.java b/net/minecraft/server/dedicated/DedicatedServer.java
index cd5551c0221ad2a7b5c7d452d8d91ffc9711c3ee..17244a82d7591004a43c013748f3db0507e73d7e 100644
--- a/net/minecraft/server/dedicated/DedicatedServer.java
+++ b/net/minecraft/server/dedicated/DedicatedServer.java
@@ -238,6 +238,7 @@ public class DedicatedServer extends MinecraftServer implements ServerInterface
this.paperConfigurations.initializeGlobalConfiguration(this.registryAccess());
this.paperConfigurations.initializeWorldDefaultsConfiguration(this.registryAccess());
// Paper end - initialize global and world-defaults configuration
+ io.nanachiyo0721.shiroha.config.ConfigManager.loadConfigFiles(); // Shiroha - Config system framework - load config file
this.server.spark.enableEarlyIfRequested(); // Paper - spark
// Paper start - fix converting txt to json file; convert old users earlier after PlayerList creation but before file load/save
if (this.convertOldUsers()) {
@@ -0,0 +1,388 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:50:30 +0800
Subject: [PATCH] Configurable region format framework
diff --git a/ca/spottedleaf/moonrise/patches/chunk_system/io/ChunkSystemRegionFileStorage.java b/ca/spottedleaf/moonrise/patches/chunk_system/io/ChunkSystemRegionFileStorage.java
index a814512fcfb85312474ae2c2c21443843bf57831..5734af81b1f88fde952f498059c791165a9d677f 100644
--- a/ca/spottedleaf/moonrise/patches/chunk_system/io/ChunkSystemRegionFileStorage.java
+++ b/ca/spottedleaf/moonrise/patches/chunk_system/io/ChunkSystemRegionFileStorage.java
@@ -8,9 +8,9 @@ public interface ChunkSystemRegionFileStorage {
public boolean moonrise$doesRegionFileNotExistNoIO(final int chunkX, final int chunkZ);
- public RegionFile moonrise$getRegionFileIfLoaded(final int chunkX, final int chunkZ);
+ public io.nanachiyo0721.shiroha.data.RegionFile moonrise$getRegionFileIfLoaded(final int chunkX, final int chunkZ); // Shiroha - Configurable region file format
- public RegionFile moonrise$getRegionFileIfExists(final int chunkX, final int chunkZ) throws IOException;
+ public io.nanachiyo0721.shiroha.data.RegionFile moonrise$getRegionFileIfExists(final int chunkX, final int chunkZ) throws IOException; // Shiroha - Configurable region file format
public MoonriseRegionFileIO.RegionDataController.WriteData moonrise$startWrite(
final int chunkX, final int chunkZ, final CompoundTag compound
diff --git a/ca/spottedleaf/moonrise/patches/chunk_system/io/MoonriseRegionFileIO.java b/ca/spottedleaf/moonrise/patches/chunk_system/io/MoonriseRegionFileIO.java
index 3bb9b58ee97464687e348e23b99159226415c267..b6d4d9fac961aa4672ef2f4a19e2ae18986bdd29 100644
--- a/ca/spottedleaf/moonrise/patches/chunk_system/io/MoonriseRegionFileIO.java
+++ b/ca/spottedleaf/moonrise/patches/chunk_system/io/MoonriseRegionFileIO.java
@@ -1273,7 +1273,7 @@ public final class MoonriseRegionFileIO {
this.regionDataController.finishWrite(this.chunkX, this.chunkZ, writeData);
// Paper start - flush regionfiles on save
if (this.world.paperConfig().chunks.flushRegionsOnSave) {
- final RegionFile regionFile = this.regionDataController.getCache().moonrise$getRegionFileIfLoaded(this.chunkX, this.chunkZ);
+ final io.nanachiyo0721.shiroha.data.RegionFile regionFile = this.regionDataController.getCache().moonrise$getRegionFileIfLoaded(this.chunkX, this.chunkZ); // Shiroha - Configurable region file format
if (regionFile != null) {
regionFile.flush();
} // else: evicted from cache, which should have called flush
@@ -1489,7 +1489,7 @@ public final class MoonriseRegionFileIO {
public static interface IORunnable {
- public void run(final RegionFile regionFile) throws IOException;
+ public void run(final io.nanachiyo0721.shiroha.data.RegionFile regionFile) throws IOException; // Shiroha - Configurable region file format
}
}
diff --git a/ca/spottedleaf/moonrise/patches/chunk_system/storage/ChunkSystemChunkBuffer.java b/ca/spottedleaf/moonrise/patches/chunk_system/storage/ChunkSystemChunkBuffer.java
index 51c126735ace8fdde89ad97b5cab62f244212db0..084b64dbaa2807fa29e4ae787144fce262a3b835 100644
--- a/ca/spottedleaf/moonrise/patches/chunk_system/storage/ChunkSystemChunkBuffer.java
+++ b/ca/spottedleaf/moonrise/patches/chunk_system/storage/ChunkSystemChunkBuffer.java
@@ -8,5 +8,5 @@ public interface ChunkSystemChunkBuffer {
public void moonrise$setWriteOnClose(final boolean value);
- public void moonrise$write(final RegionFile regionFile) throws IOException;
+ public void moonrise$write(final io.nanachiyo0721.shiroha.data.RegionFile regionFile) throws IOException; // Shiroha - Configurable region file format
}
diff --git a/net/minecraft/server/MinecraftServer.java b/net/minecraft/server/MinecraftServer.java
index e305fd5850d333eb1a30572076b6475e4428f7a7..78e9cf21fb5487e5eeec04e589c2a84c1e6b06af 100644
--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -986,10 +986,10 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
if (flush) {
for (ServerLevel level : this.getAllLevels()) {
String storageName = level.getChunkSource().chunkMap.getStorageName();
- LOGGER.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", LEGACY_WORLD_NAMES_FOR_REALMS_LOG.getOrDefault(storageName, storageName));
+ LOGGER.info("ThreadedChunkStorage ({}): All chunks are saved", LEGACY_WORLD_NAMES_FOR_REALMS_LOG.getOrDefault(storageName, storageName)); // Shiroha - Configurable region format
}
- LOGGER.info("ThreadedAnvilChunkStorage: All dimensions are saved");
+ LOGGER.info("ThreadedChunkStorage: All dimensions are saved"); // Shiroha - configurable region format
}
return result;
diff --git a/net/minecraft/util/worldupdate/FileToUpgrade.java b/net/minecraft/util/worldupdate/FileToUpgrade.java
index a7f2cfa9277c898038f6b9e0a3401db51012b64c..d6151f308e2e5864b6525409761aa6d9af5093f1 100644
--- a/net/minecraft/util/worldupdate/FileToUpgrade.java
+++ b/net/minecraft/util/worldupdate/FileToUpgrade.java
@@ -4,5 +4,5 @@ import java.util.List;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.storage.RegionFile;
-public record FileToUpgrade(RegionFile file, List<ChunkPos> chunksToUpgrade) {
+public record FileToUpgrade(io.nanachiyo0721.shiroha.data.RegionFile file, List<ChunkPos> chunksToUpgrade) { // Shiroha - Configurable region file format
}
diff --git a/net/minecraft/util/worldupdate/RegionStorageUpgrader.java b/net/minecraft/util/worldupdate/RegionStorageUpgrader.java
index b228cd6c54e8c8998923ab332882d99092769c67..13ec3d38ffb6e0e87db621c9607c9dc3c6a7b31b 100644
--- a/net/minecraft/util/worldupdate/RegionStorageUpgrader.java
+++ b/net/minecraft/util/worldupdate/RegionStorageUpgrader.java
@@ -36,7 +36,7 @@ import org.slf4j.Logger;
public class RegionStorageUpgrader {
private static final Logger LOGGER = LogUtils.getLogger();
private static final String NEW_DIRECTORY_PREFIX = "new_";
- private static final Pattern REGEX = Pattern.compile("^r\\.(-?[0-9]+)\\.(-?[0-9]+)\\.mca$");
+ private static final Pattern REGEX = Pattern.compile("^r\\.(-?[0-9]+)\\.(-?[0-9]+)\\." + io.nanachiyo0721.shiroha.config.modules.function.RegionFormatConfig.regionFormat.getArgument() + "$"); // Shiroha - Configurable region file format
private final DataFixer dataFixer;
private final UpgradeProgress upgradeProgress;
private final String type;
@@ -176,7 +176,8 @@ public class RegionStorageUpgrader {
int zOffset = Integer.parseInt(regex.group(2)) << 5;
List<ChunkPos> chunkPositions = Lists.newArrayList();
- try (RegionFile regionSource = new RegionFile(info, regionFile.toPath(), regionFolder, true)) {
+ var regionFileInfo = new io.nanachiyo0721.shiroha.utils.RegionCreatorInfo(info, regionFile.toPath(), regionFolder, true); // Shiroha - Configurable region file format
+ try (io.nanachiyo0721.shiroha.data.RegionFile regionSource = io.nanachiyo0721.shiroha.config.modules.function.RegionFormatConfig.regionFormat.getCreator().newFile(regionFileInfo)) { // Shiroha - Configurable region file format
for (int x = 0; x < 32; x++) {
for (int z = 0; z < 32; z++) {
ChunkPos pos = new ChunkPos(x + xOffset, z + zOffset);
@@ -253,7 +254,7 @@ public class RegionStorageUpgrader {
return storage.upgradeChunkTag(chunkTag, this.defaultVersion, this.dataFixContextTag, targetVersion);
}
- private void onFileFinished(final RegionFile regionFile) {
+ private void onFileFinished(final io.nanachiyo0721.shiroha.data.RegionFile regionFile) { // Shiroha - Configurable region file format
if (this.recreateRegionFiles) {
if (this.previousWriteFuture != null) {
this.previousWriteFuture.join();
diff --git a/net/minecraft/world/level/chunk/storage/RegionFile.java b/net/minecraft/world/level/chunk/storage/RegionFile.java
index 3de7fd2b084c38e72d7a6bc416880a881f514ad3..476aa2af20caeb8da293bd9e6c7467e384a2cf12 100644
--- a/net/minecraft/world/level/chunk/storage/RegionFile.java
+++ b/net/minecraft/world/level/chunk/storage/RegionFile.java
@@ -22,7 +22,7 @@ import net.minecraft.world.level.ChunkPos;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
-public class RegionFile implements AutoCloseable, ca.spottedleaf.moonrise.patches.chunk_system.storage.ChunkSystemRegionFile { // Paper - rewrite chunk system
+public class RegionFile implements AutoCloseable, ca.spottedleaf.moonrise.patches.chunk_system.storage.ChunkSystemRegionFile , io.nanachiyo0721.shiroha.data.RegionFile{ // Paper - rewrite chunk system // Shiroha - Configurable region file format
private static final Logger LOGGER = LogUtils.getLogger();
public static final int MAX_CHUNK_SIZE = 500 * 1024 * 1024; // Paper - don't write garbage data to disk if writing serialization fails
private static final int SECTOR_BYTES = 4096;
@@ -130,7 +130,7 @@ public class RegionFile implements AutoCloseable, ca.spottedleaf.moonrise.patche
return this.recalculateCount.get();
}
- boolean recalculateHeader() throws IOException {
+ public boolean recalculateHeader() throws IOException { // Shiroha - Configurable region file format
if (!this.canRecalcHeader) {
return false;
}
@@ -789,7 +789,7 @@ public class RegionFile implements AutoCloseable, ca.spottedleaf.moonrise.patche
}
}
- protected synchronized void write(final ChunkPos pos, final ByteBuffer data) throws IOException {
+ public synchronized void write(final ChunkPos pos, final ByteBuffer data) throws IOException { // Shiroha - Configurable region file format
int offsetIndex = getOffsetIndex(pos);
int offset = this.offsets.get(offsetIndex);
int sectorNumber = getSectorNumber(offset);
@@ -907,7 +907,7 @@ public class RegionFile implements AutoCloseable, ca.spottedleaf.moonrise.patche
}
@Override
- public final void moonrise$write(final RegionFile regionFile) throws IOException {
+ public final void moonrise$write(final io.nanachiyo0721.shiroha.data.RegionFile regionFile) throws IOException { // Shiroha - Configurable region file format
regionFile.write(this.pos, ByteBuffer.wrap(this.buf, 0, this.count));
}
// Paper end - rewrite chunk system
@@ -973,11 +973,11 @@ public class RegionFile implements AutoCloseable, ca.spottedleaf.moonrise.patche
return (x & 31) + (z & 31) * 32;
}
- synchronized boolean isOversized(int x, int z) {
+ public synchronized boolean isOversized(int x, int z) { // Shiroha - Configurable region file format
return this.oversized[getChunkIndex(x, z)] == 1;
}
- synchronized void setOversized(int x, int z, boolean oversized) throws IOException {
+ public synchronized void setOversized(int x, int z, boolean oversized) throws IOException { // Shiroha - Configurable region file format
final int offset = getChunkIndex(x, z);
boolean previous = this.oversized[offset] == 1;
this.oversized[offset] = (byte) (oversized ? 1 : 0);
@@ -1016,7 +1016,7 @@ public class RegionFile implements AutoCloseable, ca.spottedleaf.moonrise.patche
return this.path.getParent().resolve(this.path.getFileName().toString().replaceAll("\\.mca$", "") + "_oversized_" + x + "_" + z + ".nbt");
}
- synchronized net.minecraft.nbt.CompoundTag getOversizedData(int x, int z) throws IOException {
+ public synchronized net.minecraft.nbt.CompoundTag getOversizedData(int x, int z) throws IOException { // Shiroha - Configurable region file format
Path file = getOversizedFile(x, z);
try (DataInputStream out = new DataInputStream(new java.io.BufferedInputStream(new java.util.zip.InflaterInputStream(Files.newInputStream(file))))) {
return net.minecraft.nbt.NbtIo.read((java.io.DataInput) out);
diff --git a/net/minecraft/world/level/chunk/storage/RegionFileStorage.java b/net/minecraft/world/level/chunk/storage/RegionFileStorage.java
index 63b40c420030d935bb81a219fb33defe0946e21f..cc9913016c6d985644f8af47986db77006d31e77 100644
--- a/net/minecraft/world/level/chunk/storage/RegionFileStorage.java
+++ b/net/minecraft/world/level/chunk/storage/RegionFileStorage.java
@@ -19,7 +19,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
private static final org.slf4j.Logger LOGGER = com.mojang.logging.LogUtils.getLogger(); // Paper
public static final String ANVIL_EXTENSION = ".mca";
private static final int MAX_CACHE_SIZE = 256;
- private final Long2ObjectLinkedOpenHashMap<RegionFile> regionCache = new Long2ObjectLinkedOpenHashMap<>();
+ private final Long2ObjectLinkedOpenHashMap<io.nanachiyo0721.shiroha.data.RegionFile> regionCache = new Long2ObjectLinkedOpenHashMap<>(); // Shiroha - Configurable region file format
private final RegionStorageInfo info;
private final Path folder;
private final boolean sync;
@@ -30,7 +30,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
@Nullable
public static ChunkPos getRegionFileCoordinates(Path file) {
String fileName = file.getFileName().toString();
- if (!fileName.startsWith("r.") || !fileName.endsWith(".mca")) {
+ if (!fileName.startsWith("r.") || !fileName.endsWith(getExtensionName())) { // Shiroha - Configurable region file format
return null;
}
@@ -55,8 +55,32 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
private static final int MAX_NON_EXISTING_CACHE = 1024 * 4;
private final it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet nonExistingRegionFiles = new it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet();
private static String getRegionFileName(final int chunkX, final int chunkZ) {
- return "r." + (chunkX >> REGION_SHIFT) + "." + (chunkZ >> REGION_SHIFT) + ".mca";
+ return "r." + (chunkX >> REGION_SHIFT) + "." + (chunkZ >> REGION_SHIFT) + getExtensionName(); // Shiroha - Configurable region file format
}
+ // Shiroha start - Configurable region file format
+ public static io.nanachiyo0721.shiroha.data.RegionFile createNew(RegionStorageInfo info, Path filePath, Path folder, boolean sync) throws IOException{
+ final io.nanachiyo0721.shiroha.enums.EnumRegionFormat regionFormat = io.nanachiyo0721.shiroha.config.modules.function.RegionFormatConfig.regionFormat;
+ final String fullFileName = filePath.getFileName().toString();
+ final String[] fullNameSplit = fullFileName.split("\\.");
+ final String extensionName = fullNameSplit[fullNameSplit.length - 1];
+
+ if (!regionFormat.getArgument().equalsIgnoreCase(extensionName)) {
+ // raise a delayed crash
+ io.papermc.paper.threadedregions.RegionizedServer.getInstance().addTask(() -> {
+ throw new RuntimeException("Invalid region file format: " + extensionName + " expected " + regionFormat.getArgument());
+ });
+
+
+ throw new IOException("Invalid region file format: " + extensionName + " expected " + regionFormat.getArgument());
+ }
+
+ return regionFormat.getCreator().newFile(new io.nanachiyo0721.shiroha.utils.RegionCreatorInfo(info, filePath, folder, sync));
+ }
+
+ public static String getExtensionName() {
+ return "." + io.nanachiyo0721.shiroha.config.modules.function.RegionFormatConfig.regionFormat.getArgument();
+ }
+ // Shiroha end
private boolean doesRegionFilePossiblyExist(final long position) {
synchronized (this.nonExistingRegionFiles) {
@@ -90,15 +114,15 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
}
@Override
- public synchronized final RegionFile moonrise$getRegionFileIfLoaded(final int chunkX, final int chunkZ) {
+ public synchronized final io.nanachiyo0721.shiroha.data.RegionFile moonrise$getRegionFileIfLoaded(final int chunkX, final int chunkZ) { // Shiroha - Configurable region file format
return this.regionCache.getAndMoveToFirst(ChunkPos.pack(chunkX >> REGION_SHIFT, chunkZ >> REGION_SHIFT));
}
@Override
- public synchronized final RegionFile moonrise$getRegionFileIfExists(final int chunkX, final int chunkZ) throws IOException {
+ public synchronized final io.nanachiyo0721.shiroha.data.RegionFile moonrise$getRegionFileIfExists(final int chunkX, final int chunkZ) throws IOException { // Shiroha - Configurable region file format
final long key = ChunkPos.pack(chunkX >> REGION_SHIFT, chunkZ >> REGION_SHIFT);
- RegionFile ret = this.regionCache.getAndMoveToFirst(key);
+ io.nanachiyo0721.shiroha.data.RegionFile ret = this.regionCache.getAndMoveToFirst(key); // Shiroha - Configurable region file format
if (ret != null) {
return ret;
}
@@ -124,7 +148,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
FileUtil.createDirectoriesSafe(this.folder);
- ret = new RegionFile(this.info, regionPath, this.folder, this.sync);
+ ret = this.createNew(this.info, regionPath, this.folder, this.sync); // Shiroha - Configurable region file format
this.regionCache.putAndMoveToFirst(key, ret);
@@ -143,7 +167,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
}
final ChunkPos pos = new ChunkPos(chunkX, chunkZ);
- final RegionFile regionFile = this.getRegionFile(pos);
+ final io.nanachiyo0721.shiroha.data.RegionFile regionFile = this.getRegionFile(pos); // Shiroha - Configurable region file format
// note: not required to keep regionfile loaded after this call, as the write param takes a regionfile as input
// (and, the regionfile parameter is unused for writing until the write call)
@@ -177,7 +201,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
) throws IOException {
final ChunkPos pos = new ChunkPos(chunkX, chunkZ);
if (writeData.result() == ca.spottedleaf.moonrise.patches.chunk_system.io.MoonriseRegionFileIO.RegionDataController.WriteData.WriteResult.DELETE) {
- final RegionFile regionFile = this.moonrise$getRegionFileIfExists(chunkX, chunkZ);
+ final io.nanachiyo0721.shiroha.data.RegionFile regionFile = this.moonrise$getRegionFileIfExists(chunkX, chunkZ); // Shiroha - Configurable region file format
if (regionFile != null) {
regionFile.clear(pos);
} // else: didn't exist
@@ -192,7 +216,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
public final ca.spottedleaf.moonrise.patches.chunk_system.io.MoonriseRegionFileIO.RegionDataController.ReadData moonrise$readData(
final int chunkX, final int chunkZ
) throws IOException {
- final RegionFile regionFile = this.moonrise$getRegionFileIfExists(chunkX, chunkZ);
+ final io.nanachiyo0721.shiroha.data.RegionFile regionFile = this.moonrise$getRegionFileIfExists(chunkX, chunkZ); // Shiroha - Configurable region file format
final DataInputStream input = regionFile == null ? null : regionFile.getChunkDataInputStream(new ChunkPos(chunkX, chunkZ));
@@ -237,7 +261,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
final ChunkPos pos = new ChunkPos(chunkX, chunkZ);
final ChunkPos headerChunkPos = SerializableChunkData.getChunkCoordinate(ret);
- final RegionFile regionFile = this.getRegionFile(pos);
+ final io.nanachiyo0721.shiroha.data.RegionFile regionFile = this.getRegionFile(pos); // Shiroha - Configurable region file format
if (regionFile.getRecalculateCount() != readData.recalculateCount()) {
return null;
@@ -261,7 +285,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
}
// Paper end - rewrite chunk system
// Paper start - rewrite chunk system
- public RegionFile getRegionFile(ChunkPos pos) throws IOException {
+ public io.nanachiyo0721.shiroha.data.RegionFile getRegionFile(ChunkPos pos) throws IOException { // Shiroha - Configurable region file format
return this.getRegionFile(pos, false);
}
// Paper end - rewrite chunk system
@@ -273,7 +297,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
this.isChunkData = info.dfuType()[0] == net.minecraft.util.datafix.DataFixTypes.CHUNK; // Paper - recalculate region file headers
}
- @org.jetbrains.annotations.Contract("_, false -> !null") private @Nullable RegionFile getRegionFile(final ChunkPos pos, boolean existingOnly) throws IOException { // CraftBukkit
+ @org.jetbrains.annotations.Contract("_, false -> !null") private io.nanachiyo0721.shiroha.data.RegionFile getRegionFile(final ChunkPos pos, boolean existingOnly) throws IOException { // CraftBukkit // Shiroha - Configurable region file format
// Paper start - rewrite chunk system
if (existingOnly) {
return this.moonrise$getRegionFileIfExists(pos.x(), pos.z());
@@ -281,7 +305,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
synchronized (this) {
final long key = ChunkPos.pack(pos.x() >> REGION_SHIFT, pos.z() >> REGION_SHIFT);
- RegionFile ret = this.regionCache.getAndMoveToFirst(key);
+ io.nanachiyo0721.shiroha.data.RegionFile ret = this.regionCache.getAndMoveToFirst(key); // Shiroha - Configurable region file format
if (ret != null) {
return ret;
}
@@ -298,7 +322,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
FileUtil.createDirectoriesSafe(this.folder);
- ret = new RegionFile(this.info, regionPath, this.folder, this.sync);
+ ret = this.createNew(this.info, regionPath, this.folder, this.sync); // Shiroha - Configurable region file format
this.regionCache.putAndMoveToFirst(key, ret);
@@ -312,7 +336,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
LOGGER.error("{} ({} - {},{}) Go clean it up to remove this message. /minecraft:tp {} 128 {} - DO NOT REPORT THIS TO PAPER - You may ask for help on Discord, but do not file an issue. These error messages can not be removed.", msg, file.toString().replaceAll(".+[\\\\/]", ""), x, z, x << 4, z << 4);
}
- private static CompoundTag readOversizedChunk(RegionFile regionfile, ChunkPos chunkCoordinate) throws IOException {
+ private static CompoundTag readOversizedChunk(io.nanachiyo0721.shiroha.data.RegionFile regionfile, ChunkPos chunkCoordinate) throws IOException { // Shiroha - Configurable region file format
synchronized (regionfile) {
try (DataInputStream datainputstream = regionfile.getChunkDataInputStream(chunkCoordinate)) {
CompoundTag oversizedData = regionfile.getOversizedData(chunkCoordinate.x(), chunkCoordinate.z());
@@ -346,7 +370,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
public @Nullable CompoundTag read(final ChunkPos pos) throws IOException {
// CraftBukkit start - SPIGOT-5680: There's no good reason to preemptively create files on read, save that for writing
- RegionFile region = this.getRegionFile(pos, true);
+ io.nanachiyo0721.shiroha.data.RegionFile region = this.getRegionFile(pos, true); // Shiroha - Configurable region file format
if (region == null) {
return null;
}
@@ -383,7 +407,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
public void scanChunk(final ChunkPos pos, final StreamTagVisitor scanner) throws IOException {
// CraftBukkit start - SPIGOT-5680: There's no good reason to preemptively create files on read, save that for writing
- RegionFile region = this.getRegionFile(pos, true);
+ io.nanachiyo0721.shiroha.data.RegionFile region = this.getRegionFile(pos, true); // Shiroha - Configurable region file format
if (region == null) {
return;
}
@@ -398,7 +422,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
public void write(final ChunkPos pos, final @Nullable CompoundTag value) throws IOException {
if (!SharedConstants.DEBUG_DONT_SAVE_WORLD) {
- RegionFile region = this.getRegionFile(pos, value == null); // CraftBukkit // Paper - rewrite chunk system
+ io.nanachiyo0721.shiroha.data.RegionFile region = this.getRegionFile(pos, value == null); // CraftBukkit // Paper - rewrite chunk system // Shiroha - Configurable region file format
// Paper start - rewrite chunk system
if (region == null) {
// if the RegionFile doesn't exist, no point in deleting from it
@@ -430,7 +454,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
// Paper start - rewrite chunk system
synchronized (this) {
final ExceptionCollector<IOException> exceptionCollector = new ExceptionCollector<>();
- for (final RegionFile regionFile : this.regionCache.values()) {
+ for (final io.nanachiyo0721.shiroha.data.RegionFile regionFile : this.regionCache.values()) { // Shiroha - Configurable region file format
try {
regionFile.close();
} catch (final IOException ex) {
@@ -446,7 +470,7 @@ public class RegionFileStorage implements AutoCloseable, ca.spottedleaf.moonrise
// Paper start - rewrite chunk system
synchronized (this) {
final ExceptionCollector<IOException> exceptionCollector = new ExceptionCollector<>();
- for (final RegionFile regionFile : this.regionCache.values()) {
+ for (final io.nanachiyo0721.shiroha.data.RegionFile regionFile : this.regionCache.values()) { // Shiroha - Configurable region file format
try {
regionFile.flush();
} catch (final IOException ex) {
@@ -0,0 +1,54 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Wed, 8 Jul 2026 20:55:35 +0800
Subject: [PATCH] Correct player respawn place
diff --git a/net/minecraft/server/level/ServerPlayer.java b/net/minecraft/server/level/ServerPlayer.java
index fbe0ef19bfabfc42d9e0e08e17b08159321b3804..4c7aa11f5640e959271afd6bbae9b0ba3d998abc 100644
--- a/net/minecraft/server/level/ServerPlayer.java
+++ b/net/minecraft/server/level/ServerPlayer.java
@@ -511,8 +511,10 @@ public class ServerPlayer extends Player implements ca.spottedleaf.moonrise.patc
double amountX = selectMaxX - selectMinX;
double amountZ = selectMaxZ - selectMinZ;
- int selectX = amountX < 1.0 ? Mth.floor(worldBorder.getCenterX()) : (int)Mth.floor((amountX + 1.0) * random.nextDouble() + selectMinX);
- int selectZ = amountZ < 1.0 ? Mth.floor(worldBorder.getCenterZ()) : (int)Mth.floor((amountZ + 1.0) * random.nextDouble() + selectMinZ);
+ // Shiroha start - Correct player respawn place
+ int selectX = amountX < 0.0 ? Mth.floor(worldBorder.getCenterX()) : (int)Mth.floor(amountX * random.nextDouble() + selectMinX);
+ int selectZ = amountZ < 0.0 ? Mth.floor(worldBorder.getCenterZ()) : (int)Mth.floor(amountZ * random.nextDouble() + selectMinZ);
+ // Shiroha end - Correct player respawn place
return new BlockPos(selectX, 0, selectZ);
}
@@ -523,10 +525,20 @@ public class ServerPlayer extends Player implements ca.spottedleaf.moonrise.patc
}
private static BlockPos findSpawnAround(ServerLevel world, BlockPos selected) {
+ // Shiroha start - Correct player respawn place
+ BlockPos inChunk = PlayerSpawnFinder.getLevelRespawnPos(world, selected.getX(), selected.getZ());
+ if (inChunk != null) {
+ AABB checkVolume = PlayerSpawnFinder.PLAYER_DIMENSIONS.makeBoundingBox((double)inChunk.getX() + 0.5, (double)inChunk.getY(), (double)inChunk.getZ() + 0.5);
+
+ if (world.noCollision(null, checkVolume, true)) {
+ return inChunk;
+ }
+ }
+ // Shiroha end - Correct player respawn place
// try hard to find, so that we don't attempt another chunk load
for (int dz = -SPAWN_RADIUS_SELECTION_SEARCH; dz <= SPAWN_RADIUS_SELECTION_SEARCH; ++dz) {
for (int dx = -SPAWN_RADIUS_SELECTION_SEARCH; dx <= SPAWN_RADIUS_SELECTION_SEARCH; ++dx) {
- BlockPos inChunk = PlayerSpawnFinder.getLevelRespawnPos(world, selected.getX() + dx, selected.getZ() + dz);
+ inChunk = PlayerSpawnFinder.getLevelRespawnPos(world, selected.getX() + dx, selected.getZ() + dz); // Shiroha - Correct player respawn place
if (inChunk == null) {
continue;
}
@@ -2018,7 +2030,7 @@ public class ServerPlayer extends Player implements ca.spottedleaf.moonrise.patc
}
if (newLevel.dimension() == lastDimension) {
- this.connection.internalTeleport(PositionMoveRotation.of(transition), transition.relatives()); // CraftBukkit
+ this.connection.internalTeleport(PositionMoveRotation.of(transition), transition.relatives()); // CraftBukkit // Shiroha - Correct player respawn place
this.connection.resetPosition();
transition.postTeleportTransition().onTransition(this);
return this;
@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 20:57:02 +0800
Subject: [PATCH] Correct CAS get in RegionizedTaskQueue
diff --git a/io/papermc/paper/threadedregions/RegionizedTaskQueue.java b/io/papermc/paper/threadedregions/RegionizedTaskQueue.java
index d1a045d47dcd12f246d95ecdfc202da357897cbf..8c44de1f7bb80809856fd26fa94d6b94aa9963e0 100644
--- a/io/papermc/paper/threadedregions/RegionizedTaskQueue.java
+++ b/io/papermc/paper/threadedregions/RegionizedTaskQueue.java
@@ -533,7 +533,7 @@ public final class RegionizedTaskQueue {
}
private ReferenceCountData getReferenceCounterVolatile() {
- return (ReferenceCountData)REFERENCE_COUNTER_HANDLE.get(this);
+ return (ReferenceCountData)REFERENCE_COUNTER_HANDLE.getVolatile(this); // Shiroha - Correct CAS get in RegionizedTaskQueue
}
private ReferenceCountData compareAndExchangeReferenceCounter(final ReferenceCountData expect, final ReferenceCountData update) {
@@ -0,0 +1,32 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 20:59:01 +0800
Subject: [PATCH] Correct thread unsafe random sources
diff --git a/net/minecraft/world/entity/npc/wanderingtrader/WanderingTraderSpawner.java b/net/minecraft/world/entity/npc/wanderingtrader/WanderingTraderSpawner.java
index 01b3cda3da79abd30860eb33491ac00f9e958767..445858e4d39bd417e1e85bcb9bc7c1a4bc9d5fb0 100644
--- a/net/minecraft/world/entity/npc/wanderingtrader/WanderingTraderSpawner.java
+++ b/net/minecraft/world/entity/npc/wanderingtrader/WanderingTraderSpawner.java
@@ -30,7 +30,7 @@ public class WanderingTraderSpawner implements CustomSpawner {
private static final int SPAWN_CHANCE_INCREASE = 25;
private static final int SPAWN_ONE_IN_X_CHANCE = 10;
private static final int NUMBER_OF_SPAWN_ATTEMPTS = 10;
- private final RandomSource random = RandomSource.create();
+ private final RandomSource random = io.papermc.paper.threadedregions.util.ThreadLocalRandomSource.INSTANCE; // Shiroha - Correct thread unsafe random sources
private final SavedDataStorage savedDataStorage;
// Folia - moved to global data
diff --git a/net/minecraft/world/level/block/entity/EnchantingTableBlockEntity.java b/net/minecraft/world/level/block/entity/EnchantingTableBlockEntity.java
index 22b9f70f76ff8f592359e958fa439e9806a29fcc..45fcc35a3e8c4b80b53c96dc810bd51fb07e3dee 100644
--- a/net/minecraft/world/level/block/entity/EnchantingTableBlockEntity.java
+++ b/net/minecraft/world/level/block/entity/EnchantingTableBlockEntity.java
@@ -28,7 +28,7 @@ public class EnchantingTableBlockEntity extends BlockEntity implements Nameable
public float rot;
public float oRot;
public float tRot;
- private static final RandomSource RANDOM = RandomSource.create();
+ private static final RandomSource RANDOM = io.papermc.paper.threadedregions.util.ThreadLocalRandomSource.INSTANCE; // Shiroha - Correct thread unsafe random sources
private @Nullable Component name;
public EnchantingTableBlockEntity(final BlockPos worldPosition, final BlockState blockState) {
@@ -0,0 +1,59 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:01:20 +0800
Subject: [PATCH] Correct portal logic of some projectile entities (Should not
be ticking anymore after portal logics)
diff --git a/net/minecraft/world/entity/projectile/ShulkerBullet.java b/net/minecraft/world/entity/projectile/ShulkerBullet.java
index d5506bfc84912ec50cd5391225b9b5291435d3aa..994c069b0bcb8f0f1d4269d7a74d6fe714246c50 100644
--- a/net/minecraft/world/entity/projectile/ShulkerBullet.java
+++ b/net/minecraft/world/entity/projectile/ShulkerBullet.java
@@ -229,7 +229,7 @@ public class ShulkerBullet extends Projectile {
this.setPos(this.position().add(movement));
this.applyEffectsFromBlocks();
if (this.portalProcess != null && this.portalProcess.isInsidePortalThisTick()) {
- this.handlePortal();
+ if (this.handlePortal()) return; // Shiroha - Correct portal logic of some projectile entities (Should not be ticking anymore after portal logics)
}
if (hitResult != null && this.isAlive() && hitResult.getType() != HitResult.Type.MISS) {
diff --git a/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java b/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java
index 88c2f0f927bd8376522eb9aed184abd6f09230f6..e54267ecf448a1b7fd6c433afba2d7ee122e07f5 100644
--- a/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java
+++ b/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java
@@ -276,7 +276,7 @@ public abstract class AbstractArrow extends Projectile {
.clipIncludingBorder(
new ClipContext(originalPosition, originalPosition.add(movement), ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, this)
);
- this.stepMoveAndHit(blockHitResult);
+ if (this.stepMoveAndHit(blockHitResult)) return; // Shiroha - Correct portal logic of some projectile entities (Should not be ticking anymore after portal logics)
} else {
this.setPos(originalPosition.add(movement));
this.applyEffectsFromBlocks();
@@ -299,7 +299,7 @@ public abstract class AbstractArrow extends Projectile {
return 0.99F;
}
- private void stepMoveAndHit(final BlockHitResult blockHitResult) {
+ private boolean stepMoveAndHit(final BlockHitResult blockHitResult) { // Shiroha - Correct portal logic of some projectile entities
while (this.isAlive()) {
Vec3 initialPosition = this.position();
ArrayList<EntityHitResult> entitiesHit = new ArrayList<>(this.findHitEntities(initialPosition, blockHitResult.getLocation()));
@@ -309,7 +309,7 @@ public abstract class AbstractArrow extends Projectile {
this.setPos(nextLocation);
this.applyEffectsFromBlocks(initialPosition, nextLocation);
if (this.portalProcess != null && this.portalProcess.isInsidePortalThisTick()) {
- this.handlePortal();
+ if (this.handlePortal()) return true; // Shiroha - Correct portal logic of some projectile entities (Should not be ticking anymore after portal logics)
}
if (entitiesHit.isEmpty()) {
@@ -327,6 +327,7 @@ public abstract class AbstractArrow extends Projectile {
break;
}
}
+ return false; // Shiroha - Correct portal logic of some projectile entities
}
private ProjectileDeflection hitTargetsOrDeflectSelf(final Collection<EntityHitResult> entityHitResults) {
@@ -0,0 +1,20 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:02:54 +0800
Subject: [PATCH] Do not enable any debug subscriptions
Really this would really crash the server by accident when the operators used F3 + J or toggled the debug synchronizer
diff --git a/net/minecraft/server/level/ServerPlayer.java b/net/minecraft/server/level/ServerPlayer.java
index 4c7aa11f5640e959271afd6bbae9b0ba3d998abc..625c013e99f41a7d64e301100139f1bf4ee3e2e1 100644
--- a/net/minecraft/server/level/ServerPlayer.java
+++ b/net/minecraft/server/level/ServerPlayer.java
@@ -3504,7 +3504,7 @@ public class ServerPlayer extends Player implements ca.spottedleaf.moonrise.patc
}
public Set<DebugSubscription<?>> debugSubscriptions() {
- return !this.server.debugSubscribers().hasRequiredPermissions(this) ? Set.of() : this.requestedDebugSubscriptions;
+ return Set.of(); // Shiroha - Do not enable any debug subscriptions
}
public record RespawnConfig(LevelData.RespawnData respawnData, boolean forced) {
@@ -0,0 +1,32 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Fri, 17 Apr 2026 23:25:45 +0800
Subject: [PATCH] Do not load too far poi chunk in poi compete scan
Beeeeeeeeeeeeeeee
diff --git a/net/minecraft/world/entity/ai/behavior/PoiCompetitorScan.java b/net/minecraft/world/entity/ai/behavior/PoiCompetitorScan.java
index 53131c1b8d5562f9a1b45dfab4fdbdd37b655139..f4c171c06ac2a3d45c91365781d0789e4ee74fe8 100644
--- a/net/minecraft/world/entity/ai/behavior/PoiCompetitorScan.java
+++ b/net/minecraft/world/entity/ai/behavior/PoiCompetitorScan.java
@@ -24,8 +24,18 @@ public class PoiCompetitorScan {
return true;
}
// Folia end - region threading
- level.getPoiManager()
- .getType(pos.pos())
+ // Shiroha start - Do not load too far poi chunk in poi compete scan
+ var blockPosOfJobSite = pos.pos();
+ var sectionPosOfJobSite = net.minecraft.core.SectionPos.asLong(blockPosOfJobSite);
+ var poiManager = level.getPoiManager();
+ // we don't care if we should clear the memory of JOB_SITE
+ // as it will be automatically removed in SetWalkTargetFromBlockMemory
+ // so simply break down if it's not loaded
+ var poiChunk = io.nanachiyo0721.shiroha.config.modules.fixes.POIRangeFixes.doNotCompetePOIIfUnloaded ? poiManager.get(sectionPosOfJobSite) : poiManager.getOrLoad(sectionPosOfJobSite);
+ poiChunk.flatMap(poiSection -> poiSection.getType(blockPosOfJobSite))
+ // Shiroha end - Do not load too far poi chunk in poi compete scan
+ /*level.getPoiManager() // Shiroha - Do not load too far poi chunk in poi compete scan
+ .getType(pos.pos())*/ // Shiroha - Do not load too far poi chunk in poi compete scan
.ifPresent(
// Paper start - Improve performance of PoiCompetitorScan by unrolling stream
// The previous logic used Stream#reduce to simulate a form of single-iteration bubble sort
@@ -0,0 +1,67 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:32:08 +0800
Subject: [PATCH] Entity portal-teleport speed fix
diff --git a/net/minecraft/server/level/ServerLevel.java b/net/minecraft/server/level/ServerLevel.java
index 3db75ac3f7f111b94178cc29684f24dd55ac5847..39e511061d11039a1027320de624be07e34a2978 100644
--- a/net/minecraft/server/level/ServerLevel.java
+++ b/net/minecraft/server/level/ServerLevel.java
@@ -1491,7 +1491,35 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
foliaProfiler.startTimer(timerId);
try {
// Folia end - profiler
+ // Shiroha start - Entity portal-teleport speed fix
if (isActive) { // Paper - EAR 2
+ if (!(entity instanceof Player) && entity.teleportTickType == 2) { // Shiroha - after portal compensate tick
+ entity.tick();
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(entity)) {
+ // removed from region while ticking
+ return;
+ }
+ if (entity.handlePortal()) {
+ // portalled
+ return;
+ }
+ entity.tick();
+ entity.teleportTickType = 0;
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(entity)) {
+ return;
+ }
+ if (entity.handlePortal()) {
+ return;
+ }
+ } else if (!(entity instanceof Player) && entity.teleportTickType == 1) { // Shiroha - portal teleport only
+ entity.teleportTickType++;
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(entity)) {
+ return;
+ }
+ if (entity.handlePortal()) {
+ return;
+ }
+ } else {
entity.tick();
// Folia start - region threading
if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(entity)) {
@@ -1502,6 +1530,8 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
// portalled
return;
}
+ }
+ // Shiroha end - Entity portal-teleport speed fix
// Folia end - region threading
} else {entity.inactiveTick();} // Paper - EAR 2
profiler.pop();
diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java
index 2a8a7aeddffdfed31cd6e1162c0756986049fbab..a3f473cab6a37e65de233c7f77d9de7c967fcdd0 100644
--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -387,6 +387,7 @@ public abstract class Entity
public long activatedTick = Integer.MIN_VALUE;
public boolean isTemporarilyActive;
public long activatedImmunityTick = Integer.MIN_VALUE;
+ public int teleportTickType = 0; // Shiroha - Entity portal-teleport speed fix
public void inactiveTick() {
}
@@ -0,0 +1,289 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:12:31 +0800
Subject: [PATCH] Fix region threading with entity ai data access
diff --git a/net/minecraft/world/entity/Mob.java b/net/minecraft/world/entity/Mob.java
index 3b1c3e84ab24b6e3a0e4d129b3617b393b6d6651..c6ce88fb63e0d40ed011958a1afd36c645d965c8 100644
--- a/net/minecraft/world/entity/Mob.java
+++ b/net/minecraft/world/entity/Mob.java
@@ -299,6 +299,11 @@ public abstract class Mob extends LivingEntity implements Targeting, EquipmentUs
if (Objects.equals(currentTarget, target)) {
return false;
}
+ // Shiroha - Fix region threading with entity ai data access
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(target)) {
+ return false;
+ }
+ // Shiroha end
LivingEntity originalTarget = target;
target = asValidTarget(target);
if (reason != null) {
diff --git a/net/minecraft/world/entity/ai/Brain.java b/net/minecraft/world/entity/ai/Brain.java
index e097bc1268b4050e3948413c52dea69950858458..977a31f995799cf44fa59cc1db73571edbcf36ff 100644
--- a/net/minecraft/world/entity/ai/Brain.java
+++ b/net/minecraft/world/entity/ai/Brain.java
@@ -383,7 +383,7 @@ public class Brain<E extends LivingEntity> {
}
public void tick(final ServerLevel level, final E body) {
- this.forgetOutdatedMemories();
+ this.forgetOutdatedMemories(body); // Shiroha - Fix region threading with entity ai data access
this.tickSensors(level, body);
this.startEachNonRunningBehavior(level, body);
this.tickEachRunningBehavior(level, body);
@@ -395,8 +395,8 @@ public class Brain<E extends LivingEntity> {
}
}
- private void forgetOutdatedMemories() {
- this.memories.values().forEach(MemorySlot::tick);
+ private void forgetOutdatedMemories(E body) { // Shiroha - Fix region threading with entity ai data access
+ this.memories.values().forEach(slot -> slot.tick(body)); // Shiroha - Fix region threading with entity ai data access
}
public void stopAll(final ServerLevel level, final E body) {
diff --git a/net/minecraft/world/entity/ai/behavior/BehaviorUtils.java b/net/minecraft/world/entity/ai/behavior/BehaviorUtils.java
index f744ecd20dc70786311a7162b52aa4ceca0717db..c8373151e280764e3175a263d201c078cca6fac8 100644
--- a/net/minecraft/world/entity/ai/behavior/BehaviorUtils.java
+++ b/net/minecraft/world/entity/ai/behavior/BehaviorUtils.java
@@ -81,6 +81,11 @@ public class BehaviorUtils {
public static void setWalkAndLookTargetMemories(
final LivingEntity walker, final PositionTracker target, final float speedModifier, final int closeEnoughDistance
) {
+ // Shiroha - Fix region threading with entity ai data access
+ if (!target.checkThread(walker.level())) {
+ return;
+ }
+ // Shiroha end
WalkTarget walkTarget = new WalkTarget(target, speedModifier, closeEnoughDistance);
walker.getBrain().setMemory(MemoryModuleType.LOOK_TARGET, target);
walker.getBrain().setMemory(MemoryModuleType.WALK_TARGET, walkTarget);
diff --git a/net/minecraft/world/entity/ai/behavior/BlockPosTracker.java b/net/minecraft/world/entity/ai/behavior/BlockPosTracker.java
index 68251875edfa47ac34c64f99510998ad4bbb14b4..cb386eac7855d53c8c1df36305b6b0156cccd62d 100644
--- a/net/minecraft/world/entity/ai/behavior/BlockPosTracker.java
+++ b/net/minecraft/world/entity/ai/behavior/BlockPosTracker.java
@@ -37,4 +37,11 @@ public class BlockPosTracker implements PositionTracker {
public String toString() {
return "BlockPosTracker{blockPos=" + this.blockPos + ", centerPosition=" + this.centerPosition + "}";
}
+
+ // Shiroha start - Fix region threading with entity ai data access
+ @Override
+ public boolean checkThread(net.minecraft.world.level.Level currOwnedByLevel) {
+ return ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(currOwnedByLevel, this.blockPos);
+ }
+ // Shiroha end
}
diff --git a/net/minecraft/world/entity/ai/behavior/EntityTracker.java b/net/minecraft/world/entity/ai/behavior/EntityTracker.java
index 3ac52b025ac3e1a3f9135b8e593a385a847afe0f..61cdd99e21cf894cf73c1b90c1d4c45a94d222ff 100644
--- a/net/minecraft/world/entity/ai/behavior/EntityTracker.java
+++ b/net/minecraft/world/entity/ai/behavior/EntityTracker.java
@@ -55,4 +55,11 @@ public class EntityTracker implements PositionTracker {
public String toString() {
return "EntityTracker for " + this.entity;
}
+
+ // Shiroha start - Fix region threading with entity ai data access
+ @Override
+ public boolean checkThread(net.minecraft.world.level.Level currOwnedByLevel) {
+ return ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(this.entity);
+ }
+ // Shiroha end
}
diff --git a/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java b/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java
index b40da004b5281a041ee896ae176bfb9c4660f353..1e2a8c2beaec24f04f70baee9eb6a678ce325efa 100644
--- a/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java
+++ b/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java
@@ -117,7 +117,9 @@ public class MoveToTargetSink extends Behavior<Mob> {
private boolean tryComputePath(final Mob body, final WalkTarget walkTarget, final long timestamp) {
BlockPos targetPos = walkTarget.getTarget().currentBlockPosition();
+ if (ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(body.level(), targetPos)) // Shiroha - Fix region threading with entity ai data access
this.path = body.getNavigation().createPath(targetPos, 0);
+ else this.path = null; // Shiroha - Fix region threading with entity ai data access
this.speedModifier = walkTarget.getSpeedModifier();
Brain<?> brain = body.getBrain();
if (this.reachedTarget(body, walkTarget)) {
diff --git a/net/minecraft/world/entity/ai/behavior/PositionTracker.java b/net/minecraft/world/entity/ai/behavior/PositionTracker.java
index ce6cf5ecfb190428e3ef9b7dd39c98e3d27a7b9d..2194a77e1746c061e294840ba9a3b8d8604ff0b9 100644
--- a/net/minecraft/world/entity/ai/behavior/PositionTracker.java
+++ b/net/minecraft/world/entity/ai/behavior/PositionTracker.java
@@ -10,4 +10,6 @@ public interface PositionTracker {
BlockPos currentBlockPosition();
boolean isVisibleBy(final LivingEntity body);
+
+ boolean checkThread(net.minecraft.world.level.Level currOwnedByLevel); // Shiroha - Fix region threading with entity ai data access
}
diff --git a/net/minecraft/world/entity/ai/behavior/SleepInBed.java b/net/minecraft/world/entity/ai/behavior/SleepInBed.java
index 16017d819c28b077f732e2ef571eac179d24e323..7d0f7a42c26fe1e236b0b9696b2b962281dd6c70 100644
--- a/net/minecraft/world/entity/ai/behavior/SleepInBed.java
+++ b/net/minecraft/world/entity/ai/behavior/SleepInBed.java
@@ -49,6 +49,11 @@ public class SleepInBed extends Behavior<LivingEntity> {
return false;
}
+ // Shiroha - Fix region threading with entity ai data access
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(level, target.pos())) {
+ return false;
+ }
+ // Shiroha end
Optional<Long> lastWokenMemory = brain.getMemory(MemoryModuleType.LAST_WOKEN);
if (lastWokenMemory.isPresent()) {
long timeSinceLastWoken = level.getGameTime() - lastWokenMemory.get();
@@ -56,7 +61,6 @@ public class SleepInBed extends Behavior<LivingEntity> {
return false;
}
}
-
BlockState blockState = level.getBlockStateIfLoaded(target.pos()); // Paper - Prevent sync chunk loads when villagers try to find beds
if (blockState == null) return false; // Paper - Prevent sync chunk loads when villagers try to find beds
return target.pos().closerToCenterThan(body.position(), 2.0) && blockState.is(BlockTags.BEDS) && !blockState.getValue(BedBlock.OCCUPIED);
diff --git a/net/minecraft/world/entity/ai/memory/MemorySlot.java b/net/minecraft/world/entity/ai/memory/MemorySlot.java
index 88a89b4c72cc99dc89d3f3cc928b2dfda4125759..af210abbe1d4b75e1c6828cb25181c4caa0eca35 100644
--- a/net/minecraft/world/entity/ai/memory/MemorySlot.java
+++ b/net/minecraft/world/entity/ai/memory/MemorySlot.java
@@ -13,7 +13,7 @@ public class MemorySlot<T> {
this.timeToLive = timeToLive;
}
- public void tick() {
+ public void tick(net.minecraft.world.entity.Entity owner) { // Shiroha - Fix region threading with entity ai data access
if (this.hasValue() && this.canExpire()) {
if (this.hasExpired()) {
this.clear();
@@ -21,6 +21,41 @@ public class MemorySlot<T> {
this.timeToLive--;
}
}
+ // Shiroha start - Fix region threading with entity ai data access
+ final net.minecraft.world.level.Level ownerLevel = owner.level();
+
+ // type: entity
+ if (io.nanachiyo0721.shiroha.config.modules.fixes.ForceCleanupEntityBrainMemoryConfig.enabledForEntity && this.value instanceof net.minecraft.world.entity.Entity entity) {
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(entity)) {
+ this.clear();
+ }
+ }
+
+ // type: block_pos
+ if (io.nanachiyo0721.shiroha.config.modules.fixes.ForceCleanupEntityBrainMemoryConfig.enabledForBlockPos && this.value instanceof net.minecraft.core.BlockPos blockPos) {
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(ownerLevel, blockPos)) {
+ this.clear();
+ }
+ }
+
+
+ //type: position_tracker and walk_target
+ if (io.nanachiyo0721.shiroha.config.modules.fixes.ForceCleanupEntityBrainMemoryConfig.enabledForPositionTracker) {
+ net.minecraft.world.entity.ai.behavior.PositionTracker tracker = null;
+
+ if (value instanceof net.minecraft.world.entity.ai.behavior.PositionTracker positionTracker) {
+ tracker = positionTracker;
+ }
+
+ if (value instanceof net.minecraft.world.entity.ai.memory.WalkTarget walkTarget) {
+ tracker = walkTarget.getTarget();
+ }
+
+ if (tracker != null && !tracker.checkThread(owner.level())) {
+ this.clear();
+ }
+ }
+ // Shiroha end
}
public static <T> MemorySlot<T> create() {
diff --git a/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java b/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java
index e44814cfb6afb594456b8215bd13a92e93de2c85..e0ca242da89d06005da692172a65a37377de68aa 100644
--- a/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java
+++ b/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java
@@ -60,6 +60,17 @@ public class FlyingPathNavigation extends PathNavigation {
if (!this.isDone()) {
Vec3 target = this.path.getNextEntityPos(this.mob);
+ // Shiroha - Fix region threading with entity ai data access
+ if (io.nanachiyo0721.shiroha.config.modules.fixes.PathfindingFixesConfig.breakDownPathfindingWhenOutOfRegion) {
+ // we assume that:
+ // 1. The code above doesn't touch the 'main thread context' with the position from 'this.path'
+ // 2. The pathfinder could correctly recompute or discard the incorrect target position and this situation is happening rarely
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(this.mob.level(), target)) {
+ this.hasDelayedRecomputation = true;
+ return;
+ }
+ }
+ // Shiroha end
this.mob.getMoveControl().setWantedPosition(target.x, target.y, target.z, this.speedModifier);
}
}
diff --git a/net/minecraft/world/entity/ai/navigation/PathNavigation.java b/net/minecraft/world/entity/ai/navigation/PathNavigation.java
index 2ea1ec39a37899ae1510d0036aa670e758077537..18069d0b38ee08d798edc434875f6b5ca8bb15b5 100644
--- a/net/minecraft/world/entity/ai/navigation/PathNavigation.java
+++ b/net/minecraft/world/entity/ai/navigation/PathNavigation.java
@@ -188,6 +188,18 @@ public abstract class PathNavigation {
}
}
// Paper end - EntityPathfindEvent
+ // Shiroha start - Fix region threading with entity ai data access
+ if (io.nanachiyo0721.shiroha.config.modules.fixes.PathfindingFixesConfig.doNotPathfindToNotOwnedTargets) {
+ // filter the targets not owned by current region
+ targets = new java.util.HashSet<>(targets); // well no idea about how to determine if this should be copied to a modifiable one
+ targets.removeIf(pos -> !ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(this.mob.level(), pos));
+
+ // return if no available (observe the logic in the first if block)
+ if (targets.isEmpty()) {
+ return null;
+ }
+ }
+ // Shiroha end
ProfilerFiller profiler = Profiler.get();
profiler.push("pathfind");
BlockPos fromPos = above ? this.mob.blockPosition().above() : this.mob.blockPosition();
diff --git a/net/minecraft/world/entity/animal/allay/AllayAi.java b/net/minecraft/world/entity/animal/allay/AllayAi.java
index c3667e7997551e0f5ce63bc6ee890082d1431400..95c93df76eeec7eb3f19380efb1e2876b0625b2e 100644
--- a/net/minecraft/world/entity/animal/allay/AllayAi.java
+++ b/net/minecraft/world/entity/animal/allay/AllayAi.java
@@ -112,6 +112,16 @@ public class AllayAi {
Optional<GlobalPos> likedNoteblockPos = brain.getMemory(MemoryModuleType.LIKED_NOTEBLOCK_POSITION);
if (likedNoteblockPos.isPresent()) {
GlobalPos position = likedNoteblockPos.get();
+ // Shiroha - Fix region threading with entity ai data access
+ final Level targetLevel = allay.level().getServer().getLevel(position.dimension());
+ final BlockPos targetPos = position.pos();
+
+ // thread checks
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(targetLevel, targetPos)) {
+ brain.eraseMemory(MemoryModuleType.LIKED_NOTEBLOCK_POSITION); // The memory value is not being belong to current tick region anymore
+ return Optional.empty();
+ }
+ // Shiroha
if (shouldDepositItemsAtLikedNoteblock(allay, brain, position)) {
return Optional.of(new BlockPosTracker(position.pos().above()));
}
diff --git a/net/minecraft/world/entity/animal/sniffer/Sniffer.java b/net/minecraft/world/entity/animal/sniffer/Sniffer.java
index d5394ae7ce56555ad21aeafb2d78c291c62e2988..c49b0be376f29d21e81680e48659483f0d84b6f1 100644
--- a/net/minecraft/world/entity/animal/sniffer/Sniffer.java
+++ b/net/minecraft/world/entity/animal/sniffer/Sniffer.java
@@ -279,8 +279,18 @@ public class Sniffer extends Animal {
private boolean canDig(final BlockPos position) {
return this.level().getBlockState(position).is(BlockTags.SNIFFER_DIGGABLE_BLOCK)
- && this.getExploredPositions().noneMatch(explored -> GlobalPos.of(this.level().dimension(), position).equals(explored))
- && Optional.ofNullable(this.getNavigation().createPath(position, 1)).map(Path::canReach).orElse(false);
+ && this.getExploredPositions().noneMatch(explored -> { // Shiroha - Fix region threading with entity ai data access
+ // thread checks
+ final Level targetLevel = net.minecraft.server.MinecraftServer.getServer().getLevel(explored.dimension());
+ final BlockPos targetPos = explored.pos();
+
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(targetLevel, targetPos)) {
+ return false;
+ }
+
+ return GlobalPos.of(this.level().dimension(), position).equals(explored); // Original logic
+ }) // Shiroha end
+ && Optional.ofNullable(this.getNavigation().createPath(position, 1)).map(Path::canReach).orElse(false);
}
private void dropSeed() {
@@ -0,0 +1,35 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:13:39 +0800
Subject: [PATCH] Fix off region leashing
diff --git a/net/minecraft/world/entity/Leashable.java b/net/minecraft/world/entity/Leashable.java
index 98034a4c96bf2972316078d3b3a49140921aab50..ba4ee88ada40997759f4650b8d4aa9ecce0fab1d 100644
--- a/net/minecraft/world/entity/Leashable.java
+++ b/net/minecraft/world/entity/Leashable.java
@@ -95,10 +95,24 @@ public interface Leashable {
if (leashUuid.isPresent()) {
Entity leasher = serverLevel.getEntity(leashUuid.get());
if (leasher != null) {
+ // Shiroha start - Fix off region leashing
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(leasher)) {
+ entity.spawnAtLocation(serverLevel, Items.LEAD);
+ entity.setLeashData(null);
+ return;
+ }
+ // Shiroha end
setLeashedTo(entity, leasher, true);
return;
}
} else if (pos.isPresent()) {
+ // Shiroha start - Fix off region leashing
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(serverLevel, pos.get())) {
+ entity.spawnAtLocation(serverLevel, Items.LEAD);
+ entity.setLeashData(null);
+ return;
+ }
+ // Shiroha end
setLeashedTo(entity, LeashFenceKnotEntity.getOrCreateKnot(serverLevel, pos.get()), true);
return;
}
@@ -0,0 +1,30 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:15:26 +0800
Subject: [PATCH] Fix unpatched task returning of
ServerConfigurationPacketListenerImpl#disconnectAsync
Inspired by https://github.com/CraftCanvasMC/Canvas/blob/ver/1.21.8/canvas-server/minecraft-patches/sources/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch
but Canvas loses its main thread checks so fixed that btw
diff --git a/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java b/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
index 40b4eeb561a91264b9ab6ddc49cb8a93daae84a4..efcf294b523ca6b039eb2544546bf863ba717749 100644
--- a/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
@@ -290,13 +290,14 @@ public class ServerConfigurationPacketListenerImpl extends ServerCommonPacketLis
// Paper start
@Override
public void disconnectAsync(final net.minecraft.network.DisconnectionDetails disconnectionInfo) {
- if (this.cserver.isPrimaryThread()) {
+ if (io.papermc.paper.threadedregions.RegionizedServer.isGlobalTickThread()) { // Shiroha - Fix unpatched task returning of ServerConfigurationPacketListenerImpl#disconnectAsync
this.disconnect(disconnectionInfo);
return;
}
this.connection.setReadOnly();
- this.server.scheduleOnMain(() -> {
+ // this.server.scheduleOnMain(() -> { // Shiroha - Fix unpatched task returning of ServerConfigurationPacketListenerImpl#disconnectAsync
+ io.papermc.paper.threadedregions.RegionizedServer.getInstance().addTask(() -> { // Shiroha - Fix unpatched task returning of ServerConfigurationPacketListenerImpl#disconnectAsync
this.disconnect(disconnectionInfo); // Currently you cannot cancel disconnect during the config stage
});
}
@@ -0,0 +1,64 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:20:44 +0800
Subject: [PATCH] Fix riding statistics desync
Referred to: https://github.com/CraftCanvasMC/Canvas/commit/057175b0c10d5a4d1d9059fd9d077750c32633b2
diff --git a/net/minecraft/server/level/ServerPlayer.java b/net/minecraft/server/level/ServerPlayer.java
index 625c013e99f41a7d64e301100139f1bf4ee3e2e1..7ae5cd4a30e56c8877ea505287eb66e8a579d3f8 100644
--- a/net/minecraft/server/level/ServerPlayer.java
+++ b/net/minecraft/server/level/ServerPlayer.java
@@ -2537,7 +2537,7 @@ public class ServerPlayer extends Player implements ca.spottedleaf.moonrise.patc
}
}
- private void checkRidingStatistics(final double dx, final double dy, final double dz) {
+ public void checkRidingStatistics(final double dx, final double dy, final double dz) { // Shiroha - Fix riding statics desync - make public
if (this.isPassenger() && !didNotMove(dx, dy, dz)) {
int distance = Math.round((float)Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
Entity vehicle = this.getVehicle();
diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java
index a3f473cab6a37e65de233c7f77d9de7c967fcdd0..1bf85a60b3223c9a44bb3e3d6bffe8eb093a50e8 100644
--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -4199,7 +4199,13 @@ public abstract class Entity
}
}
+ // Shiroha start - Fix riding statics desync
public void adjustRiders(boolean teleport) {
+ this.adjustRiders(teleport, false);
+ }
+
+ public void adjustRiders(boolean teleport, boolean syncStatics) {
+ // Shiroha end - Fix riding statics desync
java.util.ArrayDeque<EntityTreeNode> queue = new java.util.ArrayDeque<>();
queue.add(this);
@@ -4212,14 +4218,24 @@ public abstract class Entity
for (EntityTreeNode passenger : passengers) {
queue.add(passenger);
+ // Shiroha start - Fix riding statics desync
+ final double oldX = passenger.root.getX();
+ final double oldY = passenger.root.getY();
+ final double oldZ = passenger.root.getZ();
+ // Shiroha end - Fix riding statics desync
curr.root.positionRider(passenger.root, teleport ? Entity::snapTo : Entity::setPos);
+ // Shiroha start - Fix riding statics desync
+ if (syncStatics && passenger.root instanceof net.minecraft.server.level.ServerPlayer serverPlayer) {
+ serverPlayer.checkRidingStatistics(serverPlayer.getX() - oldX, serverPlayer.getY() - oldY, serverPlayer.getZ() - oldZ);
+ }
+ // Shiroha end - Fix riding statics desync
}
}
}
}
public void repositionAllPassengers(boolean teleport) {
- this.makePassengerTree().adjustRiders(teleport);
+ this.makePassengerTree().adjustRiders(teleport, true); // Shiroha - Fix riding statics desync
}
protected EntityTreeNode makePassengerTree() {
@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:22:04 +0800
Subject: [PATCH] Fix player auto saving ignores interval
diff --git a/net/minecraft/server/level/ServerPlayer.java b/net/minecraft/server/level/ServerPlayer.java
index 7ae5cd4a30e56c8877ea505287eb66e8a579d3f8..f22b5fdec6da8bcff9aef3d9fed5dbe61d39250a 100644
--- a/net/minecraft/server/level/ServerPlayer.java
+++ b/net/minecraft/server/level/ServerPlayer.java
@@ -208,7 +208,7 @@ import org.slf4j.Logger;
public class ServerPlayer extends Player implements ca.spottedleaf.moonrise.patches.chunk_system.player.ChunkSystemServerPlayer { // Paper - rewrite chunk system
private static final Logger LOGGER = LogUtils.getLogger();
- public static final long LAST_SAVE_ABSENT = Long.MIN_VALUE; public long lastSave = LAST_SAVE_ABSENT; // Paper // Folia - threaded regions - changed to nanoTime
+ public static final long LAST_SAVE_ABSENT = Long.MIN_VALUE; public long lastSave = System.nanoTime(); // Paper // Folia - threaded regions - changed to nanoTime // Shiroha - Fix player auto saving ignores interval
private static final int NEUTRAL_MOB_DEATH_NOTIFICATION_RADII_XZ = 32;
private static final int NEUTRAL_MOB_DEATH_NOTIFICATION_RADII_Y = 10;
private static final int FLY_STAT_RECORDING_SPEED = 25;
@@ -0,0 +1,47 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:23:24 +0800
Subject: [PATCH] Fix dragon part desync
diff --git a/ca/spottedleaf/moonrise/patches/chunk_system/level/entity/server/ServerEntityLookup.java b/ca/spottedleaf/moonrise/patches/chunk_system/level/entity/server/ServerEntityLookup.java
index b31b55f00e2ce1bd6c1011fe852bd1dbb37de524..4e52c3a8887781a2299852c0c0d6f0fd26040d26 100644
--- a/ca/spottedleaf/moonrise/patches/chunk_system/level/entity/server/ServerEntityLookup.java
+++ b/ca/spottedleaf/moonrise/patches/chunk_system/level/entity/server/ServerEntityLookup.java
@@ -97,6 +97,7 @@ public final class ServerEntityLookup extends EntityLookup {
if (entity instanceof ThrownEnderpearl enderpearl) {
this.addEnderPearl(CoordinateUtils.getChunkKey(enderpearl.chunkPosition()), enderpearl.getId()); // Folia - region threading
}
+ if (entity instanceof net.minecraft.world.entity.boss.enderdragon.EnderDragon dragon) dragon.syncDragonPartsAfterTeleportTransform(); // Shiroha - Fix dragon part desync
entity.registerScheduler(); // Paper - optimise Folia entity scheduler
}
diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java
index 1bf85a60b3223c9a44bb3e3d6bffe8eb093a50e8..c5a9d380f318f176a2bf5d30a10a6d528d23bb92 100644
--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -4459,6 +4459,7 @@ public abstract class Entity
Entity copy = this.getType().create(destination, EntitySpawnReason.DIMENSION_TRAVEL);
copy.restoreFrom(this);
copy.transform(pos, yaw, pitch, velocity);
+ if (copy instanceof net.minecraft.world.entity.boss.enderdragon.EnderDragon dragon) dragon.syncDragonPartsAfterTeleportTransform(); // Shiroha - Fix dragon part desync
// vanilla code used to call remove _after_ copying, and some stuff is required to be after copy - so add hook here
// for example, clearing of inventory after switching dimensions
this.postRemoveAfterChangingDimensions();
diff --git a/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java b/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java
index ab921ab4b4cc860abd77744f2bd201013e136e51..cf227919723aeb1d33565787996821a1968f8106 100644
--- a/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java
+++ b/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java
@@ -1011,4 +1011,12 @@ public class EnderDragon extends Mob implements Enemy {
return 500;
}
// Paper end - init expToDrop for already dying spawned dragon
+
+ // Shiroha start - Fix dragon part desync
+ public void syncDragonPartsAfterTeleportTransform() {
+ for (EnderDragonPart part : this.subEntities) {
+ this.tickPart(part, 0.0, 0.0, 0.0); // offset -> 0.0
+ }
+ }
+ // Shiroha end
}
@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:25:15 +0800
Subject: [PATCH] Fix misbehaved ender pearls when player switched dimension
diff --git a/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java b/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java
index 501a0e89cc7bcfce6793f059b080b38666e0fb64..a5870da96da005ed682bc25eac3af6c771dee851 100644
--- a/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java
+++ b/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java
@@ -264,7 +264,7 @@ public class ThrownEnderpearl extends ThrowableItemProjectile {
int previousChunkZ = SectionPos.blockToSectionCoord(this.position().z());
Entity owner = this.owner != null ? findOwnerIncludingDeadPlayer(serverLevel, this.owner.getUUID()) : null;
if (owner instanceof ServerPlayer serverPlayer
- && !owner.isAlive()
+ && (owner.getBukkitEntity().taskScheduler.isRetired() || serverPlayer.getHealth() <= 0.0D) // Shiroha - Fix misbehaved ender pearls when player switched dimension
&& !serverPlayer.wonGame
&& serverPlayer.level().getGameRules().get(GameRules.ENDER_PEARLS_VANISH_ON_DEATH)) {
this.discard(org.bukkit.event.entity.EntityRemoveEvent.Cause.DESPAWN); // CraftBukkit - add Bukkit remove cause
@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Wed, 8 Jul 2026 22:00:35 +0800
Subject: [PATCH] Fix creative item picking
diff --git a/net/minecraft/world/entity/item/ItemEntity.java b/net/minecraft/world/entity/item/ItemEntity.java
index 223793bea54a483fefc66caa7e07b29ab351c339..9a75c6b38f1cabd4415067d781f6ad49f4d8ebc8 100644
--- a/net/minecraft/world/entity/item/ItemEntity.java
+++ b/net/minecraft/world/entity/item/ItemEntity.java
@@ -420,7 +420,7 @@ public class ItemEntity extends Entity implements TraceableEntity {
Item item = itemStack.getItem();
int orgCount = itemStack.getCount();
// CraftBukkit start - fire PlayerPickupItemEvent
- int canHold = player.getInventory().canHold(itemStack);
+ int canHold = player.hasInfiniteMaterials() ? orgCount : player.getInventory().canHold(itemStack); // Shiroha - Fix creative item picking
int remaining = orgCount - canHold;
boolean flyAtPlayer = false; // Paper
@@ -0,0 +1,63 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:34:46 +0800
Subject: [PATCH] Fix high velocity moving issue
On folia, entity usually cannot move out of the tickregion, but sometimes it actually does(like some end pearl gun that can shoot an end pearl to the block faraway than 10000 blocks even more). To fix this, we added a temporary fix which teleport these entities to the destination instead running its move logics so that we could ensure anything is under control.But one thing need to consider is that teleportAsync is actually calling halfway of the entity tick and there is still something running when teleportAsync called, which is actually modified the entity in another thread, so there is still need an improvement
Reference from : https://github.com/KaiijuMC/Kaiiju/blob/ver/1.20.1/patches/server/0040-Teleport-async-if-we-cannot-move-entity-off-main.patch
diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java
index c5a9d380f318f176a2bf5d30a10a6d528d23bb92..5f7dad51fdca3b85f8ae164b1f58241e83ea44d5 100644
--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -1163,6 +1163,19 @@ public abstract class Entity
this.moveStartZ = this.getZ();
this.moveVector = delta;
}
+ // Shiroha start - Fix high velocity moving issue
+ // Filter the threads as it may be called by the chunk system worker thread
+ if (io.nanachiyo0721.shiroha.config.modules.fixes.FoliaEntityMovingFixConfig.enabled && ca.spottedleaf.moonrise.common.util.TickThread.isTickThread()){
+ var finalPosition = delta.add(this.position);
+ // not NaN (Prevent incorrect checks under NaN minecarts)
+ if (!Double.isNaN(finalPosition.x) && !Double.isNaN(finalPosition.y) && !Double.isNaN(finalPosition.z)) {
+ // kill tick passively if it's moving out of region and we'll catch this exception
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(this.level,finalPosition)) {
+ throw new io.nanachiyo0721.shiroha.utils.entity.EntityMoveOutOfRegionException(this, delta, moverType);
+ }
+ }
+ }
+ // Shiroha end
try {
// Paper end - detailed watchdog information
if (this.noPhysics) {
diff --git a/net/minecraft/world/level/Level.java b/net/minecraft/world/level/Level.java
index a0eb1f608a99301e0197ab1d1a6fbbb0a0be4ce0..52bcb87e96f7b5997559bd532481f548be03e6da 100644
--- a/net/minecraft/world/level/Level.java
+++ b/net/minecraft/world/level/Level.java
@@ -1571,6 +1571,25 @@ public abstract class Level implements LevelAccessor, AutoCloseable, ca.spottedl
public <T extends Entity> void guardEntityTick(final Consumer<T> tick, final T entity) {
try {
tick.accept(entity);
+ } catch (io.nanachiyo0721.shiroha.utils.entity.EntityMoveOutOfRegionException moveOutOfRegionException) { // Shiroha - Fix high velocity moving issue
+ // Shiroha start - Fix high velocity moving issue
+ final Entity ent = moveOutOfRegionException.getEntity();
+ var currPosition = ent.position();
+ var toPosition = moveOutOfRegionException.getMovement().add(currPosition);
+
+ if (io.nanachiyo0721.shiroha.config.modules.fixes.FoliaEntityMovingFixConfig.warnOnDetected) {
+ MinecraftServer.LOGGER.warn("Entity {} with entityId {} has tried moving to another region!",ent, ent.getId());
+ }
+
+ ent.getBukkitEntity().taskScheduler.scheduleOrExecute(entityFresh -> entityFresh.teleportAsync(
+ (ServerLevel) entityFresh.level(),
+ toPosition,
+ entityFresh.getYRot(), entityFresh.getXRot(),
+ entityFresh.getDeltaMovement(), org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.UNKNOWN,
+ Entity.TELEPORT_FLAG_LOAD_CHUNK | Entity.TELEPORT_FLAG_TELEPORT_PASSENGERS,
+ null
+ ));
+ // Shiroha end
} catch (Throwable t) {
// Paper start - Prevent block entity and entity crashes
final String msg = String.format("Entity threw exception at %s:%s,%s,%s", io.papermc.paper.util.MCUtil.getLevelName(entity.level()), entity.getX(), entity.getY(), entity.getZ());
@@ -0,0 +1,47 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:37:19 +0800
Subject: [PATCH] Fix teleport missing original rotation and velocity
diff --git a/io/papermc/paper/threadedregions/TeleportUtils.java b/io/papermc/paper/threadedregions/TeleportUtils.java
index 2a64a5b2cf049661fe3f5a22ddfa39979624f5ec..335e9775e0d9a61f0e9641aba691a3bdf3ac7f2b 100644
--- a/io/papermc/paper/threadedregions/TeleportUtils.java
+++ b/io/papermc/paper/threadedregions/TeleportUtils.java
@@ -41,7 +41,7 @@ public final class TeleportUtils {
return;
}
(useFromRootVehicle ? realFrom.getRootVehicle() : realFrom).teleportAsync(
- ((CraftWorld)loc.getWorld()).getHandle(), pos, null, null, null,
+ ((CraftWorld)loc.getWorld()).getHandle(), pos, yaw, pitch, null, // Shiroha - Fix teleport missing original rotation and velocity
cause, teleportFlags, onComplete
);
},
diff --git a/net/minecraft/server/commands/TeleportCommand.java b/net/minecraft/server/commands/TeleportCommand.java
index 13d7965fd4f99f0848b080349df41f8b1c31a19b..9c5583886ccabb536a519e5a998ed798227ec5fd 100644
--- a/net/minecraft/server/commands/TeleportCommand.java
+++ b/net/minecraft/server/commands/TeleportCommand.java
@@ -248,8 +248,8 @@ public class TeleportCommand {
// Folia start - region threading
if (true) {
Vec3 posFinal = new Vec3(x, y, z);
- Float yawFinal = Float.valueOf(newYRot);
- Float pitchFinal = Float.valueOf(newXRot);
+ Float yawFinal = Float.valueOf(newYRot + victim.getYRot()); // Shiroha - Fix teleport missing original rotation and velocity
+ Float pitchFinal = Float.valueOf(newXRot + victim.getXRot()); // Shiroha - Fix teleport missing original rotation and velocity
victim.getBukkitEntity().taskScheduler.schedule((Entity nmsEntity) -> {
nmsEntity.stopRiding();
nmsEntity.teleportAsync(
diff --git a/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java b/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java
index a5870da96da005ed682bc25eac3af6c771dee851..4672d76ecf926975948135598f55405518e0007b 100644
--- a/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java
+++ b/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java
@@ -99,7 +99,7 @@ public class ThrownEnderpearl extends ThrowableItemProjectile {
}
entity.teleportAsync(
- checkWorld, to, null, null, null,
+ checkWorld, to, null, null, entity.getDeltaMovement(), // Shiroha - Fix teleport missing original rotation and velocity
org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.ENDER_PEARL,
// chunk could have been unloaded
Entity.TELEPORT_FLAG_TELEPORT_PASSENGERS | Entity.TELEPORT_FLAG_LOAD_CHUNK,
@@ -0,0 +1,29 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Fri, 10 Jul 2026 15:48:51 +0800
Subject: [PATCH] Force clamp grid-exponent to 1~6
diff --git a/io/papermc/paper/threadedregions/TickRegions.java b/io/papermc/paper/threadedregions/TickRegions.java
index a6ab9cb01f4f49f5f44b6ed324fa6d51139aabb6..7bf49d2c235cb3f6c4cd8de4d127f476c7deb069 100644
--- a/io/papermc/paper/threadedregions/TickRegions.java
+++ b/io/papermc/paper/threadedregions/TickRegions.java
@@ -27,7 +27,7 @@ import java.util.function.BooleanSupplier;
public final class TickRegions implements ThreadedRegionizer.RegionCallbacks<TickRegions.TickRegionData, TickRegions.TickRegionSectionData> {
private static final Logger LOGGER = LogUtils.getLogger();
- private static int regionShift = 31;
+ private static int regionShift = ca.spottedleaf.moonrise.patches.chunk_system.scheduling.ThreadedTicketLevelPropagator.SECTION_SHIFT; // Shiroha - Force clamp grid-exponent to 1~6
public static int getRegionChunkShift() {
return regionShift;
@@ -68,7 +68,8 @@ public final class TickRegions implements ThreadedRegionizer.RegionCallbacks<Tic
initialised = true;
int gridExponent = config.gridExponent;
gridExponent = Math.max(0, gridExponent);
- gridExponent = Math.min(31, gridExponent);
+ if (gridExponent > ca.spottedleaf.moonrise.patches.chunk_system.scheduling.ThreadedTicketLevelPropagator.SECTION_SHIFT) LOGGER.warn("You are using a grid-exponent ({}) which is larger than the ticket lock shift! This would lead to randomly fatal crash !!!, Clamping back to max allowed {}", gridExponent, ca.spottedleaf.moonrise.patches.chunk_system.scheduling.ThreadedTicketLevelPropagator.SECTION_SHIFT); // Shiroha - Force clamp grid-exponent to 1~6
+ gridExponent = Math.min(ca.spottedleaf.moonrise.patches.chunk_system.scheduling.ThreadedTicketLevelPropagator.SECTION_SHIFT, gridExponent); // Shiroha - Force clamp grid-exponent to 1~6
regionShift = gridExponent;
scheduler = new TickRegionScheduler(config.scheduler, tickThreads);
LOGGER.info("Initialised " + config.scheduler + " Folia scheduler with initial " + tickThreads + " target thread(s)");
@@ -0,0 +1,98 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:27:00 +0800
Subject: [PATCH] Force disable builtin spark plugin
The spark passed down from paper has some memory leaking issue, so we fully removed it from the code to prevent that memory leaking issue.
diff --git a/net/minecraft/server/MinecraftServer.java b/net/minecraft/server/MinecraftServer.java
index 78e9cf21fb5487e5eeec04e589c2a84c1e6b06af..b01e00de94d8fa45359d3d14a8481287276adb68 100644
--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -672,8 +672,8 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
}
// Paper end - Configurable player collision; Handle collideRule team for player collision toggle
this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.POSTWORLD);
- this.server.spark.registerCommandBeforePlugins(this.server); // Paper - spark
- this.server.spark.enableAfterPlugins(this.server); // Paper - spark
+ if (false) this.server.spark.registerCommandBeforePlugins(this.server); // Paper - spark // Shiroha - Force disable builtin spark
+ if (false) this.server.spark.enableAfterPlugins(this.server); // Paper - spark // Shiroha - Force disable builtin spark
io.papermc.paper.command.brigadier.PaperCommands.INSTANCE.setValid(); // Paper - reset invalid state for event fire below
io.papermc.paper.plugin.lifecycle.event.LifecycleEventRunner.INSTANCE.callReloadableRegistrarEvent(io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents.COMMANDS, io.papermc.paper.command.brigadier.PaperCommands.INSTANCE, org.bukkit.plugin.Plugin.class, io.papermc.paper.plugin.lifecycle.event.registrar.ReloadableRegistrarEvent.Cause.INITIAL); // Paper - call commands event for regular plugins
this.server.getCommandMap().registerServerAliases(); // Paper - relocate initial CommandMap#registerServerAliases() call
@@ -1087,7 +1087,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
Commands.COMMAND_SENDING_POOL.shutdownNow(); // Paper - Perf: Async command map building; Shutdown and don't bother finishing
// CraftBukkit start
if (this.server != null) {
- this.server.spark.disable(); // Paper - spark
+ if (false) this.server.spark.disable(); // Paper - spark // Shiroha - Force disable builtin spark
this.server.disablePlugins();
this.server.waitForAsyncTasksShutdown(); // Paper - Wait for Async Tasks during shutdown
}
@@ -1350,7 +1350,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
this.statusIcon = this.loadStatusIcon().orElse(null);
this.status = this.buildServerStatus();
- this.server.spark.enableBeforePlugins(); // Paper - spark
+ if (false) this.server.spark.enableBeforePlugins(); // Paper - spark // Shiroha - Force disable builtin spark
// Folia start - region threading
if (true) {
io.papermc.paper.threadedregions.RegionizedServer.getInstance().init(); // Folia - region threading - only after loading worlds
@@ -1664,7 +1664,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
}
if (this.emptyTicks >= emptyTickThreshold) {
- this.server.spark.tickStart(); // Paper - spark
+ if (false) this.server.spark.tickStart(); // Paper - spark // Shiroha - Force disable builtin spark
if (this.emptyTicks == emptyTickThreshold) {
LOGGER.info("Server empty for {} seconds, pausing", this.pauseWhenEmptySeconds());
this.autoSave();
@@ -1683,7 +1683,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
// Paper end - avoid issues with certain tasks not processing during sleep
//this.server.spark.executeMainThreadTasks(); // Paper - spark // Folia - region threading
this.tickConnection();
- this.server.spark.tickEnd(((double)(System.nanoTime() - this.currentTickStart) / 1000000D)); // Paper - spark
+ if (false) this.server.spark.tickEnd(((double)(System.nanoTime() - this.currentTickStart) / 1000000D)); // Paper - spark // Shiroha - Force disable builtin spark
return;
}
}
@@ -1696,7 +1696,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
};
// Folia end - region threading
- this.server.spark.tickStart(); // Paper - spark
+ if (false) this.server.spark.tickStart(); // Paper - spark // Shiroha - Force disable builtin spark
new com.destroystokyo.paper.event.server.ServerTickStartEvent((int)region.getCurrentTick()).callEvent(); // Paper - Server Tick Events // Folia - region threading
// Folia start - region threading
if (region != null) {
@@ -1773,7 +1773,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
long remaining = scheduledEnd - endTime; // Folia - region ticking
new com.destroystokyo.paper.event.server.ServerTickEndEvent((int)io.papermc.paper.threadedregions.RegionizedServer.getCurrentTick(), ((double)(endTime - startTime) / 1000000D), remaining).callEvent(); // Folia - region ticking
// Paper end - Server Tick Events
- this.server.spark.tickEnd(((double)(endTime - startTime) / 1000000D)); // Paper - spark // Folia - region threading
+ if (false) this.server.spark.tickEnd(((double)(endTime - startTime) / 1000000D)); // Paper - spark // Folia - region threading // Shiroha - Force disable builtin spark
// Folia - region threading
}
diff --git a/net/minecraft/server/dedicated/DedicatedServer.java b/net/minecraft/server/dedicated/DedicatedServer.java
index 17244a82d7591004a43c013748f3db0507e73d7e..4d4a1475b315dd3cb855443ecd1fa75f05bb3502 100644
--- a/net/minecraft/server/dedicated/DedicatedServer.java
+++ b/net/minecraft/server/dedicated/DedicatedServer.java
@@ -239,7 +239,7 @@ public class DedicatedServer extends MinecraftServer implements ServerInterface
this.paperConfigurations.initializeWorldDefaultsConfiguration(this.registryAccess());
// Paper end - initialize global and world-defaults configuration
io.nanachiyo0721.shiroha.config.ConfigManager.loadConfigFiles(); // Shiroha - Config system framework - load config file
- this.server.spark.enableEarlyIfRequested(); // Paper - spark
+ if (false) this.server.spark.enableEarlyIfRequested(); // Paper - spark // Shiroha - Force disable builtin spark
// Paper start - fix converting txt to json file; convert old users earlier after PlayerList creation but before file load/save
if (this.convertOldUsers()) {
this.services().nameToIdCache().save(false); // Paper
@@ -249,7 +249,7 @@ public class DedicatedServer extends MinecraftServer implements ServerInterface
org.spigotmc.WatchdogThread.doStart(org.spigotmc.SpigotConfig.timeoutTime, org.spigotmc.SpigotConfig.restartOnCrash); // Paper - start watchdog thread
consoleThread.start(); // Paper - Enhance console tab completions for brigadier commands; start console thread after MinecraftServer.console & PaperConfig are initialized
io.papermc.paper.command.PaperCommands.registerCommands(this); // Paper - setup /paper command
- this.server.spark.registerCommandBeforePlugins(this.server); // Paper - spark
+ if (false) this.server.spark.registerCommandBeforePlugins(this.server); // Paper - spark // Shiroha - Force disable builtin spark
com.destroystokyo.paper.Metrics.PaperMetrics.startMetrics(); // Paper - start metrics
com.destroystokyo.paper.VersionHistoryManager.INSTANCE.getClass(); // Paper - load version history now
@@ -0,0 +1,24 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 21:28:42 +0800
Subject: [PATCH] Prevent tamable animals check can teleport in an unloaded
chunk
Based on the implementation of Canvas(https://github.com/CraftCanvasMC/Canvas/commit/af2aacb12cbccfd328dda4961167786f5d9dad53)
We need to check canTeleport for TamableAnimal but this logic could do the check in another tick region itself, so we need to prevent that. But it needs to push off this check to schedule to the correct tickregion, which needs costly rewriting of this logic, so we could simply allow the read when the owner's position is loaded
diff --git a/net/minecraft/world/entity/TamableAnimal.java b/net/minecraft/world/entity/TamableAnimal.java
index 95ba821a895c7ea8fffcbf1df2e7b3c174463d9e..1e076d368f2e34b83b94e939ca9856bae4e9f86e 100644
--- a/net/minecraft/world/entity/TamableAnimal.java
+++ b/net/minecraft/world/entity/TamableAnimal.java
@@ -318,7 +318,8 @@ public abstract class TamableAnimal extends Animal implements OwnableEntity {
return false;
}
- BlockState blockStateBelow = this.level().getBlockState(pos.below());
+ BlockState blockStateBelow = this.level().getBlockStateIfLoaded(pos.below()); // Shiroha - Prevent tamable animals check can teleport in an unloaded chunk
+ if (blockStateBelow == null) return false; // Shiroha - Prevent tamable animals check can teleport in an unloaded chunk
if (!this.canFlyToOwner() && blockStateBelow.getBlock() instanceof LeavesBlock) {
return false;
}
@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: NanaChiyo0721 <nanachiyo0721@163.com>
Date: Mon, 13 Jul 2026 23:10:31 +0800
Subject: [PATCH] Replace packet processing queue with mt-queue
diff --git a/net/minecraft/network/PacketProcessor.java b/net/minecraft/network/PacketProcessor.java
index 10fa576838c726d026df078eef6c693d14c2cbda..20fa23988efbfb50c664fa48cc823adbe8e6ce58 100644
--- a/net/minecraft/network/PacketProcessor.java
+++ b/net/minecraft/network/PacketProcessor.java
@@ -11,7 +11,7 @@ import org.slf4j.Logger;
public class PacketProcessor implements AutoCloseable {
private static final Logger LOGGER = LogUtils.getLogger();
- private final Queue<PacketProcessor.ListenerAndPacket<?>> packetsToBeHandled = Queues.newConcurrentLinkedQueue();
+ private final Queue<PacketProcessor.ListenerAndPacket<?>> packetsToBeHandled = new ca.spottedleaf.concurrentutil.collection.MultiThreadedQueue<>(); // Shiroha - Replace packet processing queue with mt-queue
private final Thread runningThread;
private boolean closed;
@@ -0,0 +1,288 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 22:23:29 +0800
Subject: [PATCH] Async protocol switching optimization
diff --git a/net/minecraft/network/Connection.java b/net/minecraft/network/Connection.java
index 40f54536422fa38bd84017fc634808016b4de58b..d0dff5850717bd083b7a29104a61754ce1b2f822 100644
--- a/net/minecraft/network/Connection.java
+++ b/net/minecraft/network/Connection.java
@@ -1067,4 +1067,127 @@ public class Connection extends SimpleChannelInboundHandler<Packet<?>> {
}
}
// Paper end - Optimize network
+ // Shiroha start - async protocol switcher
+ public <T extends PacketListener> void setupInboundProtocolAsync(
+ ProtocolInfo<T> protocol,
+ T packetListener,
+ @Nullable Runnable callback,
+ boolean resumeAutoReading
+ ) {
+ this.validateListener(protocol, packetListener);
+ if (protocol.flow() != this.getReceiving()) {
+ throw new IllegalStateException("Invalid inbound protocol: " + protocol.id());
+ } else {
+ this.packetListener = packetListener;
+ this.disconnectListener = null;
+
+ UnconfiguredPipelineHandler.InboundConfigurationTask configMessage = UnconfiguredPipelineHandler.setupInboundProtocol(protocol);
+ BundlerInfo bundlerInfo = protocol.bundlerInfo();
+ if (bundlerInfo != null) {
+ PacketBundlePacker newBundler = new PacketBundlePacker(bundlerInfo);
+ configMessage = configMessage.andThen(context -> context.pipeline().addAfter("decoder", "bundler", newBundler));
+ }
+
+ // Here we could execute it in event loop async to prevent waiting io task on main
+ // stop reading new packets to prevent some packets came into pipeline too early
+ this.channel.config().setAutoRead(false);
+
+ // do our configuration task
+ final UnconfiguredPipelineHandler.InboundConfigurationTask finalInboundConfigurationTask = configMessage;
+ Runnable toExecute = () -> this.channel.writeAndFlush(finalInboundConfigurationTask).addListener(future -> {
+ try {
+ if (future.isSuccess()) {
+ if (callback != null) callback.run(); // retire callback if there have one
+ return;
+ }
+
+ final Throwable ex = future.cause();
+
+ // here we process our exceptions like that blocking one
+ if (ex instanceof ClosedChannelException) {
+ LOGGER.info("Connection closed during protocol change");
+ } else {
+ this.channel.pipeline().fireExceptionCaught(ex);
+ }
+ }finally {
+ // reset auto back and resume reading if needed
+ if (resumeAutoReading) {
+ this.channel.config().setAutoRead(true);
+ this.channel.read();
+ }
+ }
+ });
+
+ // we need to do this inside the event loop
+ if (!this.channel.eventLoop().inEventLoop()) {
+ this.channel.eventLoop().execute(toExecute);
+ return;
+ }
+
+ toExecute.run();
+ }
+ }
+
+ public void setupOutboundProtocolAsync(
+ ProtocolInfo<?> protocol,
+ @Nullable Runnable callback,
+ boolean resumeAutoReading
+ ) {
+ if (protocol.flow() != this.getSending()) {
+ throw new IllegalStateException("Invalid outbound protocol: " + protocol.id());
+ } else {
+ UnconfiguredPipelineHandler.OutboundConfigurationTask configMessage = UnconfiguredPipelineHandler.setupOutboundProtocol(protocol);
+ BundlerInfo bundlerInfo = protocol.bundlerInfo();
+ if (bundlerInfo != null) {
+ PacketBundleUnpacker newUnbundler = new PacketBundleUnpacker(bundlerInfo);
+ configMessage = configMessage.andThen(
+ context -> context.pipeline().addAfter("encoder", "unbundler", newUnbundler)
+ );
+ }
+
+ boolean isLoginProtocol = protocol.id() == ConnectionProtocol.LOGIN;
+
+ // Here we could execute it in event loop async to prevent waiting io task on main
+ // stop reading new packets to prevent some packets came into pipeline too early
+ this.channel.config().setAutoRead(false);
+
+ // do our configuration task
+ final UnconfiguredPipelineHandler.OutboundConfigurationTask finalOutboundConfigurationTask = configMessage;
+ final Runnable writeTask = () -> this.channel.writeAndFlush(
+ finalOutboundConfigurationTask.andThen(context -> this.sendLoginDisconnect = isLoginProtocol)
+ ).addListener(future -> {
+ try {
+ if (future.isSuccess()) {
+ if (callback != null) callback.run(); // retire callback if there have one
+ return;
+ }
+
+ final Throwable ex = future.cause();
+
+ // here we process our exceptions like that blocking one
+ if (ex instanceof ClosedChannelException) {
+ LOGGER.info("Connection closed during protocol change");
+ } else {
+ this.channel.pipeline().fireExceptionCaught(ex);
+ }
+ }finally {
+ // reset auto back and resume reading if needed
+ if (resumeAutoReading) {
+ this.channel.config().setAutoRead(true);
+ this.channel.read(); // read once
+ }
+ }
+ });
+
+ // we need to do this inside the event loop
+ if (!this.channel.eventLoop().inEventLoop()) {
+ this.channel.eventLoop().execute(writeTask);
+ return;
+ }
+
+ writeTask.run();
+ }
+ }
+ // Shiroha end
+
}
diff --git a/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java b/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
index efcf294b523ca6b039eb2544546bf863ba717749..343c98fb35eb4cb736d26f67a11c00efb8622cf8 100644
--- a/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
@@ -188,8 +188,9 @@ public class ServerConfigurationPacketListenerImpl extends ServerCommonPacketLis
public void handleConfigurationFinished(final ServerboundFinishConfigurationPacket packet) {
PacketUtils.ensureRunningOnSameThread(packet, this, this.server.packetProcessor());
this.finishCurrentTask(JoinWorldTask.TYPE);
- this.connection.setupOutboundProtocol(GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(this.server.registryAccess())));
+ // this.connection.setupOutboundProtocol(GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(this.server.registryAccess()))); // Shiroha - Async protocol switch - move down
+ Runnable afterSwitch = () -> { // Shiroha - Async protocol switch
try {
PlayerList playerList = this.server.getPlayerList();
if (playerList.getPlayer(this.gameProfile.id()) != null) {
@@ -235,6 +236,18 @@ public class ServerConfigurationPacketListenerImpl extends ServerCommonPacketLis
LOGGER.error("Couldn't place player in world", e);
this.disconnect(DISCONNECT_REASON_INVALID_DATA);
}
+ // Shiroha start - Async protocol switch
+ };
+ if (!io.nanachiyo0721.shiroha.config.modules.optimizations.AsyncProtocolChangeConfig.enabled) {
+ this.connection.setupOutboundProtocol(GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(this.server.registryAccess())));
+ afterSwitch.run(); // directly run callback as we won't process any packet this time
+ } else {
+ this.connection.setupOutboundProtocolAsync(GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(this.server.registryAccess())), () -> {
+ // push back
+ io.papermc.paper.threadedregions.RegionizedServer.getInstance().addTask(afterSwitch);
+ }, false); // we will start auto read once we set up inbound handler at placeNewPlayer in PlayerList
+ }
+ // Shiroha end
}
@Override
diff --git a/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/net/minecraft/server/network/ServerGamePacketListenerImpl.java
index eda7e765c7c2ffee305edc81e0c7a6b1e5bfa18d..4c9ea818be83ed3c4dacc762f4d0e8c0f177cd19 100644
--- a/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerGamePacketListenerImpl.java
@@ -2884,7 +2884,13 @@ public class ServerGamePacketListenerImpl
} // Folia end - rewrite login process - move connection ownership to global region
this.waitingForSwitchToConfig = true; // Folia - rewrite login process - fix bad ordering of this field write - moved down
this.send(ClientboundStartConfigurationPacket.INSTANCE);
+ if (!io.nanachiyo0721.shiroha.config.modules.optimizations.AsyncProtocolChangeConfig.enabled) { // Shiroha - Async protocol switch
this.connection.setupOutboundProtocol(ConfigurationProtocols.CLIENTBOUND);
+ // Shiroha start - Async protcol switch
+ } else {
+ this.connection.setupOutboundProtocolAsync(ConfigurationProtocols.CLIENTBOUND, null, true);
+ }
+ // Shiroha end
}
@Override
@@ -3769,12 +3775,26 @@ public class ServerGamePacketListenerImpl
}
final ServerConfigurationPacketListenerImpl listener = new ServerConfigurationPacketListenerImpl(this.server, this.connection, this.createCookie(this.player.clientInformation())); // Paper
+ if (!io.nanachiyo0721.shiroha.config.modules.optimizations.AsyncProtocolChangeConfig.enabled) { // Shiroha - Async protocol switch
this.connection
.setupInboundProtocol(
ConfigurationProtocols.SERVERBOUND,
listener // Paper
);
new io.papermc.paper.event.connection.configuration.PlayerConnectionReconfigureEvent(listener.paperConnection).callEvent(); // Paper
+ } // Shiroha - Async protocol switch - add "{"
+ // Shiroha start - Async protocol switch - move up
+ else
+ this.connection.setupInboundProtocolAsync(
+ ConfigurationProtocols.SERVERBOUND,
+ listener,
+ () -> {
+ new io.papermc.paper.event.connection.configuration.PlayerConnectionReconfigureEvent(listener.paperConnection).callEvent(); // Paper
+ },
+ true
+ );
+ // Shiroha end
+ // new io.papermc.paper.event.connection.configuration.PlayerConnectionReconfigureEvent(listener.paperConnection).callEvent(); // Paper // Shiroha - Async protocol switch - move up
}
@Override
diff --git a/net/minecraft/server/network/ServerLoginPacketListenerImpl.java b/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
index f2329d1a9d9d4bf4c9d771e25e54f2f9ef65a76c..7de3bbecea2f11e4e1cb65408729f346760dc9b8 100644
--- a/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
@@ -435,12 +435,30 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener,
public void handleLoginAcknowledgement(final ServerboundLoginAcknowledgedPacket packet) {
net.minecraft.network.protocol.PacketUtils.ensureRunningOnSameThread(packet, this, this.server.packetProcessor()); // CraftBukkit
Validate.validState(this.state == ServerLoginPacketListenerImpl.State.PROTOCOL_SWITCHING, "Unexpected login acknowledgement packet");
- this.connection.setupOutboundProtocol(ConfigurationProtocols.CLIENTBOUND);
+ /*this.connection.setupOutboundProtocol(ConfigurationProtocols.CLIENTBOUND); // Shiroha - Async protocol switch - Rewrite
CommonListenerCookie cookie = CommonListenerCookie.createInitial(Objects.requireNonNull(this.authenticatedProfile), this.transferred);
ServerConfigurationPacketListenerImpl configPacketListener = new ServerConfigurationPacketListenerImpl(this.server, this.connection, cookie);
this.connection.setupInboundProtocol(ConfigurationProtocols.SERVERBOUND, configPacketListener);
configPacketListener.startConfiguration();
- this.state = ServerLoginPacketListenerImpl.State.ACCEPTED;
+ this.state = ServerLoginPacketListenerImpl.State.ACCEPTED;*/ // Shiroha - Async protocol switch - Rewrite
+
+ // Shiroha start - Async protocol switch
+ CommonListenerCookie cookie = CommonListenerCookie.createInitial(Objects.requireNonNull(this.authenticatedProfile), this.transferred);
+ ServerConfigurationPacketListenerImpl configPacketListener = new ServerConfigurationPacketListenerImpl(this.server, this.connection, cookie);
+
+ Runnable afterSwitch = () -> io.papermc.paper.threadedregions.RegionizedServer.getInstance().addTask(configPacketListener::startConfiguration); // push back to main thread
+
+ if (!io.nanachiyo0721.shiroha.config.modules.optimizations.AsyncProtocolChangeConfig.enabled) {
+ this.connection.setupOutboundProtocol(ConfigurationProtocols.CLIENTBOUND);
+ this.connection.setupInboundProtocol(ConfigurationProtocols.SERVERBOUND, configPacketListener);
+ afterSwitch.run();
+ return;
+ }
+
+ this.connection.setupInboundProtocolAsync(ConfigurationProtocols.SERVERBOUND, configPacketListener, () -> {
+ this.connection.setupOutboundProtocolAsync(ConfigurationProtocols.CLIENTBOUND, afterSwitch, true); // start auto read when everything is ready
+ }, false); // we will resume auto reading once the outbound protocol is also setup
+ // Shiroha end
}
@Override
diff --git a/net/minecraft/server/players/PlayerList.java b/net/minecraft/server/players/PlayerList.java
index e7579a9873362317dd82b63306cf650af9472574..9e90197b96fcac958c5073ca8f560e77bb811460 100644
--- a/net/minecraft/server/players/PlayerList.java
+++ b/net/minecraft/server/players/PlayerList.java
@@ -237,9 +237,11 @@ public abstract class PlayerList {
// only after setting the connection listener to game type, add the connection to this regions list
level.getCurrentWorldData().connections.add(connection);
// Folia end - rewrite login process
+ if (!io.nanachiyo0721.shiroha.config.modules.optimizations.AsyncProtocolChangeConfig.enabled) { // Shiroha - Async protocol switch // we will run async switch once these main thread logics became done
connection.setupInboundProtocol(
GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(this.server.registryAccess()), playerConnection), playerConnection
);
+ } // Shiroha - Async protocol switch
playerConnection.suspendFlushing();
GameRules gameRules = level.getGameRules();
boolean immediateRespawn = gameRules.get(GameRules.IMMEDIATE_RESPAWN);
@@ -403,6 +405,17 @@ public abstract class PlayerList {
);
}
// Paper end - Send empty chunk
+ // Shiroha start - Async protocol switch
+ if (io.nanachiyo0721.shiroha.config.modules.optimizations.AsyncProtocolChangeConfig.enabled) {
+ // auto read will be enabled once the async switch is done
+ connection.setupInboundProtocolAsync(
+ GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(this.server.registryAccess()), playerConnection),
+ playerConnection,
+ null, // we don't need to do anything more
+ true // start auto read which we have disabled in configuration handler
+ );
+ }
+ // Shiroha end
}
public void updateEntireScoreboard(final ServerScoreboard scoreboard, final ServerPlayer player) {
@@ -0,0 +1,367 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: SakuraiMochi0721 <sakuraimochi0721@163.com>
Date: Sun, 12 Jul 2026 10:15:29 +0800
Subject: [PATCH] Improved server health command
This is generated by calude
As it's only change the display, no tests and review are required
diff --git a/io/papermc/paper/threadedregions/commands/CommandServerHealth.java b/io/papermc/paper/threadedregions/commands/CommandServerHealth.java
index aa860cfe9de616f185163fe74e0f4f49bd13a805..3545258acc0f516045594674c6f39f749d4d073a 100644
--- a/io/papermc/paper/threadedregions/commands/CommandServerHealth.java
+++ b/io/papermc/paper/threadedregions/commands/CommandServerHealth.java
@@ -42,46 +42,88 @@ public final class CommandServerHealth extends Command {
return new DecimalFormat("#,##0");
});
- private static final TextColor HEADER = TextColor.color(79, 164, 240);
- private static final TextColor PRIMARY = TextColor.color(48, 145, 237);
- private static final TextColor SECONDARY = TextColor.color(104, 177, 240);
- private static final TextColor INFORMATION = TextColor.color(145, 198, 243);
- private static final TextColor LIST = TextColor.color(33, 97, 188);
+ private static final TextColor HEADER = TextColor.color(0xcb, 0xa6, 0xf7); // Shiroha - Catppuccin Mocha: Mauve
+ private static final TextColor PRIMARY = TextColor.color(0xa6, 0xad, 0xc8); // Shiroha - Catppuccin Mocha: Subtext0
+ private static final TextColor SECONDARY = TextColor.color(0xb4, 0xbe, 0xfe); // Shiroha - Catppuccin Mocha: Lavender
+ private static final TextColor INFORMATION = TextColor.color(0xcd, 0xd6, 0xf4); // Shiroha - Catppuccin Mocha: Text
+ private static final TextColor LIST = TextColor.color(0x74, 0xc7, 0xec); // Shiroha - Catppuccin Mocha: Sapphire
+ // Shiroha start - prettier /tps output
+ private static final TextColor MUTED = TextColor.color(0x6c, 0x70, 0x86); // Catppuccin Mocha: Overlay0
+ private static final int DIVIDER_WIDTH = 44;
+ private static final int BAR_SEGMENTS = 20;
+ private static final String[] RANK_ICONS = {"①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩"};
+ // Shiroha end
public CommandServerHealth() {
super("tps");
- this.setUsage("/<command> [server/region] [lowest regions to display]");
+ this.setUsage("/<command> [server/region] [lowest regions to display|all]"); // Shiroha - document "all" option
this.setDescription("Reports information about server health.");
this.setPermission("bukkit.command.tps");
}
+ // Shiroha start - prettier /tps output helpers
+ private static Component divider() {
+ // strikethrough spaces render as a solid flat line on every client/font, unlike box-drawing glyphs
+ return Component.text(" ".repeat(DIVIDER_WIDTH), MUTED, TextDecoration.STRIKETHROUGH);
+ }
+
+ private static Component sectionHeader(final String title) {
+ return Component.text()
+ .append(Component.text("» ", HEADER, TextDecoration.BOLD))
+ .append(Component.text(title + "\n", HEADER, TextDecoration.BOLD))
+ .build();
+ }
+
+ private static String rankLabel(final int index) {
+ return index < RANK_ICONS.length ? RANK_ICONS[index] : ("#" + (index + 1));
+ }
+
+ private static Component progressBar(final double fraction) {
+ // same strikethrough-space trick as divider() so the bar is a smooth flat two-tone line, not a
+ // row of block glyphs that may render as tiny/misaligned dots depending on the client's font
+ final double clamped = Math.max(0.0, Math.min(1.0, fraction));
+ final int filled = (int) Math.round(clamped * BAR_SEGMENTS);
+ final TextColor barColour = CommandUtil.getUtilisationColourRegion(clamped);
+ return Component.text()
+ .append(Component.text(" ".repeat(filled), barColour, TextDecoration.STRIKETHROUGH))
+ .append(Component.text(" ".repeat(BAR_SEGMENTS - filled), MUTED, TextDecoration.STRIKETHROUGH))
+ .build();
+ }
+ // Shiroha end
+
private static Component formatRegionInfo(final String prefix, final double util, final double mspt, final double tps,
final boolean newline) {
+ // Shiroha start - use progress bar + dot separators instead of plain "util at ... MSPT at ..." text
return Component.text()
- .append(Component.text(prefix, PRIMARY, TextDecoration.BOLD))
- .append(Component.text(ONE_DECIMAL_PLACES.get().format(util * 100.0), CommandUtil.getUtilisationColourRegion(util)))
- .append(Component.text("% util at ", PRIMARY))
- .append(Component.text(TWO_DECIMAL_PLACES.get().format(mspt), CommandUtil.getColourForMSPT(mspt)))
- .append(Component.text(" MSPT at ", PRIMARY))
- .append(Component.text(TWO_DECIMAL_PLACES.get().format(tps), CommandUtil.getColourForTPS(tps)))
- .append(Component.text(" TPS" + (newline ? "\n" : ""), PRIMARY))
- .build();
+ .append(Component.text(prefix, PRIMARY, TextDecoration.BOLD))
+ .append(progressBar(util))
+ .append(Component.text(" "))
+ .append(Component.text(ONE_DECIMAL_PLACES.get().format(util * 100.0) + "%", CommandUtil.getUtilisationColourRegion(util)))
+ .append(Component.text(" · ", MUTED))
+ .append(Component.text(TWO_DECIMAL_PLACES.get().format(mspt) + " ms", CommandUtil.getColourForMSPT(mspt)))
+ .append(Component.text(" · ", MUTED))
+ .append(Component.text(TWO_DECIMAL_PLACES.get().format(tps) + " tps", CommandUtil.getColourForTPS(tps)))
+ .append(Component.text(newline ? "\n" : "", PRIMARY))
+ .build();
+ // Shiroha end
}
private static Component formatRegionStats(final TickRegions.RegionStats stats, final boolean newline) {
+ // Shiroha start - add "·" separators for readability
return Component.text()
- .append(Component.text("Chunks: ", PRIMARY))
- .append(Component.text(NO_DECIMAL_PLACES.get().format((long)stats.getChunkCount()), INFORMATION))
- .append(Component.text(" Players: ", PRIMARY))
- .append(Component.text(NO_DECIMAL_PLACES.get().format((long)stats.getPlayerCount()), INFORMATION))
- .append(Component.text(" Entities: ", PRIMARY))
- .append(Component.text(NO_DECIMAL_PLACES.get().format((long)stats.getEntityCount()) + (newline ? "\n" : ""), INFORMATION))
- .build();
+ .append(Component.text("Chunks: ", PRIMARY))
+ .append(Component.text(NO_DECIMAL_PLACES.get().format((long)stats.getChunkCount()), INFORMATION))
+ .append(Component.text(" · Players: ", PRIMARY))
+ .append(Component.text(NO_DECIMAL_PLACES.get().format((long)stats.getPlayerCount()), INFORMATION))
+ .append(Component.text(" · Entities: ", PRIMARY))
+ .append(Component.text(NO_DECIMAL_PLACES.get().format((long)stats.getEntityCount()) + (newline ? "\n" : ""), INFORMATION))
+ .build();
+ // Shiroha end
}
private static boolean executeRegion(final CommandSender sender, final String commandLabel, final String[] args) {
final ThreadedRegionizer.ThreadedRegion<TickRegions.TickRegionData, TickRegions.TickRegionSectionData> region =
- TickRegionScheduler.getCurrentRegion();
+ TickRegionScheduler.getCurrentRegion();
if (region == null) {
sender.sendMessage(Component.text("You are not in a region currently", NamedTextColor.RED));
return true;
@@ -108,22 +150,24 @@ public final class CommandServerHealth extends Command {
final int yLoc = 80;
final String location = "[w:'" + world.getWorld().getName() + "'," + centerBlockX + "," + yLoc + "," + centerBlockZ + "]";
+ // Shiroha start - prettier /tps region output
final Component line = Component.text()
- .append(Component.text("Region around block ", PRIMARY))
- .append(Component.text(location, INFORMATION))
- .append(Component.text(":\n", PRIMARY))
-
- .append(
- formatRegionInfo("15s: ", util15s, mspt15s, tps15s, true)
- )
- .append(
- formatRegionInfo("1m: ", util1m, mspt1m, tps1m, true)
- )
- .append(
- formatRegionStats(region.getData().getRegionStats(), false)
- )
-
- .build();
+ .append(sectionHeader("Region around " + location))
+ .append(divider())
+ .append(Component.text("\n"))
+
+ .append(
+ formatRegionInfo("15s: ", util15s, mspt15s, tps15s, true)
+ )
+ .append(
+ formatRegionInfo("1m: ", util1m, mspt1m, tps1m, true)
+ )
+ .append(
+ formatRegionStats(region.getData().getRegionStats(), false)
+ )
+
+ .build();
+ // Shiroha end
sender.sendMessage(line);
@@ -131,9 +175,13 @@ public final class CommandServerHealth extends Command {
}
private static boolean executeServer(final CommandSender sender, final String commandLabel, final String[] args) {
+ // Shiroha start - "all" lists every tick region instead of just the top N by utilisation
+ final boolean showAllRegions = args.length >= 2 && args[1].equalsIgnoreCase("all");
final int lowestRegionsCount;
- if (args.length < 2) {
- lowestRegionsCount = 3;
+ if (showAllRegions) {
+ lowestRegionsCount = Integer.MAX_VALUE; // unused when showAllRegions is true, kept for definite assignment
+ } else if (args.length < 2) {
+ lowestRegionsCount = 5; // default to top 5 regions
} else {
try {
lowestRegionsCount = Integer.parseInt(args[1]);
@@ -142,9 +190,10 @@ public final class CommandServerHealth extends Command {
return true;
}
}
+ // Shiroha end
final List<ThreadedRegionizer.ThreadedRegion<TickRegions.TickRegionData, TickRegions.TickRegionSectionData>> regions =
- new ArrayList<>();
+ new ArrayList<>();
for (final World bukkitWorld : Bukkit.getWorlds()) {
final ServerLevel world = ((CraftWorld)bukkitWorld).getHandle();
@@ -174,6 +223,7 @@ public final class CommandServerHealth extends Command {
final double loadRate = ca.spottedleaf.moonrise.patches.chunk_system.scheduling.task.ChunkFullTask.loadRate(currTime);
totalUtil += globalTickReport.utilisation();
+ final double overallFraction = maxThreadCount > 0 ? (totalUtil / maxThreadCount) : 0.0; // Shiroha - overall load fraction for progress bar
tpsByRegion.sort(null);
if (!tpsByRegion.isEmpty()) {
@@ -194,7 +244,7 @@ public final class CommandServerHealth extends Command {
}
final List<ObjectObjectImmutablePair<ThreadedRegionizer.ThreadedRegion<TickRegions.TickRegionData, TickRegions.TickRegionSectionData>, TickData.TickReportData>>
- regionsBelowThreshold = new ArrayList<>();
+ regionsBelowThreshold = new ArrayList<>();
for (int i = 0, len = regions.size(); i < len; ++i) {
final TickData.TickReportData report = reportsByRegion.get(i);
@@ -215,15 +265,15 @@ public final class CommandServerHealth extends Command {
final TextComponent.Builder lowestRegionsBuilder = Component.text();
if (sender instanceof Player) {
- lowestRegionsBuilder.append(Component.text(" Click to teleport\n", SECONDARY));
+ lowestRegionsBuilder.append(Component.text(" Click to teleport\n", SECONDARY, TextDecoration.ITALIC)); // Shiroha - restyle hint text
}
- for (int i = 0, len = Math.min(lowestRegionsCount, regionsBelowThreshold.size()); i < len; ++i) {
+ for (int i = 0, len = showAllRegions ? regionsBelowThreshold.size() : Math.min(lowestRegionsCount, regionsBelowThreshold.size()); i < len; ++i) { // Shiroha - support "all"
final ObjectObjectImmutablePair<ThreadedRegionizer.ThreadedRegion<TickRegions.TickRegionData, TickRegions.TickRegionSectionData>, TickData.TickReportData>
- pair = regionsBelowThreshold.get(i);
+ pair = regionsBelowThreshold.get(i);
final TickData.TickReportData report = pair.right();
final ThreadedRegionizer.ThreadedRegion<TickRegions.TickRegionData, TickRegions.TickRegionSectionData> region =
- pair.left();
+ pair.left();
if (report == null) {
// skip regions with no data
@@ -244,74 +294,76 @@ public final class CommandServerHealth extends Command {
final int yLoc = 80;
final String location = "[w:'" + world.getWorld().getName() + "'," + centerBlockX + "," + yLoc + "," + centerBlockZ + "]";
+ // Shiroha start - prettier /tps region list entries
final Component line = Component.text()
- .append(Component.text(" - ", LIST, TextDecoration.BOLD))
- .append(Component.text("Region around block ", PRIMARY))
- .append(Component.text(location, INFORMATION))
- .append(Component.text(":\n", PRIMARY))
-
- .append(Component.text(" ", PRIMARY))
- .append(Component.text(ONE_DECIMAL_PLACES.get().format(util * 100.0), CommandUtil.getUtilisationColourRegion(util)))
- .append(Component.text("% util at ", PRIMARY))
- .append(Component.text(TWO_DECIMAL_PLACES.get().format(mspt), CommandUtil.getColourForMSPT(mspt)))
- .append(Component.text(" MSPT at ", PRIMARY))
- .append(Component.text(TWO_DECIMAL_PLACES.get().format(tps), CommandUtil.getColourForTPS(tps)))
- .append(Component.text(" TPS\n", PRIMARY))
-
- .append(Component.text(" ", PRIMARY))
- .append(formatRegionStats(region.getData().getRegionStats(), (i + 1) != len))
- .build()
-
- .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, Payload.string("/minecraft:execute as @s in " + world.getWorld().getKey().toString() + " run tp " + centerBlockX + ".5 " + yLoc + " " + centerBlockZ + ".5")))
- .hoverEvent(HoverEvent.hoverEvent(HoverEvent.Action.SHOW_TEXT, Component.text("Click to teleport to " + location, SECONDARY)));
+ .append(Component.text(" " + rankLabel(i) + " ", LIST, TextDecoration.BOLD)) // Shiroha - Catppuccin Mocha: Sapphire rank marker
+ .append(Component.text(location + "\n", INFORMATION))
+
+ .append(Component.text(" "))
+ .append(progressBar(util))
+ .append(Component.text(" "))
+ .append(Component.text(ONE_DECIMAL_PLACES.get().format(util * 100.0) + "%", CommandUtil.getUtilisationColourRegion(util)))
+ .append(Component.text(" · ", MUTED))
+ .append(Component.text(TWO_DECIMAL_PLACES.get().format(mspt) + " ms", CommandUtil.getColourForMSPT(mspt)))
+ .append(Component.text(" · ", MUTED))
+ .append(Component.text(TWO_DECIMAL_PLACES.get().format(tps) + " tps\n", CommandUtil.getColourForTPS(tps)))
+
+ .append(Component.text(" "))
+ .append(formatRegionStats(region.getData().getRegionStats(), (i + 1) != len))
+ .build()
+
+ .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, Payload.string("/minecraft:execute as @s in " + world.getWorld().getKey().toString() + " run tp " + centerBlockX + ".5 " + yLoc + " " + centerBlockZ + ".5")))
+ .hoverEvent(HoverEvent.hoverEvent(HoverEvent.Action.SHOW_TEXT, Component.text("Click to teleport to " + location, SECONDARY)));
+ // Shiroha end
lowestRegionsBuilder.append(line);
}
sender.sendMessage(
- Component.text()
- .append(Component.text("Server Health Report\n", HEADER, TextDecoration.BOLD))
-
- .append(Component.text(" - ", LIST, TextDecoration.BOLD))
- .append(Component.text("Online Players: ", PRIMARY))
- .append(Component.text(Bukkit.getOnlinePlayers().size() + "\n", INFORMATION))
-
- .append(Component.text(" - ", LIST, TextDecoration.BOLD))
- .append(Component.text("Total regions: ", PRIMARY))
- .append(Component.text(regions.size() + "\n", INFORMATION))
-
- .append(Component.text(" - ", LIST, TextDecoration.BOLD))
- .append(Component.text("Utilisation: ", PRIMARY))
- .append(Component.text(ONE_DECIMAL_PLACES.get().format(totalUtil * 100.0), CommandUtil.getUtilisationColourRegion(totalUtil / (double)maxThreadCount)))
- .append(Component.text("% / ", PRIMARY))
- .append(Component.text(ONE_DECIMAL_PLACES.get().format(maxThreadCount * 100.0), INFORMATION))
- .append(Component.text("%\n", PRIMARY))
-
- .append(Component.text(" - ", LIST, TextDecoration.BOLD))
- .append(Component.text("Load rate: ", PRIMARY))
- .append(Component.text(TWO_DECIMAL_PLACES.get().format(loadRate) + ", ", INFORMATION))
- .append(Component.text("Gen rate: ", PRIMARY))
- .append(Component.text(TWO_DECIMAL_PLACES.get().format(genRate) + "\n", INFORMATION))
-
- .append(Component.text(" - ", LIST, TextDecoration.BOLD))
- .append(Component.text("Lowest Region TPS: ", PRIMARY))
- .append(Component.text(TWO_DECIMAL_PLACES.get().format(minTps) + "\n", CommandUtil.getColourForTPS(minTps)))
-
-
- .append(Component.text(" - ", LIST, TextDecoration.BOLD))
- .append(Component.text("Median Region TPS: ", PRIMARY))
- .append(Component.text(TWO_DECIMAL_PLACES.get().format(medianTps) + "\n", CommandUtil.getColourForTPS(medianTps)))
-
- .append(Component.text(" - ", LIST, TextDecoration.BOLD))
- .append(Component.text("Highest Region TPS: ", PRIMARY))
- .append(Component.text(TWO_DECIMAL_PLACES.get().format(maxTps) + "\n", CommandUtil.getColourForTPS(maxTps)))
-
- .append(Component.text("Highest ", HEADER, TextDecoration.BOLD))
- .append(Component.text(Integer.toString(lowestRegionsCount), INFORMATION, TextDecoration.BOLD))
- .append(Component.text(" utilisation regions\n", HEADER, TextDecoration.BOLD))
-
- .append(lowestRegionsBuilder.build())
- .build()
+ // Shiroha start - prettier /tps server output
+ Component.text()
+ .append(sectionHeader("Server Health Report"))
+ .append(divider())
+ .append(Component.text("\n"))
+
+ .append(Component.text(" Summary\n", HEADER, TextDecoration.BOLD))
+ .append(Component.text(" Players ", PRIMARY))
+ .append(Component.text(Bukkit.getOnlinePlayers().size() + " ", INFORMATION))
+ .append(Component.text("Regions ", PRIMARY))
+ .append(Component.text(regions.size() + "\n", INFORMATION))
+
+ .append(Component.text(" Chunk system load\n", HEADER, TextDecoration.BOLD))
+ .append(Component.text(" Load rate ", PRIMARY))
+ .append(Component.text(TWO_DECIMAL_PLACES.get().format(loadRate) + " ", INFORMATION))
+ .append(Component.text("Gen rate ", PRIMARY))
+ .append(Component.text(TWO_DECIMAL_PLACES.get().format(genRate) + "\n", INFORMATION))
+
+ .append(Component.text(" Overall load\n", HEADER, TextDecoration.BOLD))
+ .append(Component.text(" "))
+ .append(progressBar(overallFraction))
+ .append(Component.text(" "))
+ .append(Component.text(ONE_DECIMAL_PLACES.get().format(overallFraction * 100.0) + "%", CommandUtil.getUtilisationColourRegion(overallFraction)))
+ .append(Component.text(" (", MUTED))
+ .append(Component.text(ONE_DECIMAL_PLACES.get().format(totalUtil * 100.0) + "%", INFORMATION))
+ .append(Component.text(" / ", MUTED))
+ .append(Component.text(maxThreadCount + " threads", INFORMATION))
+ .append(Component.text(")\n", MUTED))
+
+ .append(Component.text(" TPS\n", HEADER, TextDecoration.BOLD))
+ .append(Component.text(" min ", PRIMARY))
+ .append(Component.text(TWO_DECIMAL_PLACES.get().format(minTps) + " ", CommandUtil.getColourForTPS(minTps)))
+ .append(Component.text("med ", PRIMARY))
+ .append(Component.text(TWO_DECIMAL_PLACES.get().format(medianTps) + " ", CommandUtil.getColourForTPS(medianTps)))
+ .append(Component.text("max ", PRIMARY))
+ .append(Component.text(TWO_DECIMAL_PLACES.get().format(maxTps) + "\n", CommandUtil.getColourForTPS(maxTps)))
+
+ .append(divider())
+ .append(Component.text("\n"))
+ .append(sectionHeader(showAllRegions ? "All " + regions.size() + " regions by utilisation" : "Top " + lowestRegionsCount + " regions by utilisation")) // Shiroha - "all" heading
+
+ .append(lowestRegionsBuilder.build())
+ .build()
+ // Shiroha end
);
return true;
@@ -0,0 +1,55 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Bacteriawa <A3167717663@hotmail.com>
Date: Tue, 21 Apr 2026 01:41:14 +0800
Subject: [PATCH] Kaiiju: Entity tick and removal limiter
Co-authored by: Xymb <xymb@endcrystal.me>
As part of: Kaiiju (https://github.com/KaiijuMC/Kaiiju/blob/c2b7aec8f7b418a39a2ec408e6411e6f752379da/patches/server/0021-Entity-ticking-throttling-removal-to-prevent-lag.patch)
Licensed under: GPL-3.0 (https://github.com/KaiijuMC/Kaiiju/blob/c2b7aec8f7b418a39a2ec408e6411e6f752379da/LICENSE)
diff --git a/io/papermc/paper/threadedregions/RegionizedWorldData.java b/io/papermc/paper/threadedregions/RegionizedWorldData.java
index cb15cfbc684ae9e9d9634886f707c2df10063139..f32d118e1e925b2155cef3fcdcb1e194c541e242 100644
--- a/io/papermc/paper/threadedregions/RegionizedWorldData.java
+++ b/io/papermc/paper/threadedregions/RegionizedWorldData.java
@@ -354,6 +354,7 @@ public final class RegionizedWorldData {
private final IteratorSafeOrderedReferenceSet<Mob> navigatingMobs = new IteratorSafeOrderedReferenceSet<>();
public final ReferenceList<Entity> trackerEntities = new ReferenceList<>(EMPTY_ENTITY_ARRAY); // Moonrise - entity tracker
public final ReferenceList<Entity> trackerUnloadedEntities = new ReferenceList<>(EMPTY_ENTITY_ARRAY); // Moonrise - entity tracker
+ public final dev.kaiijumc.kaiiju.KaiijuEntityThrottler entityThrottler = new dev.kaiijumc.kaiiju.KaiijuEntityThrottler(); // Kaiiju
// block ticking
private final ObjectLinkedOpenHashSet<BlockEventData> blockEvents = new ObjectLinkedOpenHashSet<>();
diff --git a/net/minecraft/server/level/ServerLevel.java b/net/minecraft/server/level/ServerLevel.java
index 39e511061d11039a1027320de624be07e34a2978..0097c55adf5578f425b476b3498db1c701189e4b 100644
--- a/net/minecraft/server/level/ServerLevel.java
+++ b/net/minecraft/server/level/ServerLevel.java
@@ -910,6 +910,7 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
}
foliaProfiler.startTimer(ca.spottedleaf.leafprofiler.LProfilerRegistry.ACTIVATE_ENTITIES); try { // Folia - profiler
+ if (dev.kaiijumc.kaiiju.KaiijuEntityLimits.enabled) regionizedWorldData.entityThrottler.tickLimiterStart(); // Kaiiju
io.papermc.paper.entity.activation.ActivationRange.activateEntities(this); // Paper - EAR
} finally { foliaProfiler.stopTimer(ca.spottedleaf.leafprofiler.LProfilerRegistry.ACTIVATE_ENTITIES); } // Folia - profiler
foliaProfiler.startTimer(ca.spottedleaf.leafprofiler.LProfilerRegistry.ENTITY_TICK); try { // Folia - profiler
@@ -931,6 +932,13 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
entity.stopRiding();
}
+ // Kaiiju start
+ if (dev.kaiijumc.kaiiju.KaiijuEntityLimits.enabled) {
+ dev.kaiijumc.kaiiju.KaiijuEntityThrottler.EntityThrottlerReturn throttle = regionizedWorldData.entityThrottler.tickLimiterShouldSkip(entity);
+ if (throttle.remove && !entity.hasCustomName()) entity.remove(Entity.RemovalReason.DISCARDED);
+ if (throttle.skip) return;
+ }
+ // Kaiiju end
profiler.push("tick");
this.guardEntityTick(this::tickNonPassenger, entity);
@@ -940,6 +948,7 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
}
}
);
+ if (dev.kaiijumc.kaiiju.KaiijuEntityLimits.enabled) regionizedWorldData.entityThrottler.tickLimiterFinish(regionizedWorldData); // Kaiiju
} finally { foliaProfiler.stopTimer(ca.spottedleaf.leafprofiler.LProfilerRegistry.ENTITY_TICK); } // Folia - profiler
if (this.paperConfig().unsupportedSettings.ticking.blockEntities) { // Paper - option to disable ticking
profiler.popPush("blockEntities");
@@ -0,0 +1,81 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 22:35:59 +0800
Subject: [PATCH] Kaiiju: Vanilla end portal teleportation
Co-authored by: Sofiane H. Djerbi <46628754+kugge@users.noreply.github.com>
As part of: Kaiiju (https://github.com/KaiijuMC/Kaiiju/blob/c2b7aec8f7b418a39a2ec408e6411e6f752379da/patches/server/0024-Vanilla-end-portal-teleportation.patch)
Licensed under: GPL-3.0 (https://github.com/KaiijuMC/Kaiiju/blob/c2b7aec8f7b418a39a2ec408e6411e6f752379da/LICENSE)
diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java
index 5f7dad51fdca3b85f8ae164b1f58241e83ea44d5..5d2f1a90a8e78a95b47c580f6dc4b893dc98f067 100644
--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -4640,14 +4640,18 @@ public abstract class Entity
targetPos, 16, // load 16 blocks to be safe from block physics
ca.spottedleaf.concurrentutil.util.Priority.HIGH,
(chunks) -> {
- net.minecraft.world.level.levelgen.feature.EndPlatformFeature.createEndPlatform(destination, targetPos.below(), true, null);
-
+ //net.minecraft.world.level.levelgen.feature.EndPlatformFeature.createEndPlatform(destination, targetPos.below(), true, null); // Kaiiju - Vanilla end teleportation - moved down
+ // Kaiiju start - Vanilla end teleportation
+ Vec3 finalPos;
+ if (this instanceof Player) finalPos = Vec3.atBottomCenterOf(targetPos.below());
+ else finalPos = Vec3.atBottomCenterOf(targetPos);
+ // Kaiiju end
// the portal obsidian is placed at targetPos.y - 2, so if we want to place the entity
// on the obsidian, we need to spawn at targetPos.y - 1
portalInfoCompletable.complete(
new net.minecraft.world.level.portal.TeleportTransition(
- destination, Vec3.atBottomCenterOf(targetPos.below()), Vec3.ZERO, Direction.WEST.toYRot(), 0.0f,
- Relative.union(Relative.DELTA, Set.of(Relative.X_ROT)),
+ destination, finalPos, this.getDeltaMovement(), Direction.WEST.toYRot(), 0.0f, // Kaiiju - Vanilla end teleportation
+ /*Relative.union(Relative.DELTA, Set.of(Relative.X_ROT))*/Set.of(), // Kaiiju - Vanilla end teleportation
TeleportTransition.PLAY_PORTAL_SOUND.then(TeleportTransition.PLACE_PORTAL_TICKET),
org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.END_PORTAL
)
@@ -4662,11 +4666,15 @@ public abstract class Entity
ca.spottedleaf.concurrentutil.util.Priority.HIGH,
(chunks) -> {
BlockPos adjustedSpawn = destination.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, spawnPos);
-
+ // Kaiiju start - Vanilla end teleportation
+ Vec3 finalPos;
+ if (this instanceof Player) finalPos = Vec3.atBottomCenterOf(adjustedSpawn.below());
+ else finalPos = Vec3.atBottomCenterOf(adjustedSpawn);
+ // Kaiiju end
// done
portalInfoCompletable.complete(
new net.minecraft.world.level.portal.TeleportTransition(
- destination, Vec3.atBottomCenterOf(adjustedSpawn), Vec3.ZERO, 0.0f, 0.0f,
+ destination, finalPos, this.getDeltaMovement(), 0.0f, 0.0f, // Kaiiju - Vanilla end teleportation
Relative.union(Relative.DELTA, Relative.ROTATION),
TeleportTransition.PLAY_PORTAL_SOUND.then(TeleportTransition.PLACE_PORTAL_TICKET),
org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.END_PORTAL
@@ -4845,6 +4853,10 @@ public abstract class Entity
return false;
}
+ // Kaiiju start - sync end platform spawning & entity teleportation
+ final java.util.function.Consumer<Entity> tpComplete = type == PortalType.END && destination.getTypeKey() == net.minecraft.world.level.dimension.LevelStem.END ?
+ e -> {net.minecraft.world.level.levelgen.feature.EndPlatformFeature.createEndPlatform(destination, ServerLevel.END_SPAWN_POINT.below(), true, null); if (teleportComplete != null) {teleportComplete.accept(e);}} : teleportComplete;
+ // Kaiiju end
Vec3 initialPosition = this.position();
ChunkPos initialPositionChunk = new ChunkPos(
ca.spottedleaf.moonrise.common.util.CoordinateUtils.getChunkX(initialPosition),
@@ -4908,9 +4920,14 @@ public abstract class Entity
info.postTeleportTransition().onTransition(teleported);
}
- if (teleportComplete != null) {
+ // Kaiiju start - vanilla end teleportation
+ /*if (teleportComplete != null) {
teleportComplete.accept(teleported);
+ }*/
+ if (tpComplete != null){
+ tpComplete.accept(teleported);
}
+ // Kaiiju end
}
);
});
@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Wed, 8 Jul 2026 21:53:18 +0800
Subject: [PATCH] Add config to support for long command inputs
Some long commands can be run through the dialog command, but paper has prohibited it.
Revert to vanilla to fix it.
diff --git a/net/minecraft/network/protocol/game/ServerboundChatCommandPacket.java b/net/minecraft/network/protocol/game/ServerboundChatCommandPacket.java
index 491af2413a4e793a121fec368259ff8211ed031e..f9076b71f22b016a117a1eeb9cc4b8801db000e7 100644
--- a/net/minecraft/network/protocol/game/ServerboundChatCommandPacket.java
+++ b/net/minecraft/network/protocol/game/ServerboundChatCommandPacket.java
@@ -12,7 +12,7 @@ public record ServerboundChatCommandPacket(String command) implements Packet<Ser
);
private ServerboundChatCommandPacket(final FriendlyByteBuf input) {
- this(input.readUtf(MAX_CHAT_PACKET_INPUT_SIZE)); // Paper - limit chat command inputs
+ this(io.nanachiyo0721.shiroha.config.modules.fixes.LongCommandSupportConfig.enabled ? input.readUtf() : input.readUtf(MAX_CHAT_PACKET_INPUT_SIZE)); // Paper - limit chat command inputs // Shiroha - Add config to support for long command inputs
}
private void write(final FriendlyByteBuf output) {
@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 18 Apr 2026 09:08:52 +0800
Subject: [PATCH] Add config for server mod name
diff --git a/net/minecraft/server/MinecraftServer.java b/net/minecraft/server/MinecraftServer.java
index b01e00de94d8fa45359d3d14a8481287276adb68..cdb1647146f526dc80b15a09d3a936b5dbc54ba3 100644
--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -2060,7 +2060,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
}
public String getServerModName() {
- return io.papermc.paper.ServerBuildInfo.buildInfo().brandName(); // Paper
+ return io.nanachiyo0721.shiroha.config.modules.misc.ServerModNameConfig.fakeVanilla ? "vanilla" : io.nanachiyo0721.shiroha.config.modules.misc.ServerModNameConfig.serverModName; // Paper // Shiroha - Add config for server mod name
}
public ServerClockManager clockManager() {
@@ -0,0 +1,33 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Fri, 17 Apr 2026 22:47:34 +0800
Subject: [PATCH] Add config for cpu affinity
diff --git a/io/papermc/paper/threadedregions/TickRegionScheduler.java b/io/papermc/paper/threadedregions/TickRegionScheduler.java
index 5a72fa0d72bfdb927293abe921c57f6ae964a6ec..913161732b0affa70fb114dd4087a6102b611cba 100644
--- a/io/papermc/paper/threadedregions/TickRegionScheduler.java
+++ b/io/papermc/paper/threadedregions/TickRegionScheduler.java
@@ -66,7 +66,7 @@ public final class TickRegionScheduler {
@Override
public Thread newThread(final Runnable run) {
- final Thread ret = new TickThreadRunner(this.threadGroup, run, "Folia Region Scheduler Thread #" + this.idGenerator.getAndIncrement());
+ final Thread ret = new TickThreadRunner(this.threadGroup, io.nanachiyo0721.shiroha.config.modules.optimizations.CpuAffinityConfig.wrapForTickRegion(run), "Folia Region Scheduler Thread #" + this.idGenerator.getAndIncrement()); // Shiroha - Add config for cpu affinity
ret.setUncaughtExceptionHandler(TickRegionScheduler.this::uncaughtException);
return ret;
}
diff --git a/net/minecraft/server/network/EventLoopGroupHolder.java b/net/minecraft/server/network/EventLoopGroupHolder.java
index 9544eaee7e02d00226d957ea0b79cd1a1fb0c4d0..4e138fe36aa0bc519482990b60543b17ee2f388f 100644
--- a/net/minecraft/server/network/EventLoopGroupHolder.java
+++ b/net/minecraft/server/network/EventLoopGroupHolder.java
@@ -98,7 +98,8 @@ public abstract class EventLoopGroupHolder {
}
private ThreadFactory createThreadFactory() {
- return new ThreadFactoryBuilder().setNameFormat("Netty " + this.type + " IO #%d").setDaemon(true).setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(net.minecraft.server.MinecraftServer.LOGGER)).build(); // Paper
+ var origin = new ThreadFactoryBuilder().setNameFormat("Netty " + this.type + " IO #%d").setDaemon(true).setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(net.minecraft.server.MinecraftServer.LOGGER)).build(); // Paper // Shiroha - Add config for cpu affinity
+ return run -> origin.newThread(io.nanachiyo0721.shiroha.config.modules.optimizations.CpuAffinityConfig.wrapForNettyIo(run)); // Shiroha - Add config for cpu affinity
}
protected abstract IoHandlerFactory ioHandlerFactory();
@@ -0,0 +1,45 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Bacteriawa <A3167717663@hotmail.com>
Date: Tue, 21 Apr 2026 01:47:51 +0800
Subject: [PATCH] Add config for unsafe teleportation
diff --git a/net/minecraft/world/entity/item/FallingBlockEntity.java b/net/minecraft/world/entity/item/FallingBlockEntity.java
index 480b6b2405706fd4d7158d0e160adafd84099887..ca8207f7bf6a71ae283c6c9739563e9dfe1f0f02 100644
--- a/net/minecraft/world/entity/item/FallingBlockEntity.java
+++ b/net/minecraft/world/entity/item/FallingBlockEntity.java
@@ -70,7 +70,7 @@ public class FallingBlockEntity extends Entity {
public int fallDamageMax = 40;
public float fallDamagePerDistance = 0.0F;
public @Nullable CompoundTag blockData;
- public boolean forceTickAfterTeleportToDuplicate;
+ public boolean forceTickAfterTeleportToDuplicate = io.nanachiyo0721.shiroha.config.modules.fixes.UnsafeTeleportationConfig.enabled; // Shiroha - Add config for unsafe teleportation
protected static final EntityDataAccessor<BlockPos> DATA_START_POS = SynchedEntityData.defineId(FallingBlockEntity.class, EntityDataSerializers.BLOCK_POS);
public boolean autoExpire = true; // Paper - Expand FallingBlock API
@@ -384,7 +384,7 @@ public class FallingBlockEntity extends Entity {
ResourceKey<Level> oldDimension = this.level().dimension();
boolean fromOrToEnd = (oldDimension == Level.END || newDimension == Level.END) && oldDimension != newDimension;
Entity newEntity = super.teleport(transition);
- this.forceTickAfterTeleportToDuplicate = newEntity != null && fromOrToEnd && io.papermc.paper.configuration.GlobalConfiguration.get().unsupportedSettings.allowUnsafeEndPortalTeleportation; // Paper
+ this.forceTickAfterTeleportToDuplicate = newEntity != null && fromOrToEnd && (io.papermc.paper.configuration.GlobalConfiguration.get().unsupportedSettings.allowUnsafeEndPortalTeleportation || io.nanachiyo0721.shiroha.config.modules.fixes.UnsafeTeleportationConfig.enabled); // Paper // Shiroha - Add config for unsafe teleportation
return newEntity;
}
}
diff --git a/net/minecraft/world/level/block/EndPortalBlock.java b/net/minecraft/world/level/block/EndPortalBlock.java
index d42bb2a1721e4ab8c9956e18c3ca418b8d648c59..1bb9e32fd0f112deeec936976da0899dae301e56 100644
--- a/net/minecraft/world/level/block/EndPortalBlock.java
+++ b/net/minecraft/world/level/block/EndPortalBlock.java
@@ -76,6 +76,12 @@ public class EndPortalBlock extends BaseEntityBlock implements Portal {
if (level.paperConfig().misc.disableEndCredits) {player.seenCredits = true; return;} // Paper - Option to disable end credits
player.showEndCredits();
} else {
+ // Shiroha start - Add config for unsafe teleportation
+ if (io.nanachiyo0721.shiroha.config.modules.fixes.UnsafeTeleportationConfig.enabled && !(entity instanceof net.minecraft.world.entity.player.Player)) {
+ entity.endPortalLogicAsync(pos);
+ return;
+ }
+ // Shiroha end
entity.setAsInsidePortal(this, pos);
}
}
@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 18 Apr 2026 09:12:26 +0800
Subject: [PATCH] Add config for watchdog timeout
diff --git a/io/papermc/paper/threadedregions/FoliaWatchdogThread.java b/io/papermc/paper/threadedregions/FoliaWatchdogThread.java
index e9ca1a15049b0211d10401cb78e953b93afaf6c7..56c0cac6e6e4c86a1db3c27a2c850d65b5b58c55 100644
--- a/io/papermc/paper/threadedregions/FoliaWatchdogThread.java
+++ b/io/papermc/paper/threadedregions/FoliaWatchdogThread.java
@@ -65,7 +65,7 @@ public final class FoliaWatchdogThread extends Thread {
for (final RunningTick tick : ticks) {
final long elapsed = now - tick.lastPrint;
- if (elapsed <= TimeUnit.SECONDS.toNanos(5L)) {
+ if (elapsed <= TimeUnit.MILLISECONDS.toNanos(io.nanachiyo0721.shiroha.config.modules.misc.FoliaWatchogConfig.tickRegionTimeOutMs)) { // Shiroha - Add config for watchdog timeout
continue;
}
tick.lastPrint = now;
@@ -0,0 +1,18 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Sun, 28 Jun 2026 20:10:51 +0800
Subject: [PATCH] Add config to disable entity tick catchers
diff --git a/net/minecraft/world/level/Level.java b/net/minecraft/world/level/Level.java
index 52bcb87e96f7b5997559bd532481f548be03e6da..41b84a84a2ae24555a065d0779957b7b71611523 100644
--- a/net/minecraft/world/level/Level.java
+++ b/net/minecraft/world/level/Level.java
@@ -1591,6 +1591,7 @@ public abstract class Level implements LevelAccessor, AutoCloseable, ca.spottedl
));
// Shiroha end
} catch (Throwable t) {
+ if (io.nanachiyo0721.shiroha.config.modules.experiment.DisableEntityCatchConfig.enabled) throw t; // Shiroha - Add config to disable entity tick catchers
// Paper start - Prevent block entity and entity crashes
final String msg = String.format("Entity threw exception at %s:%s,%s,%s", io.papermc.paper.util.MCUtil.getLevelName(entity.level()), entity.getX(), entity.getY(), entity.getZ());
MinecraftServer.LOGGER.error(msg, t);
@@ -0,0 +1,18 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 23:34:17 +0800
Subject: [PATCH] Add config for heightmap warning
diff --git a/net/minecraft/world/level/levelgen/Heightmap.java b/net/minecraft/world/level/levelgen/Heightmap.java
index dffa0d4859ecd7e21a9345f946083c56205145a3..8f2e4fa566cefc2089fb6f306a37939f647ebeb2 100644
--- a/net/minecraft/world/level/levelgen/Heightmap.java
+++ b/net/minecraft/world/level/levelgen/Heightmap.java
@@ -128,6 +128,7 @@ public class Heightmap {
if (rawData.length == data.length) {
System.arraycopy(data, 0, rawData, 0, data.length);
} else {
+ if (!io.nanachiyo0721.shiroha.config.modules.misc.DisableWarningConfig.disableHeightmapWarning) // Shiroha - Add config for heightmap warning
LOGGER.warn("Ignoring heightmap data for chunk {}, size does not match; expected: {}, got: {}", chunk.getPos(), rawData.length, data.length);
primeHeightmaps(chunk, EnumSet.of(type));
}
@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 23:35:08 +0800
Subject: [PATCH] Add config gui support
diff --git a/net/minecraft/server/dialog/action/ParsedTemplate.java b/net/minecraft/server/dialog/action/ParsedTemplate.java
index 8a720ef5cd10bf04e97fb34c1ca0f0b265e98468..cbe7ebb8f3b3de6cdb0893c24b52c7cf036402a3 100644
--- a/net/minecraft/server/dialog/action/ParsedTemplate.java
+++ b/net/minecraft/server/dialog/action/ParsedTemplate.java
@@ -13,7 +13,7 @@ public class ParsedTemplate {
private final String raw;
private final StringTemplate parsed;
- private ParsedTemplate(final String raw, final StringTemplate parsed) {
+ public ParsedTemplate(final String raw, final StringTemplate parsed) { // Shiroha - Add config gui support - make public
this.raw = raw;
this.parsed = parsed;
}
@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 23:37:00 +0800
Subject: [PATCH] Add force the data command to be enabled config
diff --git a/net/minecraft/commands/Commands.java b/net/minecraft/commands/Commands.java
index bc9f6cc286536b87513de81855ad0b61cf787c84..6b91eab354d8e7c93bf148bfc1f5a611f8ffcf86 100644
--- a/net/minecraft/commands/Commands.java
+++ b/net/minecraft/commands/Commands.java
@@ -202,7 +202,9 @@ public class Commands {
ClearInventoryCommands.register(this.dispatcher, context);
//CloneCommands.register(this.dispatcher, context); // Folia - region threading - TODO
DamageCommand.register(this.dispatcher, context);
- //DataCommands.register(this.dispatcher); // Folia - region threading - TODO
+ if(io.nanachiyo0721.shiroha.config.modules.experiment.CommandConfig.data) { // Shiroha - Add force the data command to be enabled config
+ DataCommands.register(this.dispatcher); // Folia - region threading - TODO // Shiroha - Add force the data command to be enabled config
+ } // Shiroha - Add force the data command to be enabled config
//DataPackCommand.register(this.dispatcher, context); // Folia - region threading - TODO
//DebugCommand.register(this.dispatcher); // Folia - region threading - TODO
DefaultGameModeCommands.register(this.dispatcher);
@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Wed, 8 Jul 2026 23:39:10 +0800
Subject: [PATCH] Add experimental config for command block command execution
diff --git a/net/minecraft/world/level/BaseCommandBlock.java b/net/minecraft/world/level/BaseCommandBlock.java
index 31f1583f29eebe5e13b5a7ac5116fdafc3592e5c..bc567e04791128cc0b78a234c496cf99d2dd5682 100644
--- a/net/minecraft/world/level/BaseCommandBlock.java
+++ b/net/minecraft/world/level/BaseCommandBlock.java
@@ -91,7 +91,7 @@ public abstract class BaseCommandBlock {
}
public boolean performCommand(final ServerLevel level) {
- if (true) return false; // Folia - region threading
+ if (!io.nanachiyo0721.shiroha.config.modules.experiment.CommandConfig.commandBlock) return false; // Folia - region threading // Shiroha - Add experimental config for command block command execution
if (level.getGameTime() == this.lastExecution) {
return false;
}
@@ -0,0 +1,116 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Thu, 9 Jul 2026 10:05:46 +0800
Subject: [PATCH] Add config to modify tripwire behavior
diff --git a/net/minecraft/world/level/block/TripWireHookBlock.java b/net/minecraft/world/level/block/TripWireHookBlock.java
index 8bcc8b6f83ab4d5a472741185511b5d84f4974be..7e78e67c32f5b577518fe735eaba4ce2fba8023f 100644
--- a/net/minecraft/world/level/block/TripWireHookBlock.java
+++ b/net/minecraft/world/level/block/TripWireHookBlock.java
@@ -201,10 +201,17 @@ public class TripWireHookBlock extends Block {
BlockPos testPos = pos.relative(direction, i);
BlockState wireData = wireStates[i];
if (wireData != null) {
- BlockState testPosState = level.getBlockState(testPos);
- if (testPosState.is(Blocks.TRIPWIRE) || testPosState.is(Blocks.TRIPWIRE_HOOK)) {
- if (!io.papermc.paper.configuration.GlobalConfiguration.get().blockUpdates.disableTripwireUpdates || !testPosState.is(Blocks.TRIPWIRE)) level.setBlock(testPos, wireData.trySetValue(ATTACHED, attached), Block.UPDATE_ALL); // Paper - prevent tripwire from updating
+ // Shiroha start - tripwire and tripwireHook dupe
+ if (io.nanachiyo0721.shiroha.config.modules.function.TripwireBehaviorConfig.enabled) {
+ level.setBlock(testPos, wireData.trySetValue(ATTACHED, attached), 3);
+ level.getBlockState(testPos);
+ } else {
+ BlockState testPosState = level.getBlockState(testPos);
+ if (testPosState.is(Blocks.TRIPWIRE) || testPosState.is(Blocks.TRIPWIRE_HOOK)) {
+ if (!io.papermc.paper.configuration.GlobalConfiguration.get().blockUpdates.disableTripwireUpdates || !testPosState.is(Blocks.TRIPWIRE)) level.setBlock(testPos, wireData.trySetValue(ATTACHED, attached), Block.UPDATE_ALL); // Paper - prevent tripwire from updating
+ }
}
+ // Shiroha end - tripwire and tripwireHook dupe
}
}
}
diff --git a/net/minecraft/world/level/levelgen/feature/EndPlatformFeature.java b/net/minecraft/world/level/levelgen/feature/EndPlatformFeature.java
index b67f5f7b76037ab77548c37a83e4d0918915223a..4407333785e8e76d08bb8b18510e6db95c954e36 100644
--- a/net/minecraft/world/level/levelgen/feature/EndPlatformFeature.java
+++ b/net/minecraft/world/level/levelgen/feature/EndPlatformFeature.java
@@ -28,15 +28,41 @@ public class EndPlatformFeature extends Feature<NoneFeatureConfiguration> {
// CraftBukkit end
BlockPos.MutableBlockPos pos = origin.mutable();
- for (int dz = -2; dz <= 2; dz++) {
+ // Shiroha start - tripwire behavior modifier
+ java.util.List<BlockPos> blockList1 = new java.util.ArrayList<>();
+ java.util.List<BlockPos> blockList2 = new java.util.ArrayList<>();
+ boolean flag21 = io.nanachiyo0721.shiroha.config.modules.function.TripwireBehaviorConfig.behaviorMode == io.nanachiyo0721.shiroha.enums.EnumTripwireBehavior.VANILLA21; for (int dz = -2; dz <= 2; dz++) {
for (int dx = -2; dx <= 2; dx++) {
for (int dy = -1; dy < 3; dy++) {
BlockPos blockPos = pos.set(origin).move(dx, dy, dz);
Block block = dy == -1 ? Blocks.OBSIDIAN : Blocks.AIR;
if (!blockList.getBlockState(blockPos).is(block)) { // CraftBukkit
if (dropResources) {
- blockList.destroyBlock(blockPos, true, null); // CraftBukkit
+ boolean flag = false;
+ if (io.nanachiyo0721.shiroha.config.modules.function.TripwireBehaviorConfig.enabled) {
+ switch (io.nanachiyo0721.shiroha.config.modules.function.TripwireBehaviorConfig.behaviorMode) {
+ case io.nanachiyo0721.shiroha.enums.EnumTripwireBehavior.VANILLA20: {
+ flag = true;
+ }
+ case io.nanachiyo0721.shiroha.enums.EnumTripwireBehavior.MIXED: {
+ net.minecraft.world.level.block.state.BlockState state = newLevel.getBlockState(blockPos);
+ if (state.is(Blocks.TRIPWIRE)) {
+ if (state.getValue(net.minecraft.world.level.block.TripWireBlock.DISARMED)) {
+ flag = true;
+ blockList2.add(blockPos.immutable());
+ }
+ if (!flag) {
+ flag = checkString(blockList2, blockPos);
+ }
+ }
+ }
+ default: {} // 1.21 & default Logic - default empty
+ }
+ }
+ if (flag) blockList1.add(blockPos.immutable());
+ else blockList.destroyBlock(blockPos, true, null); // CraftBukkit
}
+ // Shiroha end - prevent tripwire dupe in end platform generate
blockList.setBlock(blockPos, block.defaultBlockState(), Block.UPDATE_ALL); // CraftBukkit
}
@@ -53,11 +79,34 @@ public class EndPlatformFeature extends Feature<NoneFeatureConfiguration> {
if (portalEvent.isCancelled()) return;
}
- if (dropResources) {
- blockList.placeBlocks(state -> newLevel.destroyBlock(state.getPosition(), true, null));
+ // Shiroha start - prevent tripwire dupe in end platform generate
+ if (flag21 || !io.nanachiyo0721.shiroha.config.modules.function.TripwireBehaviorConfig.enabled) {
+ if (dropResources) {
+ blockList.placeBlocks(state -> newLevel.destroyBlock(state.getPosition(), true, null));
+ } else {
+ blockList.placeBlocks();
+ }
+ // Shiroha end - prevent tripwire dupe in end platform generate
} else {
+ // Shiroha start - prevent tripwire dupe in end platform generate
+ if (dropResources) {
+ blockList.getSnapshotBlocks().forEach((state) -> {
+ newLevel.destroyBlock(state.getPosition(), !blockList1.contains(state.getPosition()), null);
+ });
+ }
+ // Shiroha end - prevent tripwire dupe in end platform generate
blockList.placeBlocks();
}
// CraftBukkit end
}
+
+ // Shiroha start - tripwire behavior modifier
+ private static boolean checkString(java.util.List<BlockPos> blockList, BlockPos blockPos) {
+ for (BlockPos pos : blockList) {
+ if (pos.getY() != blockPos.getY()) continue;
+ if (pos.getX() == blockPos.getX() || pos.getZ() == blockPos.getZ()) return true;
+ }
+ return false;
+ }
+ // Shiroha end - tripwire behavior modifier
}
@@ -0,0 +1,39 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Libalpm64 <levamara@proton.me>
Date: Thu, 9 Jul 2026 10:08:30 +0800
Subject: [PATCH] Add config for item multitask
Allows players to use items while moving or switching hotbar slots. This
is for Anarchy servers or Crystal PVP servers this allows them to pvp
without stopping the item mid animation.
diff --git a/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/net/minecraft/server/network/ServerGamePacketListenerImpl.java
index 4c9ea818be83ed3c4dacc762f4d0e8c0f177cd19..9fe5ee1c5578be6f6c5ad9a58e10669a4b7ac75a 100644
--- a/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerGamePacketListenerImpl.java
@@ -2169,7 +2169,9 @@ public class ServerGamePacketListenerImpl
this.player.sendSpawnProtectionMessage(pos);
} else if (this.awaitingPositionFromClient == null && (level.mayInteract(this.player, pos) || passthroughSignInteraction)) {
// Paper end - Allow using signs inside spawn protection
+ if (!io.nanachiyo0721.shiroha.config.modules.fixes.ItemMultitaskConfig.enabled) { // Shiroha - Add config for item multitask
this.player.stopUsingItem(); // CraftBukkit - SPIGOT-4706
+ } // Shiroha - Add config for item multitask
InteractionResult interactionResult = this.player.gameMode.useItemOn(this.player, level, itemStack, hand, blockHit);
if (interactionResult.consumesAction()) {
CriteriaTriggers.ANY_BLOCK_USE.trigger(this.player, blockHit.getBlockPos(), itemStack);
@@ -2368,9 +2370,13 @@ public class ServerGamePacketListenerImpl
return;
}
// CraftBukkit end
- if (this.player.getInventory().getSelectedSlot() != packet.getSlot() && this.player.getUsedItemHand() == InteractionHand.MAIN_HAND) {
- this.player.stopUsingItem();
+ // Shiroha start - Add item multitask config
+ if (!io.nanachiyo0721.shiroha.config.modules.fixes.ItemMultitaskConfig.enabled) {
+ if (this.player.getInventory().getSelectedSlot() != packet.getSlot() && this.player.getUsedItemHand() == InteractionHand.MAIN_HAND) {
+ this.player.stopUsingItem();
+ }
}
+ // Shiroha end
this.player.getInventory().setSelectedSlot(packet.getSlot());
this.player.resetLastActionTime();
@@ -0,0 +1,104 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Thu, 9 Jul 2026 10:11:39 +0800
Subject: [PATCH] Add config to enable tick command
only freeze/unfreeze/step/query can run when enabled
diff --git a/io/papermc/paper/threadedregions/RegionizedServer.java b/io/papermc/paper/threadedregions/RegionizedServer.java
index aa575f3b76ef70ffb9f0410e7e5cfe7af384bfbd..a00b086962b68d6f86cfb55eee6f61afdb162d5f 100644
--- a/io/papermc/paper/threadedregions/RegionizedServer.java
+++ b/io/papermc/paper/threadedregions/RegionizedServer.java
@@ -233,6 +233,11 @@ public final class RegionizedServer {
private void globalTick(final long tickCount) {
++this.tickCount;
+ // Shiroha start - Add a config to enable tick command
+ if (io.nanachiyo0721.shiroha.config.modules.experiment.CommandConfig.tick) {
+ MinecraftServer.getServer().tickRateManager().tick();
+ }
+ // Shiroha end - Add a config to enable tick command
// expire invalid click command callbacks
io.papermc.paper.adventure.providers.ClickCallbackProviderImpl.ADVENTURE_CLICK_MANAGER.handleQueue((int)this.tickCount); // Paper // Folia - region threading - moved to global tick
io.papermc.paper.adventure.providers.ClickCallbackProviderImpl.DIALOG_CLICK_MANAGER.handleQueue((int)this.tickCount); // Paper // Folia - region threading - moved to global tick
@@ -409,7 +414,7 @@ public final class RegionizedServer {
}
private void tickTime(final ServerLevel world, final long tickCount) {
- if (world.tickTime) {
+ if ((!io.nanachiyo0721.shiroha.config.modules.experiment.CommandConfig.tick || world.tickRateManager().runsNormally()) && world.tickTime) { // Shiroha - Add a config to enable tick command
world.serverLevelData.setGameTime(world.serverLevelData.getGameTime() + tickCount);
}
}
diff --git a/io/papermc/paper/threadedregions/TickRegionScheduler.java b/io/papermc/paper/threadedregions/TickRegionScheduler.java
index 913161732b0affa70fb114dd4087a6102b611cba..ccd86db7b384d99d290869a155792b49385dc9a6 100644
--- a/io/papermc/paper/threadedregions/TickRegionScheduler.java
+++ b/io/papermc/paper/threadedregions/TickRegionScheduler.java
@@ -479,6 +479,11 @@ public final class TickRegionScheduler {
try {
// next start isn't updated until the end of this tick
this.tickRegion(tickCount, tickStart, scheduledEnd);
+ // Shiroha start - Add a config to enable tick command
+ if (io.nanachiyo0721.shiroha.config.modules.experiment.CommandConfig.tick) {
+ MinecraftServer.getServer().tickRateManager().endTickWork();
+ }
+ // Shiroha end - Add a config to enable tick command
} catch (final Throwable thr) {
this.scheduler.regionFailed(this, false, thr);
// regionFailed will schedule a shutdown, so we should avoid letting this region tick further
diff --git a/net/minecraft/commands/Commands.java b/net/minecraft/commands/Commands.java
index 6b91eab354d8e7c93bf148bfc1f5a611f8ffcf86..d971cc9669aca1005c026133e7e7e7f9b170ed0d 100644
--- a/net/minecraft/commands/Commands.java
+++ b/net/minecraft/commands/Commands.java
@@ -259,7 +259,11 @@ public class Commands {
TeleportCommand.register(this.dispatcher);
TellRawCommand.register(this.dispatcher, context);
//TestCommand.register(this.dispatcher, context); // Folia - region threading
- //TickCommand.register(this.dispatcher); // Folia - region threading - TODO later
+ // Shiroha start - Add a config to enable tick command
+ if (io.nanachiyo0721.shiroha.config.modules.experiment.CommandConfig.tick) {
+ TickCommand.register(this.dispatcher); // Folia - region threading - TODO later
+ }
+ // Shiroha end - Add a config to enable tick command
TimeCommand.register(this.dispatcher, context);
TitleCommand.register(this.dispatcher, context);
//TriggerCommand.register(this.dispatcher); // Folia - region threading - TODO later
diff --git a/net/minecraft/server/commands/TickCommand.java b/net/minecraft/server/commands/TickCommand.java
index e8d6a67143f3f0b4813e51bb273498bc404899b9..12ff74e46d39d3bf6f025cc59a27ba8925724d80 100644
--- a/net/minecraft/server/commands/TickCommand.java
+++ b/net/minecraft/server/commands/TickCommand.java
@@ -23,14 +23,14 @@ public class TickCommand {
Commands.literal("tick")
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
.then(Commands.literal("query").executes(c -> tickQuery(c.getSource())))
- .then(
+/* .then( // Shiroha - Add config to enable tick command - limit unsupported functions
Commands.literal("rate")
.then(
Commands.argument("rate", FloatArgumentType.floatArg(1.0F, 10000.0F))
.suggests((c, b) -> SharedSuggestionProvider.suggest(new String[]{DEFAULT_TICKRATE}, b))
.executes(c -> setTickingRate(c.getSource(), FloatArgumentType.getFloat(c, "rate")))
)
- )
+ )*/ // Shiroha - Add config to enable tick command - limit unsupported functions
.then(
Commands.literal("step")
.executes(c -> step(c.getSource(), 1))
@@ -41,7 +41,7 @@ public class TickCommand {
.executes(c -> step(c.getSource(), IntegerArgumentType.getInteger(c, "time")))
)
)
- .then(
+/* .then( // Shiroha - Add config to enable tick command - limit unsupported functions
Commands.literal("sprint")
.then(Commands.literal("stop").executes(c -> stopSprinting(c.getSource())))
.then(
@@ -49,7 +49,7 @@ public class TickCommand {
.suggests((c, b) -> SharedSuggestionProvider.suggest(new String[]{"60s", "1d", "3d"}, b))
.executes(c -> sprint(c.getSource(), IntegerArgumentType.getInteger(c, "time")))
)
- )
+ )*/ // Shiroha - Add config to enable tick command - limit unsupported functions
.then(Commands.literal("unfreeze").executes(c -> setFreeze(c.getSource(), false)))
.then(Commands.literal("freeze").executes(c -> setFreeze(c.getSource(), true)))
);
@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 9 Jul 2026 14:34:05 +0800
Subject: [PATCH] Add config for whether to save portal tickets
diff --git a/net/minecraft/server/level/TicketType.java b/net/minecraft/server/level/TicketType.java
index 7e612e03087d63f9b500f7e9f3442b1931bae7ee..9d46c1bc0629faca4ca9e0a2f830912b36148c11 100644
--- a/net/minecraft/server/level/TicketType.java
+++ b/net/minecraft/server/level/TicketType.java
@@ -60,7 +60,7 @@ public final class TicketType<T> implements ca.spottedleaf.moonrise.patches.chun
public static final TicketType PLAYER_LOADING = register("player_loading", NO_TIMEOUT, FLAG_LOADING);
public static final TicketType PLAYER_SIMULATION = register("player_simulation", NO_TIMEOUT, FLAG_SIMULATION | FLAG_KEEP_DIMENSION_ACTIVE);
public static final TicketType FORCED = register("forced", NO_TIMEOUT, FLAG_PERSIST | FLAG_LOADING | FLAG_SIMULATION | FLAG_KEEP_DIMENSION_ACTIVE);
- public static final TicketType PORTAL = register("portal", 300L, FLAG_PERSIST | FLAG_LOADING | FLAG_SIMULATION | FLAG_KEEP_DIMENSION_ACTIVE);
+ public static final TicketType PORTAL = register("portal", 300L, io.nanachiyo0721.shiroha.config.modules.misc.SavePortalTicketsConfig.doSave ? FLAG_PERSIST | FLAG_LOADING | FLAG_SIMULATION | FLAG_KEEP_DIMENSION_ACTIVE : FLAG_LOADING | FLAG_SIMULATION | FLAG_KEEP_DIMENSION_ACTIVE); // Shiroha - Add config for whether to save portal tickets
public static final TicketType ENDER_PEARL = register("ender_pearl", 40L, FLAG_LOADING | FLAG_SIMULATION | FLAG_KEEP_DIMENSION_ACTIVE);
public static final TicketType UNKNOWN = register("unknown", 1L, FLAG_CAN_EXPIRE_IF_UNLOADED | FLAG_LOADING);
public static final TicketType PLUGIN = register("plugin", NO_TIMEOUT, FLAG_LOADING | FLAG_SIMULATION); // CraftBukkit
@@ -0,0 +1,130 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 9 Jul 2026 10:17:22 +0800
Subject: [PATCH] Add portal rate limiter
diff --git a/io/papermc/paper/threadedregions/RegionizedWorldData.java b/io/papermc/paper/threadedregions/RegionizedWorldData.java
index f32d118e1e925b2155cef3fcdcb1e194c541e242..fe17157c4c6fc9ec745c5c11f6837e715d7949ab 100644
--- a/io/papermc/paper/threadedregions/RegionizedWorldData.java
+++ b/io/papermc/paper/threadedregions/RegionizedWorldData.java
@@ -157,6 +157,10 @@ public final class RegionizedWorldData {
for (final ChunkHolder chunkHolder : from.chunkHoldersToBroadcast) {
into.chunkHoldersToBroadcast.add(chunkHolder);
}
+ // Shiroha start - Add portal rate limiter
+ into.portalRateThrottler.mergeWith(from.portalRateThrottler);
+ from.portalRateThrottler.destroy();
+ // Shiroha end
}
@Override
@@ -322,6 +326,12 @@ public final class RegionizedWorldData {
into.chunkHoldersToBroadcast.add(chunkHolder);
}
}
+ // Shiroha start - Add portal rate limiter
+ for (var worldData : dataSet) {
+ from.portalRateThrottler.splitInto(worldData.portalRateThrottler);
+ }
+ from.portalRateThrottler.destroy();
+ // Shiroha end
}
};
@@ -343,6 +353,35 @@ public final class RegionizedWorldData {
return this.isHandlingTick;
}
+ // Shiroha start - Add portal rate limiter
+ public final io.nanachiyo0721.shiroha.utils.RateThrottler portalRateThrottler = new io.nanachiyo0721.shiroha.utils.RateThrottler();
+ public final net.objecthunter.exp4j.Expression portalRateCapExpression = io.nanachiyo0721.shiroha.config.modules.function.PortalRateLimiterConfig.getExpressionIfConfigured();
+
+ private int computePortalRateCap() {
+ // expression mode is disabled
+ if (this.portalRateCapExpression == null) {
+ return io.nanachiyo0721.shiroha.config.modules.function.PortalRateLimiterConfig.maxPortalTeleportsPerTick;
+ }
+
+ final int tickingEntityCount = this.entityTickList.size();
+ final int tickingChunkCount = this.tickingChunks.size();
+ final int playerCount = this.localPlayers.size();
+
+ return io.nanachiyo0721.shiroha.config.modules.function.PortalRateLimiterConfig.computeExpression(
+ this.portalRateCapExpression,
+ tickingEntityCount,
+ tickingChunkCount,
+ playerCount
+ );
+ }
+ public boolean isPortalTeleportationOutOfRate() {
+ if (!io.nanachiyo0721.shiroha.config.modules.function.PortalRateLimiterConfig.enabled) {
+ return false;
+ }
+
+ return this.portalRateThrottler.isOutOfRate(this.computePortalRateCap());
+ }
+ // Shiroha end
// entities
// this is copy on write to allow packet processing to iterate safely
private final CopyOnWriteArrayList<ServerPlayer> localPlayers = new CopyOnWriteArrayList<>();
diff --git a/net/minecraft/server/MinecraftServer.java b/net/minecraft/server/MinecraftServer.java
index cdb1647146f526dc80b15a09d3a936b5dbc54ba3..4ce5bdd16b04f76c2e98a5465343a82ed5f28ab7 100644
--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -1922,6 +1922,9 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
//net.minecraft.world.level.block.entity.HopperBlockEntity.skipHopperEvents = level.paperConfig().hopper.disableMoveEvent || org.bukkit.event.inventory.InventoryMoveItemEvent.getHandlerList().getRegisteredListeners().length == 0; // Paper - Perf: Optimize Hoppers // Folia - region threading
profiler.push(() -> level + " " + level.dimension().identifier());
profiler.push("tick");
+ // Shiroha start - Add portal rate limiter
+ regionizedWorldData.portalRateThrottler.begin();
+ // Shiroha end
try {
foliaProfiler.startTimer(level.tickTimerId); try { // Folia - profiler
@@ -1936,6 +1939,9 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
profiler.pop();
profiler.pop();
regionizedWorldData.explosionDensityCache.clear(); // Paper - Optimize explosions // Folia - region threading
+ // Shiroha start - Add portal rate limiter
+ regionizedWorldData.portalRateThrottler.done();
+ // Shiroha end
}
//this.isIteratingOverLevels = false; // Paper - Throw exception on world create while being ticked // Folia - region threading
diff --git a/net/minecraft/server/level/ServerLevel.java b/net/minecraft/server/level/ServerLevel.java
index 0097c55adf5578f425b476b3498db1c701189e4b..1a0e5fbc823c328d16f48f2df4507bf240915c79 100644
--- a/net/minecraft/server/level/ServerLevel.java
+++ b/net/minecraft/server/level/ServerLevel.java
@@ -1535,8 +1535,15 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
// removed from region while ticking
return;
}
+ // Shiroha start - Add portal rate limiter
+ var worldData = entity.level().getCurrentWorldData();
+ if (entity.portalProcess != null && worldData.isPortalTeleportationOutOfRate()) {
+ return;
+ }
+ // Shiroha end
if (entity.handlePortal()) {
// portalled
+ worldData.portalRateThrottler.increase(); // Shiroha - Add portal rate limiter
return;
}
}
@@ -1580,8 +1587,15 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
// removed from region while ticking
return;
}
+ // Shiroha start - Add portal rate limiter
+ var worldData = entity.level().getCurrentWorldData();
+ if (entity.portalProcess != null && worldData.isPortalTeleportationOutOfRate()) {
+ return;
+ }
+ // Shiroha end
if (entity.handlePortal()) {
// portalled
+ worldData.portalRateThrottler.increase(); // Shiroha - Add portal rate limiter
return;
}
// Folia end - region threading
@@ -0,0 +1,348 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 9 Jul 2026 12:10:04 +0800
Subject: [PATCH] Add status bar
diff --git a/ca/spottedleaf/moonrise/paper/util/BaseChunkSystemHooks.java b/ca/spottedleaf/moonrise/paper/util/BaseChunkSystemHooks.java
index 52dcbcf64c3a510d4a4524b7d0ee226d9a73511d..051d601e7e809518e8d82ae4ae3259054d704f51 100644
--- a/ca/spottedleaf/moonrise/paper/util/BaseChunkSystemHooks.java
+++ b/ca/spottedleaf/moonrise/paper/util/BaseChunkSystemHooks.java
@@ -122,6 +122,7 @@ public abstract class BaseChunkSystemHooks implements ca.spottedleaf.moonrise.co
@Override
public void onChunkNotTicking(final LevelChunk chunk, final ChunkHolder holder) {
+ chunk.getChunkHot().clear(); // KioCG
chunk.getLevel().getCurrentWorldData().removeTickingChunk(chunk); // Folia - region threading
}
diff --git a/net/minecraft/server/MinecraftServer.java b/net/minecraft/server/MinecraftServer.java
index 4ce5bdd16b04f76c2e98a5465343a82ed5f28ab7..ab8d69fa54203175760d394a5425601073fcd0d9 100644
--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -1731,7 +1731,46 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
// Folia end - region threading
//this.tickCount++; // Folia - region threading
//this.tickRateManager.tick(); // Folia - region threading
+ // KioCG start - ChunkHot
+ final ca.spottedleaf.moonrise.common.list.IteratorSafeOrderedReferenceSet<net.minecraft.world.level.chunk.LevelChunk> chunks = new ca.spottedleaf.moonrise.common.list.IteratorSafeOrderedReferenceSet<>();
+ if (region != null){
+ for (net.minecraft.world.level.chunk.LevelChunk chunk : region.world.getCurrentWorldData().getTickingChunks()) {
+ /* wait for rewrite - temporarily crash fix
+ for (net.minecraft.server.level.ServerChunkCache.ChunkAndHolder chunkAndHolder : region.world.getCurrentWorldData().getTickingChunks()){
+ final net.minecraft.world.level.chunk.LevelChunk chunk = chunkAndHolder.chunk();
+ */
+ if (!ca.spottedleaf.moonrise.common.util.TickThread.isTickThreadFor(region.world, chunk.locX, chunk.locZ)){
+ continue;
+ }
+
+ chunks.add(chunk);
+ }
+ }
+ if (region != null && io.papermc.paper.threadedregions.RegionizedServer.getCurrentTick() % 20 == 0){
+ final java.util.Iterator<net.minecraft.world.level.chunk.LevelChunk> chunkIterator = chunks.unsafeIterator();
+ while (chunkIterator.hasNext()){
+ final net.minecraft.world.level.chunk.LevelChunk targetChunk = chunkIterator.next();
+
+ targetChunk.getChunkHot().nextTick();
+ targetChunk.getChunkHot().start();
+ }
+ }
+ //KioCG end
this.tickChildren(haveTime, region); // Folia - region threading
+ // KioCG start - ChunkHot
+ if (region != null && io.papermc.paper.threadedregions.RegionizedServer.getCurrentTick() % 20 == 0){
+ final java.util.Iterator<net.minecraft.world.level.chunk.LevelChunk> chunkIterator = chunks.unsafeIterator();
+ while (chunkIterator.hasNext()){
+ final net.minecraft.world.level.chunk.LevelChunk targetChunk = chunkIterator.next();
+
+ if (!targetChunk.getChunkHot().isStarted()){
+ continue;
+ }
+
+ targetChunk.getChunkHot().stop();
+ }
+ }
+ //KioCG end
if (false && nano - this.lastServerStatus >= STATUS_EXPIRE_TIME_NANOS) { // Folia - region threading
this.lastServerStatus = nano;
this.status = this.buildServerStatus();
diff --git a/net/minecraft/server/level/ServerLevel.java b/net/minecraft/server/level/ServerLevel.java
index 1a0e5fbc823c328d16f48f2df4507bf240915c79..bd1368def6c2656902bae28dc07b98f8709107a9 100644
--- a/net/minecraft/server/level/ServerLevel.java
+++ b/net/minecraft/server/level/ServerLevel.java
@@ -1484,6 +1484,8 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
public void tickNonPassenger(final Entity entity) {
// Paper start - log detailed entity tick information
ca.spottedleaf.moonrise.common.util.TickThread.ensureTickThread("Cannot tick an entity off-main");
+ LevelChunk levelChunk = entity.shouldTickHot() ? this.getChunkIfLoaded(entity.moonrise$getSectionX(),entity.moonrise$getSectionZ()) : null; // KioCG
+ if (levelChunk != null) levelChunk.getChunkHot().startTicking(); try { // KioCG
try {
// Folia - region threading
// Paper end - log detailed entity tick information
@@ -1560,6 +1562,7 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
} finally {
// Folia - region threading
}
+ } finally { if (levelChunk != null) levelChunk.getChunkHot().stopTickingAndCount(); } // KioCG
// Paper end - log detailed entity tick information
}
@@ -1571,6 +1574,8 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
final int timerId = isActive ? entity.getType().tickTimerId : entity.getType().inactiveTickTimerId;
final ca.spottedleaf.leafprofiler.RegionizedProfiler.Handle foliaProfiler = io.papermc.paper.threadedregions.TickRegionScheduler.getProfiler();
foliaProfiler.startTimer(timerId);
+ LevelChunk levelChunk = !(entity instanceof Player) ? this.getChunkIfLoaded(entity.blockPosition()) : null; // KioCG
+ if (levelChunk != null) levelChunk.getChunkHot().startTicking(); try { // KioCG
try {
// Folia end - profiler
entity.setOldPosAndRot();
@@ -1612,6 +1617,7 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
this.tickPassenger(entity, passenger, isActive); // Paper - EAR 2
}
} finally { foliaProfiler.stopTimer(timerId); } // Folia - profiler
+ } finally { if (levelChunk != null) levelChunk.getChunkHot().stopTickingAndCount(); } // KioCG
}
}
diff --git a/net/minecraft/server/level/ServerPlayer.java b/net/minecraft/server/level/ServerPlayer.java
index f22b5fdec6da8bcff9aef3d9fed5dbe61d39250a..336a1ae13810207696a699a936d4031eb904d0dd 100644
--- a/net/minecraft/server/level/ServerPlayer.java
+++ b/net/minecraft/server/level/ServerPlayer.java
@@ -889,6 +889,9 @@ public class ServerPlayer extends Player implements ca.spottedleaf.moonrise.patc
@Override
public void tick() {
+ // Shiroha start - Add status bars
+ this.statusBarList.tick();
+ // Shiroha end - Add status bars
// CraftBukkit start
if (this.joining) {
this.joining = false;
@@ -949,7 +952,34 @@ public class ServerPlayer extends Player implements ca.spottedleaf.moonrise.patc
this.trackEnteredOrExitedLavaOnVehicle();
this.updatePlayerAttributes();
this.advancements.flushDirty(this, true);
+
+ // KioCG start - ChunkHot
+ if (this.tickCount % 20 == 0){
+ this.nearbyChunkHot = this.refreshNearbyChunkHot();
+ }
+ // KioCG end
+ }
+
+ // KioCG start - ChunkHot
+ private volatile long nearbyChunkHot = 0;
+
+ public long getNearbyChunkHot() { return this.nearbyChunkHot; }
+
+ private long refreshNearbyChunkHot() {
+ long total = 0L;
+ int searchRadius = ((ServerLevel) this.level()).moonrise$getViewDistanceHolder().getViewDistances().tickViewDistance();
+ for (int i = this.moonrise$getSectionX() - searchRadius; i <= this.moonrise$getSectionX() + searchRadius; ++i) {
+ for (int j = this.moonrise$getSectionZ() - searchRadius; j <= this.moonrise$getSectionZ() + searchRadius; ++j) {
+ net.minecraft.world.level.chunk.LevelChunk targetChunk = this.level().getChunkIfLoaded(i, j);
+ if (targetChunk != null) {
+ total += targetChunk.getChunkHot().getAverage();
+ }
+ }
+ }
+ return total;
}
+ // KioCG end
+
private void updatePlayerAttributes() {
AttributeInstance blockInteractionRange = this.getAttribute(Attributes.BLOCK_INTERACTION_RANGE);
diff --git a/net/minecraft/world/entity/AreaEffectCloud.java b/net/minecraft/world/entity/AreaEffectCloud.java
index f03fa06c0ba56f7f5e1e45bc1568a490751efde3..eee1c14249addbf4714df733870da9747bda2245 100644
--- a/net/minecraft/world/entity/AreaEffectCloud.java
+++ b/net/minecraft/world/entity/AreaEffectCloud.java
@@ -415,4 +415,11 @@ public class AreaEffectCloud extends Entity implements TraceableEntity {
return super.applyImplicitComponent(type, value);
}
}
+
+ // KioCG start
+ @Override
+ public boolean shouldTickHot() {
+ return false;
+ }
+ // KioCG end
}
diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java
index 5d2f1a90a8e78a95b47c580f6dc4b893dc98f067..18e0572fe28461e57edb13e6ed6f5a0b6b3604c9 100644
--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -6347,4 +6347,6 @@ public abstract class Entity
return ((ServerLevel) this.level()).isPositionEntityTicking(this.blockPosition());
}
// Paper end
+
+ public boolean shouldTickHot() { return this.tickCount > 20 * 10 && this.isAlive(); } // KioCG
}
diff --git a/net/minecraft/world/entity/LightningBolt.java b/net/minecraft/world/entity/LightningBolt.java
index 5b19fee8a4861e5dbfb545bbe4dabda7787c430a..0afca6f5f5b02609fd55e9ea4d72b8862cc03420 100644
--- a/net/minecraft/world/entity/LightningBolt.java
+++ b/net/minecraft/world/entity/LightningBolt.java
@@ -283,4 +283,11 @@ public class LightningBolt extends Entity {
public final boolean hurtServer(final ServerLevel level, final DamageSource source, final float damage) {
return false;
}
+
+ // KioCG start
+ @Override
+ public boolean shouldTickHot() {
+ return false;
+ }
+ // KioCG end
}
diff --git a/net/minecraft/world/entity/Mob.java b/net/minecraft/world/entity/Mob.java
index c6ce88fb63e0d40ed011958a1afd36c645d965c8..3c59325cb82a66a74d6605b51db83ff63e59e089 100644
--- a/net/minecraft/world/entity/Mob.java
+++ b/net/minecraft/world/entity/Mob.java
@@ -1735,4 +1735,11 @@ public abstract class Mob extends LivingEntity implements Targeting, EquipmentUs
public float chargeSpeedModifier() {
return 1.0F;
}
+
+ // KioCG start
+ @Override
+ public boolean shouldTickHot() {
+ return super.shouldTickHot() && (!this.removeWhenFarAway(0.0) || this.isPersistenceRequired() || this.requiresCustomPersistence());
+ }
+ // KioCG end
}
diff --git a/net/minecraft/world/entity/animal/equine/TraderLlama.java b/net/minecraft/world/entity/animal/equine/TraderLlama.java
index 7c92c9335997cee76ff360c51f704ee41a180796..fb4cab83fd23c5561326a58683558e9a4219b0e9 100644
--- a/net/minecraft/world/entity/animal/equine/TraderLlama.java
+++ b/net/minecraft/world/entity/animal/equine/TraderLlama.java
@@ -164,4 +164,11 @@ public class TraderLlama extends Llama {
super.start();
}
}
+
+ // KioCG start
+ @Override
+ public boolean shouldTickHot() {
+ return super.shouldTickHot() && !this.canDespawn();
+ }
+ // KioCG end
}
diff --git a/net/minecraft/world/entity/npc/wanderingtrader/WanderingTrader.java b/net/minecraft/world/entity/npc/wanderingtrader/WanderingTrader.java
index f79353aa58b03d00839e4e95d1fd2480a635a592..0a43947bcc9f505ad9bc4d54c564709c2c3e411a 100644
--- a/net/minecraft/world/entity/npc/wanderingtrader/WanderingTrader.java
+++ b/net/minecraft/world/entity/npc/wanderingtrader/WanderingTrader.java
@@ -271,4 +271,11 @@ public class WanderingTrader extends AbstractVillager implements Consumable.Over
return !pos.closerToCenterThan(this.trader.position(), distance);
}
}
+
+ // KioCG start
+ @Override
+ public boolean shouldTickHot() {
+ return false;
+ }
+ // KioCG end
}
diff --git a/net/minecraft/world/entity/player/Player.java b/net/minecraft/world/entity/player/Player.java
index 2eb5fc819e2e17c69de87f8aa1a99e02bc5a62d5..ab0f42c6ed9ba4f920eefba4d1449ded6dda0fe9 100644
--- a/net/minecraft/world/entity/player/Player.java
+++ b/net/minecraft/world/entity/player/Player.java
@@ -170,6 +170,7 @@ public abstract class Player extends Avatar implements ContainerUser {
private ItemStack lastItemInMainHand = ItemStack.EMPTY;
private final ItemCooldowns cooldowns = this.createItemCooldowns();
private Optional<GlobalPos> lastDeathLocation = Optional.empty();
+ public io.nanachiyo0721.shiroha.functions.bars.TickableStatusBarList statusBarList = new io.nanachiyo0721.shiroha.functions.bars.TickableStatusBarList(this); // Shiroha - Add status bars
public @Nullable FishingHook fishing;
public float hurtDir;
public boolean affectsSpawning = true; // Paper - Affects Spawning API
@@ -679,6 +680,7 @@ public abstract class Player extends Avatar implements ContainerUser {
this.getAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(this.abilities.getWalkingSpeed());
this.enderChestInventory.fromSlots(input.listOrEmpty("EnderItems", ItemStackWithSlot.CODEC));
this.setLastDeathLocation(input.read("LastDeathLocation", GlobalPos.CODEC));
+ this.statusBarList.load(input); // Shiroha - Add status bars
}
@Override
@@ -697,6 +699,7 @@ public abstract class Player extends Avatar implements ContainerUser {
output.store("abilities", Abilities.Packed.CODEC, this.abilities.pack());
this.enderChestInventory.storeAsSlots(output.list("EnderItems", ItemStackWithSlot.CODEC));
this.lastDeathLocation.ifPresent(pos -> output.store("LastDeathLocation", GlobalPos.CODEC, pos));
+ this.statusBarList.save(output); // Shiroha - Add status bars
}
@Override
@@ -2255,4 +2258,12 @@ public abstract class Player extends Avatar implements ContainerUser {
public static final Player.BedSleepingProblem NOT_SAFE = new Player.BedSleepingProblem(Component.translatable("block.minecraft.bed.not_safe"));
public static final Player.BedSleepingProblem EXPLOSION = new Player.BedSleepingProblem(null); // Paper - Added to properly handle explosions in bed events
}
+
+ // KioCG start
+ @Override
+ public boolean shouldTickHot() {
+ return false;
+ }
+ // KioCG end
+
}
diff --git a/net/minecraft/world/entity/projectile/Projectile.java b/net/minecraft/world/entity/projectile/Projectile.java
index 67d01bb84cd40a3f67de441e9dbdc2ac7638cada..721e3b083846fd363a31311196bc4c681969215c 100644
--- a/net/minecraft/world/entity/projectile/Projectile.java
+++ b/net/minecraft/world/entity/projectile/Projectile.java
@@ -512,4 +512,11 @@ public abstract class Projectile extends Entity implements TraceableEntity {
public interface ProjectileFactory<T extends Projectile> {
T create(final ServerLevel level, LivingEntity entity, ItemStack itemStack);
}
+
+ // KioCG start
+ @Override
+ public boolean shouldTickHot() {
+ return false;
+ }
+ // KioCG end
}
diff --git a/net/minecraft/world/level/chunk/LevelChunk.java b/net/minecraft/world/level/chunk/LevelChunk.java
index 64e0c4a60a74cd33f2b99f34fa2a419abf3a0c02..0e84b695a677e71f443a29c78fc5025eec7ae7f4 100644
--- a/net/minecraft/world/level/chunk/LevelChunk.java
+++ b/net/minecraft/world/level/chunk/LevelChunk.java
@@ -112,6 +112,7 @@ public class LevelChunk extends ChunkAccess implements DebugValueSource, ca.spot
// Paper start - rewrite chunk system
private boolean postProcessingDone;
private ca.spottedleaf.moonrise.patches.chunk_system.scheduling.NewChunkHolder chunkAndHolder;
+ private final com.kiocg.ChunkHot chunkHot = new com.kiocg.ChunkHot(); public com.kiocg.ChunkHot getChunkHot() { return this.chunkHot; } // KioCG
@Override
public final boolean moonrise$isPostProcessingDone() {
@@ -960,6 +961,7 @@ public class LevelChunk extends ChunkAccess implements DebugValueSource, ca.spot
ProfilerFiller profiler = Profiler.get();
profiler.push(this::getType);
foliaProfiler.startTimer(timerId); try { // Folia - profiler
+ LevelChunk.this.chunkHot.startTicking(); // KioCG
BlockState blockState = LevelChunk.this.getBlockState(pos);
if (this.blockEntity.getType().isValid(blockState)) {
this.ticker.tick(LevelChunk.this.level, this.blockEntity.getBlockPos(), blockState, this.blockEntity);
@@ -979,7 +981,7 @@ public class LevelChunk extends ChunkAccess implements DebugValueSource, ca.spot
);
} // Paper - Remove the Block Entity if it's invalid
}
- } finally { foliaProfiler.stopTimer(timerId); } // Folia - profiler
+ } finally { foliaProfiler.stopTimer(timerId); LevelChunk.this.chunkHot.stopTickingAndCount(); } // Folia - profiler // KioCG
profiler.pop();
} catch (Throwable t) {
diff --git a/net/minecraft/world/level/redstone/NeighborUpdater.java b/net/minecraft/world/level/redstone/NeighborUpdater.java
index 041ed95948ff6bb4cf3610ce4522a6ba105b6812..44dbe6f83c8593c213132feabc7fe27615cb0049 100644
--- a/net/minecraft/world/level/redstone/NeighborUpdater.java
+++ b/net/minecraft/world/level/redstone/NeighborUpdater.java
@@ -81,7 +81,10 @@ public interface NeighborUpdater {
return;
}
// CraftBukkit end
+ net.minecraft.world.level.chunk.LevelChunk levelChunk = level.getChunkIfLoaded(pos); // KioCG
+ if (levelChunk != null) levelChunk.getChunkHot().startTicking(); try { // KioCG
state.handleNeighborChanged(level, pos, changedBlock, orientation, movedByPiston);
+ } finally { if (levelChunk != null) levelChunk.getChunkHot().stopTickingAndCount(); } // KioCG
// Spigot start
} catch (StackOverflowError ex) {
level.lastPhysicsProblem = pos.immutable();
@@ -0,0 +1,94 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 9 Jul 2026 11:54:24 +0800
Subject: [PATCH] Leaves Vanilla Hopper
A part from leaves
Origin patch link: https://github.com/LeavesMC/Leaves/blob/master/leaves-server/minecraft-patches/features/0092-Vanilla-hopper.patch
Origin license: https://github.com/LeavesMC/Leaves/blob/master/LICENSE.md
diff --git a/net/minecraft/world/level/block/entity/HopperBlockEntity.java b/net/minecraft/world/level/block/entity/HopperBlockEntity.java
index a858cb658af70f07614fa1f4d9e8a3435d5c161f..4c9d0bcd8820b250b51c06fff4531021ab57d408 100644
--- a/net/minecraft/world/level/block/entity/HopperBlockEntity.java
+++ b/net/minecraft/world/level/block/entity/HopperBlockEntity.java
@@ -281,36 +281,55 @@ public class HopperBlockEntity extends RandomizableContainerBlockEntity implemen
ItemStack movedItem = origItemStack;
final int originalItemCount = origItemStack.getCount();
final int movedItemCount = Math.min(level.spigotConfig.hopperAmount, originalItemCount);
- container.setChanged(); // original logic always marks source inv as changed even if no move happens.
- movedItem.setCount(movedItemCount);
-
- if (!worldData.skipPullModeEventFire) { // Folia - region threading
- movedItem = callPullMoveEvent(hopper, container, movedItem);
- if (movedItem == null) { // cancelled
- origItemStack.setCount(originalItemCount);
- // Drastically improve performance by returning true.
- // No plugin could have relied on the behavior of false as the other call
- // site for IMIE did not exhibit the same behavior
+ // Leaves start - fix vanilla hopper
+ if (movedItem.getCount() <= movedItemCount) {
+ if (!worldData.skipPullModeEventFire) {
+ movedItem = callPullMoveEvent(hopper, container, movedItem);
+ if (movedItem == null) { // cancelled
+ origItemStack.setCount(originalItemCount);
+ return true;
+ }
+ }
+ movedItem = origItemStack.copy();
+ final ItemStack remainingItem = addItem(container, hopper, container.removeItem(i, movedItemCount), null);
+ if (remainingItem.isEmpty()) {
+ container.setChanged();
return true;
}
- }
+ container.setItem(i, movedItem);
+ } else {
+ container.setChanged(); // original logic always marks source inv as changed even if no move happens.
+ movedItem.setCount(movedItemCount);
- final ItemStack remainingItem = addItem(container, hopper, movedItem, null);
- final int remainingItemCount = remainingItem.getCount();
- if (remainingItemCount != movedItemCount) {
- origItemStack = origItemStack.copy(true);
- origItemStack.setCount(originalItemCount);
- if (!origItemStack.isEmpty()) {
- origItemStack.setCount(originalItemCount - movedItemCount + remainingItemCount);
+ if (!worldData.skipPullModeEventFire) {
+ movedItem = callPullMoveEvent(hopper, container, movedItem);
+ if (movedItem == null) { // cancelled
+ origItemStack.setCount(originalItemCount);
+ // Drastically improve performance by returning true.
+ // No plugin could have relied on the behavior of false as the other call
+ // site for IMIE did not exhibit the same behavior
+ return true;
+ }
}
- IGNORE_TILE_UPDATES.set(true); // Folia - region threading
- container.setItem(i, origItemStack);
- IGNORE_TILE_UPDATES.set(false); // Folia - region threading
- container.setChanged();
- return true;
+ final ItemStack remainingItem = addItem(container, hopper, movedItem, null);
+ final int remainingItemCount = remainingItem.getCount();
+ if (remainingItemCount != movedItemCount) {
+ origItemStack = origItemStack.copy(true);
+ origItemStack.setCount(originalItemCount);
+ if (!origItemStack.isEmpty()) {
+ origItemStack.setCount(originalItemCount - movedItemCount + remainingItemCount);
+ }
+
+ IGNORE_TILE_UPDATES.set(true);
+ container.setItem(i, origItemStack);
+ IGNORE_TILE_UPDATES.set(false);
+ container.setChanged();
+ return true;
+ }
+ origItemStack.setCount(originalItemCount);
}
- origItemStack.setCount(originalItemCount);
+ // Leaves end - fix vanilla hopper
if (level.paperConfig().hopper.cooldownWhenFull) {
applyCooldown(hopper);
@@ -0,0 +1,28 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 18 Apr 2026 12:30:47 +0800
Subject: [PATCH] Petal: Reduce sensor work
Co-authored by: peaches94 <peachescu94@gmail.com>
As part of: Petal (https://github.com/Bloom-host/Petal/blob/cc691540fb48240f38b376f3d94c8b0db2b60d99/patches/server/0005-feat-reduce-sensor-work.patch)
Licensed under: GPL-3.0 (https://github.com/Bloom-host/Petal/blob/cc691540fb48240f38b376f3d94c8b0db2b60d99/LICENSE)
diff --git a/net/minecraft/world/entity/Mob.java b/net/minecraft/world/entity/Mob.java
index 3c59325cb82a66a74d6605b51db83ff63e59e089..cab6061af551352a27e623af2ced3f497c5af2b3 100644
--- a/net/minecraft/world/entity/Mob.java
+++ b/net/minecraft/world/entity/Mob.java
@@ -840,11 +840,12 @@ public abstract class Mob extends LivingEntity implements Targeting, EquipmentUs
return;
}
// Paper end - Allow nerfed mobs to jump and float
+ int idBasedTickCount = this.tickCount + this.getId(); // Shiroha - Petal - Move up
ProfilerFiller profiler = Profiler.get();
profiler.push("sensing");
- this.sensing.tick();
+ if (idBasedTickCount % io.nanachiyo0721.shiroha.config.modules.optimizations.PetalReduceSensorWorkConfig.delayTicks == 0 || !io.nanachiyo0721.shiroha.config.modules.optimizations.PetalReduceSensorWorkConfig.enabled) this.sensing.tick(); // Shiroha - Petal - Reduce sensor work
profiler.pop();
- int idBasedTickCount = this.tickCount + this.getId();
+ //int idBasedTickCount = this.tickCount + this.getId(); // Shiroha - Petal - Move up
if (idBasedTickCount % 2 != 0 && this.tickCount > 1) {
profiler.push("targetSelector");
this.targetSelector.tickRunningGoals(false);
@@ -0,0 +1,89 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 9 Jul 2026 12:13:58 +0800
Subject: [PATCH] Purpur: Lobotomize stuck villagers
Co-authored by: William Blake Galbreath <Blake.Galbreath@GMail.com>
As part of: Purpur (https://github.com/PurpurMC/Purpur/blob/09f547de09fc5d886f18f6d99ff389289766ec9d/purpur-server/minecraft-patches/features/0001-Ridables.patch)
Licensed under: MIT (https://github.com/PurpurMC/Purpur/blob/09f547de09fc5d886f18f6d99ff389289766ec9d/LICENSE)
diff --git a/net/minecraft/world/entity/npc/villager/Villager.java b/net/minecraft/world/entity/npc/villager/Villager.java
index f649c46cc9a34e646f8da3244866c6e011d30aa3..b0b017f61f1c7832068d2ba7b10efc72b9815b39 100644
--- a/net/minecraft/world/entity/npc/villager/Villager.java
+++ b/net/minecraft/world/entity/npc/villager/Villager.java
@@ -190,6 +190,53 @@ public class Villager extends AbstractVillager implements VillagerDataHolder, Re
this.setCanPickUpLoot(true);
}
+ // Purpur start
+ private boolean isLobotomized = false; public boolean isLobotomized() { return this.isLobotomized; } // Purpur
+ private int notLobotomizedCount = 0; // Purpur
+
+ private boolean checkLobotomized() {
+ int interval = io.nanachiyo0721.shiroha.config.modules.optimizations.LobotomizeVillageConfig.villagerLobotomizeCheckInterval;
+ boolean shouldCheckForTradeLocked = io.nanachiyo0721.shiroha.config.modules.optimizations.LobotomizeVillageConfig.villagerLobotomizeWaitUntilTradeLocked;
+ if (this.notLobotomizedCount > 3) {
+ // check half as often if not lobotomized for the last 3+ consecutive checks
+ interval *= 2;
+ }
+ if (this.level().getGameTime() % interval == 0) {
+ // offset Y for short blocks like dirt_path/farmland
+ this.isLobotomized = !(shouldCheckForTradeLocked && this.getVillagerXp() == 0) && !canTravelFrom(net.minecraft.core.BlockPos.containing(this.position().x, this.getBoundingBox().minY + 0.0625D, this.position().z));
+
+ if (this.isLobotomized) {
+ this.notLobotomizedCount = 0;
+ } else {
+ this.notLobotomizedCount++;
+ }
+ }
+ return this.isLobotomized;
+ }
+ // Purpur end
+
+ private boolean canTravelFrom(net.minecraft.core.BlockPos pos) {
+ return canTravelTo(pos.east()) || canTravelTo(pos.west()) || canTravelTo(pos.north()) || canTravelTo(pos.south());
+ }
+
+ private boolean canTravelTo(net.minecraft.core.BlockPos pos) {
+ net.minecraft.world.level.block.state.BlockState state = this.level().getBlockStateIfLoaded(pos);
+ if (state == null) {
+ // chunk not loaded
+ return false;
+ }
+ net.minecraft.world.level.block.Block bottom = state.getBlock();
+ if (bottom instanceof net.minecraft.world.level.block.FenceBlock ||
+ bottom instanceof net.minecraft.world.level.block.FenceGateBlock ||
+ bottom instanceof net.minecraft.world.level.block.WallBlock) {
+ // bottom block is too tall to get over
+ return false;
+ }
+ net.minecraft.world.level.block.Block top = level().getBlockState(pos.above()).getBlock();
+ // only if both blocks have no collision
+ return !bottom.hasCollision && !top.hasCollision;
+ }
+
@Override
public Brain<Villager> getBrain() {
return (Brain<Villager>)super.getBrain();
@@ -259,11 +306,20 @@ public class Villager extends AbstractVillager implements VillagerDataHolder, Re
// Paper start - EAR 2
this.customServerAiStep(level, false);
}
- protected void customServerAiStep(ServerLevel level, final boolean inactive) {
+ protected void customServerAiStep(ServerLevel level, boolean inactive) { // Purpur - not final
// Paper end - EAR 2
ProfilerFiller profiler = Profiler.get();
profiler.push("villagerBrain");
+ // Purpur start
+ if (io.nanachiyo0721.shiroha.config.modules.optimizations.LobotomizeVillageConfig.villagerLobotomizeEnabled) {
+ // treat as inactive if lobotomized
+ inactive = inactive || checkLobotomized();
+ } else {
+ this.isLobotomized = false;
+ }
+ // Purpur end
if (!inactive) this.getBrain().tick(level, this); // Paper - EAR 2
+ else if (this.isLobotomized && shouldRestock(level)) restock(); // Purpur - Lobotomize stuck villagers
profiler.pop();
if (this.assignProfessionWhenSpawned) {
this.assignProfessionWhenSpawned = false;
@@ -0,0 +1,68 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Fri, 1 May 2026 21:47:48 +0800
Subject: [PATCH] Pufferfish: Reduce projectile chunk loading
A part of Pufferfish(https://github.com/Pufferfish-gg/Pufferfish)
Co-authored-by: Paul Sauve <paul@technove.co>
Original patch: https://github.com/pufferfish-gg/Pufferfish/blob/ver/1.21/pufferfish-server/minecraft-patches/features/0006-Reduce-projectile-chunk-loading.patch
Original license(GPL-3.0): https://github.com/pufferfish-gg/Pufferfish/blob/ver/1.21/PATCH-LICENSE
diff --git a/io/papermc/paper/threadedregions/RegionizedWorldData.java b/io/papermc/paper/threadedregions/RegionizedWorldData.java
index be3bdce1b42a32f57d9ec71d8f115ea1ceac9d52..fc5161a77a4a846888c564123265a669188646b5 100644
--- a/io/papermc/paper/threadedregions/RegionizedWorldData.java
+++ b/io/papermc/paper/threadedregions/RegionizedWorldData.java
@@ -408,6 +408,10 @@ public final class RegionizedWorldData {
private RegionizedServer.WorldLevelData tickData;
+ // Shiroha start - Pufferfish - Reduce projectile chunk loading
+ public long pufferfish$loadedThisTick = 0L;
+ public long pufferfish$loadedTick = 0L;
+ // Shiroha end
// connections
public final List<Connection> connections = new ArrayList<>();
diff --git a/net/minecraft/world/entity/projectile/Projectile.java b/net/minecraft/world/entity/projectile/Projectile.java
index 721e3b083846fd363a31311196bc4c681969215c..9f49f0b801e23a82492e6b2865ba60493bf2f944 100644
--- a/net/minecraft/world/entity/projectile/Projectile.java
+++ b/net/minecraft/world/entity/projectile/Projectile.java
@@ -58,6 +58,38 @@ public abstract class Projectile extends Entity implements TraceableEntity {
this.setOwner(EntityReference.of(owner));
}
+ // Pufferfish start
+ private int loadedLifetime = 0;
+ @Override
+ public void setPos(double x, double y, double z) {
+ var currRegionData = io.papermc.paper.threadedregions.TickRegionScheduler.getCurrentRegionizedWorldData();
+ // we might run this on a chunk system worker(chunk gen), so skip this check if no world data was fetched
+ if (currRegionData == null || currRegionData.world != this.level()) {
+ return;
+ }
+ long currentTick = currRegionData.getRedstoneGameTime();
+ if (currRegionData.pufferfish$loadedTick != currentTick) {
+ currRegionData.pufferfish$loadedTick = currentTick;
+ currRegionData.pufferfish$loadedThisTick = 0L;
+ }
+ int previousX = Mth.floor(this.getX()) >> 4, previousZ = Mth.floor(this.getZ()) >> 4;
+ int newX = Mth.floor(x) >> 4, newZ = Mth.floor(z) >> 4;
+ if (previousX != newX || previousZ != newZ) {
+ boolean isLoaded = ((net.minecraft.server.level.ServerChunkCache) this.level().getChunkSource()).getChunkAtIfLoadedImmediately(newX, newZ) != null;
+ if (!isLoaded) {
+ if (currRegionData.pufferfish$loadedThisTick > io.nanachiyo0721.shiroha.config.modules.optimizations.ProjectileChunkReduceConfig.maxProjectileLoadsPerTick) {
+ if (++this.loadedLifetime > io.nanachiyo0721.shiroha.config.modules.optimizations.ProjectileChunkReduceConfig.maxProjectileLoadsPerProjectile) {
+ this.discard();
+ }
+ return;
+ }
+ currRegionData.pufferfish$loadedThisTick++;
+ }
+ }
+ super.setPos(x, y, z);
+ }
+ // Pufferfish end
+
// Folia start - region threading
// In general, this is an entire mess. At the time of writing, there are fifty usages of getOwner.
// Usage of this function is to avoid concurrency issues, even if it sacrifices behavior.
@@ -0,0 +1,30 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Fri, 1 May 2026 21:48:40 +0800
Subject: [PATCH] Pufferfish: Throttle goal selector during inactive ticking
A part of Pufferfish(https://github.com/Pufferfish-gg/Pufferfish)
Co-authored-by: Kevin Raneri <kevin.raneri@gmail.com>
Original patch: https://github.com/pufferfish-gg/Pufferfish/blob/ver/1.21/pufferfish-server/minecraft-patches/features/0015-Throttle-goal-selector-during-inactive-ticking.patch
Original license(GPL-3.0): https://github.com/pufferfish-gg/Pufferfish/blob/ver/1.21/PATCH-LICENSE
diff --git a/net/minecraft/world/entity/Mob.java b/net/minecraft/world/entity/Mob.java
index cab6061af551352a27e623af2ced3f497c5af2b3..e87af051432e0118fc4c16d7ac321b3072ef0c24 100644
--- a/net/minecraft/world/entity/Mob.java
+++ b/net/minecraft/world/entity/Mob.java
@@ -215,12 +215,14 @@ public abstract class Mob extends LivingEntity implements Targeting, EquipmentUs
return this.lookControl;
}
+ int _pufferfish_inactiveTickDisableCounter = 0; // Pufferfish - throttle inactive goal selector ticking
// Paper start
@Override
public void inactiveTick() {
super.inactiveTick();
if (!this.aware) return; // Paper - Do not tick AI for inactive unaware mobs
- if (this.goalSelector.inactiveTick()) {
+ boolean isThrottled = io.nanachiyo0721.shiroha.config.modules.optimizations.EntityGoalSelectorInactiveTickConfig.enabled && _pufferfish_inactiveTickDisableCounter++ % 20 != 0; // Pufferfish - throttle inactive goal selector ticking
+ if (this.goalSelector.inactiveTick() && !isThrottled) { // Pufferfish
this.goalSelector.tick();
}
if (this.targetSelector.inactiveTick()) {
@@ -0,0 +1,423 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Sun, 28 Jun 2026 20:39:22 +0800
Subject: [PATCH] Leaf: Secure seed and matter seed command
Co-authored by: Apehum <apehumchik@gmail.com>
As part of: Leaf (https://github.com/Winds-Studio/Leaf/blob/7f3e240bbe0970683c40279a7a65f0fde47503b6/leaf-server/paper-patches/features/0019-Matter-Secure-Seed.patch and https://github.com/Winds-Studio/Leaf/blob/7f3e240bbe0970683c40279a7a65f0fde47503b6/leaf-server/minecraft-patches/features/0050-Matter-Secure-Seed-command.patch)
Licensed under: GPL-3.0 (https://github.com/Winds-Studio/Leaf/blob/7f3e240bbe0970683c40279a7a65f0fde47503b6/licenses/GPL-3.0.txt)
diff --git a/net/minecraft/server/commands/SeedCommand.java b/net/minecraft/server/commands/SeedCommand.java
index 86ee3b3ae028597576b9549bc4954dfcbaa6732c..65121d2b17432f0ec5e8ec106cd205396ff96b73 100644
--- a/net/minecraft/server/commands/SeedCommand.java
+++ b/net/minecraft/server/commands/SeedCommand.java
@@ -13,6 +13,15 @@ public class SeedCommand {
long seed = c.getSource().getLevel().getSeed();
Component seedText = ComponentUtils.copyOnClickText(String.valueOf(seed));
c.getSource().sendSuccess(() -> Component.translatable("commands.seed.success", seedText), false);
+ // Leaf start - Matter - SecureSeed Command
+ if (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled) {
+ su.plo.matter.Globals.setupGlobals(c.getSource().getLevel());
+ String seedStr = su.plo.matter.Globals.seedToString(su.plo.matter.Globals.worldSeed);
+ Component featureSeedComponent = ComponentUtils.copyOnClickText(seedStr);
+
+ c.getSource().sendSuccess(() -> Component.translatable(("Feature seed: %s"), featureSeedComponent), false);
+ }
+ // Leaf end - Matter - SecureSeed Command
return (int)seed;
})
);
diff --git a/net/minecraft/server/dedicated/DedicatedServerProperties.java b/net/minecraft/server/dedicated/DedicatedServerProperties.java
index 639a5400499266f83cf8b7c1251483cd8fb699a4..24e355b71c196cb0ea7958ef7d33fb49a3de9bb0 100644
--- a/net/minecraft/server/dedicated/DedicatedServerProperties.java
+++ b/net/minecraft/server/dedicated/DedicatedServerProperties.java
@@ -139,7 +139,17 @@ public class DedicatedServerProperties extends Settings<DedicatedServerPropertie
String levelSeed = this.get("level-seed", "");
boolean generateStructures = this.get("generate-structures", true);
long seed = WorldOptions.parseSeed(levelSeed).orElse(WorldOptions.randomSeed());
- this.worldOptions = new WorldOptions(seed, generateStructures, false);
+ // Leaf start - Matter - Secure Seed
+ if (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled) {
+ String featureSeedStr = this.get("feature-level-seed", "");
+ long[] featureSeed = su.plo.matter.Globals.parseSeed(featureSeedStr)
+ .orElse(su.plo.matter.Globals.createRandomWorldSeed());
+
+ this.worldOptions = new WorldOptions(seed, featureSeed, generateStructures, false);
+ } else {
+ this.worldOptions = new WorldOptions(seed, generateStructures, false);
+ }
+ // Leaf end - Matter - Secure Seed
this.worldDimensionData = new DedicatedServerProperties.WorldDimensionData(
this.get("generator-settings", s -> GsonHelper.parse(!s.isEmpty() ? s : "{}"), new JsonObject()),
this.get("level-type", v -> v.toLowerCase(Locale.ROOT), WorldPresets.NORMAL.identifier().toString())
diff --git a/net/minecraft/server/level/ServerChunkCache.java b/net/minecraft/server/level/ServerChunkCache.java
index b71c16640b1a2495e61480e9eb752fafbada7c44..0011653c857ee82f86355cc49b170120d9f96cfd 100644
--- a/net/minecraft/server/level/ServerChunkCache.java
+++ b/net/minecraft/server/level/ServerChunkCache.java
@@ -671,6 +671,7 @@ public class ServerChunkCache extends ChunkSource implements ca.spottedleaf.moon
}
public ChunkGenerator getGenerator() {
+ su.plo.matter.Globals.setupGlobals(level); // Leaf - Matter - Secure Seed
return this.chunkMap.generator();
}
diff --git a/net/minecraft/server/level/ServerLevel.java b/net/minecraft/server/level/ServerLevel.java
index bd1368def6c2656902bae28dc07b98f8709107a9..fca5017a13148a928ae320ee99cddc45f617ffcd 100644
--- a/net/minecraft/server/level/ServerLevel.java
+++ b/net/minecraft/server/level/ServerLevel.java
@@ -633,6 +633,7 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
generator = new org.bukkit.craftbukkit.generator.CustomChunkGenerator(this, generator, gen);
}
// CraftBukkit end
+ su.plo.matter.Globals.setupGlobals(this); // Leaf - Matter - Secure Seed
boolean syncWrites = server.forceSynchronousWrites();
DataFixer fixerUpper = server.getFixerUpper();
// Paper - rewrite chunk system
diff --git a/net/minecraft/world/entity/monster/cubemob/Slime.java b/net/minecraft/world/entity/monster/cubemob/Slime.java
index 984ec15bdebcb541cd6ee9014a654ea58988f6f1..582fcd553e85ff6e2437c117dc0a655cb0017bae 100644
--- a/net/minecraft/world/entity/monster/cubemob/Slime.java
+++ b/net/minecraft/world/entity/monster/cubemob/Slime.java
@@ -94,7 +94,12 @@ public class Slime extends AbstractCubeMob implements Enemy {
}
ChunkPos chunkPos = ChunkPos.containing(pos);
- boolean slimeChunk = level.getMinecraftWorld().paperConfig().entities.spawning.allChunksAreSlimeChunks || WorldgenRandom.seedSlimeChunk(chunkPos.x(), chunkPos.z(), worldGenLevel.getSeed(), level.getMinecraftWorld().spigotConfig.slimeSeed).nextInt(10) == 0; // Paper
+ // Leaf start - Matter - Secure Seed
+ boolean isSlimeChunk = io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled
+ ? level.getChunk(chunkPos.x(), chunkPos.z()).isSlimeChunk()
+ : WorldgenRandom.seedSlimeChunk(chunkPos.x(), chunkPos.z(), worldGenLevel.getSeed(), level.getMinecraftWorld().spigotConfig.slimeSeed).nextInt(10) == 0; // Paper
+ boolean slimeChunk = level.getMinecraftWorld().paperConfig().entities.spawning.allChunksAreSlimeChunks || isSlimeChunk;
+ // Leaf end - Matter - Secure Seed
// Paper start - Replace rules for Height in Slime Chunks
final double maxHeightSlimeChunk = level.getMinecraftWorld().paperConfig().entities.spawning.slimeSpawnHeight.slimeChunk.maximum;
if (random.nextInt(10) == 0 && slimeChunk && pos.getY() < maxHeightSlimeChunk) {
diff --git a/net/minecraft/world/level/chunk/ChunkAccess.java b/net/minecraft/world/level/chunk/ChunkAccess.java
index 28f703204afd834cd50335346ef065670d6b37ad..f6cecf0ec1ebf9dd7028877dcadf191d1a2d954c 100644
--- a/net/minecraft/world/level/chunk/ChunkAccess.java
+++ b/net/minecraft/world/level/chunk/ChunkAccess.java
@@ -83,6 +83,10 @@ public abstract class ChunkAccess implements LightChunk, StructureAccess, BiomeM
private static final org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry DATA_TYPE_REGISTRY = new org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry();
public org.bukkit.craftbukkit.persistence.DirtyCraftPersistentDataContainer persistentDataContainer = new org.bukkit.craftbukkit.persistence.DirtyCraftPersistentDataContainer(ChunkAccess.DATA_TYPE_REGISTRY);
// CraftBukkit end
+ // Leaf start - Matter - Secure Seed
+ private boolean slimeChunk;
+ private boolean hasComputedSlimeChunk;
+ // Leaf end - Matter - Secure Seed
// Paper start - rewrite chunk system
private volatile ca.spottedleaf.moonrise.patches.starlight.light.SWMRNibbleArray[] blockNibbles;
@@ -186,6 +190,17 @@ public abstract class ChunkAccess implements LightChunk, StructureAccess, BiomeM
return GameEventListenerRegistry.NOOP;
}
+ // Leaf start - Matter - Secure Seed
+ public boolean isSlimeChunk() {
+ if (!hasComputedSlimeChunk) {
+ hasComputedSlimeChunk = true;
+ slimeChunk = su.plo.matter.WorldgenCryptoRandom.seedSlimeChunk(chunkPos.x(), chunkPos.z()).nextInt(10) == 0;
+ }
+
+ return slimeChunk;
+ }
+ // Leaf end - Matter - Secure Seed
+
public abstract BlockState getBlockState(final int x, final int y, final int z); // Paper
public @Nullable BlockState setBlockState(final BlockPos pos, final BlockState state) {
diff --git a/net/minecraft/world/level/chunk/ChunkGenerator.java b/net/minecraft/world/level/chunk/ChunkGenerator.java
index b7325170369299a74be35ecc66a6446c301605b8..e3a57d7fc2ad9244594870ffac7c6625c5781eff 100644
--- a/net/minecraft/world/level/chunk/ChunkGenerator.java
+++ b/net/minecraft/world/level/chunk/ChunkGenerator.java
@@ -347,7 +347,11 @@ public abstract class ChunkGenerator {
Map<Integer, List<Structure>> structuresByStep = structuresRegistry.stream()
.collect(Collectors.groupingBy(structure -> structure.step().ordinal()));
List<FeatureSorter.StepFeatureData> featureList = this.featuresPerStep.get();
- WorldgenRandom random = new WorldgenRandom(new XoroshiroRandomSource(RandomSupport.generateUniqueSeed()));
+ // Leaf start - Matter - Secure Seed
+ WorldgenRandom random = io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled
+ ? new su.plo.matter.WorldgenCryptoRandom(origin.getX(), origin.getZ(), su.plo.matter.Globals.Salt.UNDEFINED, 0)
+ : new WorldgenRandom(new XoroshiroRandomSource(RandomSupport.generateUniqueSeed()));
+ // Leaf end - Matter - Secure Seed
long decorationSeed = random.setDecorationSeed(level.getSeed(), origin.getX(), origin.getZ());
Set<Holder<Biome>> possibleBiomes = new ObjectArraySet<>();
ChunkPos.rangeClosed(sectionPos.chunk(), 1).forEach(chunkPos -> {
@@ -571,8 +575,15 @@ public abstract class ChunkGenerator {
} else {
ArrayList<StructureSet.StructureSelectionEntry> options = new ArrayList<>(structures.size());
options.addAll(structures);
- WorldgenRandom random = new WorldgenRandom(new LegacyRandomSource(0L));
- random.setLargeFeatureSeed(state.getLevelSeed(), sourceChunkPos.x(), sourceChunkPos.z());
+ // Leaf start - Matter - Secure Seed
+ WorldgenRandom random;
+ if (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled) {
+ random = new su.plo.matter.WorldgenCryptoRandom(sourceChunkPos.x(), sourceChunkPos.z(), su.plo.matter.Globals.Salt.GENERATE_FEATURE, 0);
+ } else {
+ random = new WorldgenRandom(new LegacyRandomSource(0L));
+ random.setLargeFeatureSeed(state.getLevelSeed(), sourceChunkPos.x(), sourceChunkPos.z());
+ }
+ // Leaf end - Matter - Secure Seed
int total = 0;
for (StructureSet.StructureSelectionEntry option : options) {
diff --git a/net/minecraft/world/level/chunk/ChunkGeneratorStructureState.java b/net/minecraft/world/level/chunk/ChunkGeneratorStructureState.java
index 8b4ea2b16da45bcefe743990866e43c94e121825..144bf28dac810c7009ec3ce06b4f08e958ebc1f6 100644
--- a/net/minecraft/world/level/chunk/ChunkGeneratorStructureState.java
+++ b/net/minecraft/world/level/chunk/ChunkGeneratorStructureState.java
@@ -203,14 +203,20 @@ public class ChunkGeneratorStructureState {
List<CompletableFuture<ChunkPos>> tasks = new ArrayList<>(count);
int spread = placement.spread();
HolderSet<Biome> preferredBiomes = placement.preferredBiomes();
- RandomSource random = RandomSource.create();
- // Paper start - Add missing structure set seed configs
+ // Leaf start - Matter - Secure Seed
+ RandomSource random = io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled
+ ? new su.plo.matter.WorldgenCryptoRandom(0, 0, su.plo.matter.Globals.Salt.STRONGHOLDS, 0)
+ :RandomSource.create();
+ // Leaf end - Matter - Secure Seed
+ if (!io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled) {
+ //Paper start - Add missing structure set seed configs
if (this.conf.strongholdSeed != null && structureSet.is(net.minecraft.world.level.levelgen.structure.BuiltinStructureSets.STRONGHOLDS)) {
random.setSeed(this.conf.strongholdSeed);
} else {
// Paper end - Add missing structure set seed configs
random.setSeed(this.concentricRingsSeed);
} // Paper - Add missing structure set seed configs
+ } // Leaf - Matter - Secure Seed
double angle = random.nextDouble() * Math.PI * 2.0;
int positionInCircle = 0;
int circle = 0;
diff --git a/net/minecraft/world/level/chunk/status/ChunkStep.java b/net/minecraft/world/level/chunk/status/ChunkStep.java
index 9208924f54d5024bc50ad4501fbff9eb2a289181..01d87d9c474a5f3e14713579e6a1d1e17d2455ae 100644
--- a/net/minecraft/world/level/chunk/status/ChunkStep.java
+++ b/net/minecraft/world/level/chunk/status/ChunkStep.java
@@ -60,6 +60,7 @@ public final class ChunkStep implements ca.spottedleaf.moonrise.patches.chunk_sy
}
public CompletableFuture<ChunkAccess> apply(final WorldGenContext context, final StaticCache2D<GenerationChunkHolder> cache, final ChunkAccess chunk) {
+ su.plo.matter.Globals.setupGlobals(context.level()); // Leaf - Matter - Secure Seed
if (chunk.getPersistedStatus().isBefore(this.targetStatus)) {
ProfiledDuration profiledDuration = JvmProfiler.INSTANCE.onChunkGenerate(chunk.getPos(), context.level().dimension(), this.targetStatus.getName());
return this.task.doWork(context, this, cache, chunk).thenApply(newCenterChunk -> this.completeChunkGeneration(newCenterChunk, profiledDuration));
diff --git a/net/minecraft/world/level/levelgen/WorldOptions.java b/net/minecraft/world/level/levelgen/WorldOptions.java
index 4ad94af024d81b7dfe910dcee2a6ec7a9b200d56..075bffa587e7ca394421a3a4d03b7eb125955247 100644
--- a/net/minecraft/world/level/levelgen/WorldOptions.java
+++ b/net/minecraft/world/level/levelgen/WorldOptions.java
@@ -10,8 +10,22 @@ import net.minecraft.util.RandomSource;
import org.apache.commons.lang3.StringUtils;
public class WorldOptions {
+ // Leaf start - Matter - Secure Seed
+ private static final com.google.gson.Gson gson = new com.google.gson.Gson();
+ private static final boolean isSecureSeedEnabled = io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled;
public static final MapCodec<WorldOptions> CODEC = RecordCodecBuilder.mapCodec(
- i -> i.group(
+ // Leaf start - Matter - Secure Seed
+ i -> isSecureSeedEnabled
+ ? i.group(
+ Codec.LONG.fieldOf("seed").stable().forGetter(WorldOptions::seed),
+ Codec.STRING.fieldOf("feature_seed").orElse(gson.toJson(su.plo.matter.Globals.createRandomWorldSeed())).stable().forGetter(WorldOptions::featureSeedSerialize),
+ Codec.BOOL.fieldOf("generate_features").orElse(true).stable().forGetter(WorldOptions::generateStructures),
+ Codec.BOOL.fieldOf("bonus_chest").orElse(false).stable().forGetter(WorldOptions::generateBonusChest),
+ Codec.STRING.lenientOptionalFieldOf("legacy_custom_options").stable().forGetter(worldOptions -> worldOptions.legacyCustomOptions)
+ )
+ .apply(i, i.stable(WorldOptions::new))
+ : i.group(
+ // Leaf end
Codec.LONG.fieldOf("seed").stable().forGetter(WorldOptions::seed),
ExtraCodecs.optionalAlwaysPresentFieldOf(Codec.BOOL, "generate_structures", true).stable().forGetter(WorldOptions::generateStructures),
ExtraCodecs.optionalAlwaysPresentFieldOf(Codec.BOOL, "bonus_chest", false).stable().forGetter(WorldOptions::generateBonusChest),
@@ -19,8 +33,14 @@ public class WorldOptions {
)
.apply(i, i.stable(WorldOptions::new))
);
- public static final WorldOptions DEMO_OPTIONS = new WorldOptions("North Carolina".hashCode(), true, true);
+ // Leaf end - Matter - Secure Seed
+ // Leaf start - Matter - Secure Seed
+ public static final WorldOptions DEMO_OPTIONS = isSecureSeedEnabled
+ ? new WorldOptions((long) "North Carolina".hashCode(), su.plo.matter.Globals.createRandomWorldSeed(), true, true)
+ : new WorldOptions("North Carolina".hashCode(), true, true);
+ // Leaf end - Matter - Secure Seed
private final long seed;
+ private long[] featureSeed = su.plo.matter.Globals.createRandomWorldSeed(); // Leaf - Matter - Secure Seed
private final boolean generateStructures;
private final boolean generateBonusChest;
private final Optional<String> legacyCustomOptions;
@@ -29,14 +49,35 @@ public class WorldOptions {
this(seed, generateStructures, generateBonusChest, Optional.empty());
}
+ // Leaf start - Matter - Secure Seed
+ public WorldOptions(long seed, long[] featureSeed, boolean generateStructures, boolean bonusChest) {
+ this(seed, featureSeed, generateStructures, bonusChest, Optional.empty());
+ }
+
+ private WorldOptions(long seed, String featureSeedJson, boolean generateStructures, boolean bonusChest, Optional<String> legacyCustomOptions) {
+ this(seed, gson.fromJson(featureSeedJson, long[].class), generateStructures, bonusChest, legacyCustomOptions);
+ }
+ // Leaf end - Matter - Secure Seed
+
public static WorldOptions defaultWithRandomSeed() {
- return new WorldOptions(randomSeed(), true, false);
+ // Leaf start - Matter - Secure Seed
+ return isSecureSeedEnabled
+ ? new WorldOptions(randomSeed(), su.plo.matter.Globals.createRandomWorldSeed(), true, false)
+ : new WorldOptions(randomSeed(), true, false);
+ // Leaf end - Matter - Secure Seed
}
public static WorldOptions testWorldWithRandomSeed() {
return new WorldOptions(randomSeed(), false, false);
}
+ // Leaf start - Matter - Secure Seed
+ private WorldOptions(long seed, long[] featureSeed, boolean generateStructures, boolean bonusChest, Optional<String> legacyCustomOptions) {
+ this(seed, generateStructures, bonusChest, legacyCustomOptions);
+ this.featureSeed = featureSeed;
+ }
+ // Leaf end - Matter - Secure Seed
+
private WorldOptions(final long seed, final boolean generateStructures, final boolean generateBonusChest, final Optional<String> legacyCustomOptions) {
this.seed = seed;
this.generateStructures = generateStructures;
@@ -48,6 +89,16 @@ public class WorldOptions {
return this.seed;
}
+ // Leaf start - Matter - Secure Seed
+ public long[] featureSeed() {
+ return this.featureSeed;
+ }
+
+ private String featureSeedSerialize() {
+ return gson.toJson(this.featureSeed);
+ }
+ // Leaf end - Matter - Secure Seed
+
public boolean generateStructures() {
return this.generateStructures;
}
@@ -60,17 +111,25 @@ public class WorldOptions {
return this.legacyCustomOptions.isPresent();
}
+ // Leaf start - Matter - Secure Seed
public WorldOptions withBonusChest(final boolean generateBonusChest) {
- return new WorldOptions(this.seed, this.generateStructures, generateBonusChest, this.legacyCustomOptions);
+ return isSecureSeedEnabled
+ ? new WorldOptions(this.seed, this.featureSeed, this.generateStructures, generateBonusChest, this.legacyCustomOptions)
+ : new WorldOptions(this.seed, this.generateStructures, generateBonusChest, this.legacyCustomOptions);
}
public WorldOptions withStructures(final boolean generateStructures) {
- return new WorldOptions(this.seed, generateStructures, this.generateBonusChest, this.legacyCustomOptions);
+ return isSecureSeedEnabled
+ ? new WorldOptions(this.seed, this.featureSeed, generateStructures, this.generateBonusChest, this.legacyCustomOptions)
+ : new WorldOptions(this.seed, generateStructures, this.generateBonusChest, this.legacyCustomOptions);
}
public WorldOptions withSeed(final OptionalLong seed) {
- return new WorldOptions(seed.orElse(randomSeed()), this.generateStructures, this.generateBonusChest, this.legacyCustomOptions);
+ return isSecureSeedEnabled
+ ? new WorldOptions(seed.orElse(randomSeed()), su.plo.matter.Globals.createRandomWorldSeed(), this.generateStructures, this.generateBonusChest, this.legacyCustomOptions)
+ : new WorldOptions(seed.orElse(randomSeed()), this.generateStructures, this.generateBonusChest, this.legacyCustomOptions);
}
+ // Leaf end - Matter - Secure Seed
public static OptionalLong parseSeed(String seedString) {
seedString = seedString.trim();
diff --git a/net/minecraft/world/level/levelgen/feature/GeodeFeature.java b/net/minecraft/world/level/levelgen/feature/GeodeFeature.java
index baed0479a4552676844989868ee4c37ffa344def..bcda97e7439945d2a559e45e33f55ccf7ebe801b 100644
--- a/net/minecraft/world/level/levelgen/feature/GeodeFeature.java
+++ b/net/minecraft/world/level/levelgen/feature/GeodeFeature.java
@@ -43,7 +43,11 @@ public class GeodeFeature extends Feature<GeodeConfiguration> {
int maxGenOffset = config.maxGenOffset();
List<Pair<BlockPos, Integer>> points = Lists.newLinkedList();
int numPoints = config.distributionPoints().sample(random);
- WorldgenRandom random1 = new WorldgenRandom(new LegacyRandomSource(level.getSeed()));
+ // Leaf start - Matter - Secure Seed
+ WorldgenRandom random1 = io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled
+ ? new su.plo.matter.WorldgenCryptoRandom(0, 0, su.plo.matter.Globals.Salt.GEODE_FEATURE, 0)
+ : new WorldgenRandom(new LegacyRandomSource(level.getSeed()));
+ // Leaf end - Matter - Secure Seed
NormalNoise noise = NormalNoise.create(random1, -4, 1.0);
List<BlockPos> crackPoints = Lists.newLinkedList();
double crackSizeAdjustment = (double)numPoints / config.outerWallDistance().maxInclusive();
diff --git a/net/minecraft/world/level/levelgen/structure/Structure.java b/net/minecraft/world/level/levelgen/structure/Structure.java
index f1e13ede1f7345089ece8d8ef391f7fd5e55c445..2bfc339e3301deb0d46a92b1c138ff1abbf5b409 100644
--- a/net/minecraft/world/level/levelgen/structure/Structure.java
+++ b/net/minecraft/world/level/levelgen/structure/Structure.java
@@ -248,6 +248,11 @@ public abstract class Structure {
}
private static WorldgenRandom makeRandom(final long seed, final ChunkPos chunkPos) {
+ // Leaf start - Matter - Secure Seed
+ if (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled) {
+ return new su.plo.matter.WorldgenCryptoRandom(chunkPos.x(), chunkPos.z(), su.plo.matter.Globals.Salt.GENERATE_FEATURE, seed);
+ }
+ // Leaf end - Matter - Secure Seed
WorldgenRandom random = new WorldgenRandom(new LegacyRandomSource(0L));
random.setLargeFeatureSeed(seed, chunkPos.x(), chunkPos.z());
return random;
diff --git a/net/minecraft/world/level/levelgen/structure/placement/RandomSpreadStructurePlacement.java b/net/minecraft/world/level/levelgen/structure/placement/RandomSpreadStructurePlacement.java
index 1310b2ca994b8f6d3d92bdc676fe44de3619cc09..ae55fd5d4b08f00557b384671412ee31b5d1aeef 100644
--- a/net/minecraft/world/level/levelgen/structure/placement/RandomSpreadStructurePlacement.java
+++ b/net/minecraft/world/level/levelgen/structure/placement/RandomSpreadStructurePlacement.java
@@ -67,8 +67,15 @@ public class RandomSpreadStructurePlacement extends StructurePlacement {
public ChunkPos getPotentialStructureChunk(final long seed, final int sourceX, final int sourceZ) {
int spacedGridX = Math.floorDiv(sourceX, this.spacing);
int spacedGridZ = Math.floorDiv(sourceZ, this.spacing);
- WorldgenRandom random = new WorldgenRandom(new LegacyRandomSource(0L));
- random.setLargeFeatureWithSalt(seed, spacedGridX, spacedGridZ, this.salt());
+ // Leaf start - Matter - Secure Seed
+ WorldgenRandom random;
+ if (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled) {
+ random = new su.plo.matter.WorldgenCryptoRandom(spacedGridX, spacedGridZ, su.plo.matter.Globals.Salt.POTENTIONAL_FEATURE, this.salt);
+ } else {
+ random = new WorldgenRandom(new LegacyRandomSource(0L));
+ random.setLargeFeatureWithSalt(seed, spacedGridX, spacedGridZ, this.salt());
+ }
+ // Leaf end - Matter - Secure Seed
int limit = this.spacing - this.separation;
int spreadX = this.spreadType.evaluate(random, limit);
int spreadZ = this.spreadType.evaluate(random, limit);
diff --git a/net/minecraft/world/level/levelgen/structure/placement/StructurePlacement.java b/net/minecraft/world/level/levelgen/structure/placement/StructurePlacement.java
index 646df0237a5a2863f75e6c5f9dfe9ddf512c540f..3fddb11c1bd0277d878d90d0dae8e5ed8a42556a 100644
--- a/net/minecraft/world/level/levelgen/structure/placement/StructurePlacement.java
+++ b/net/minecraft/world/level/levelgen/structure/placement/StructurePlacement.java
@@ -137,8 +137,16 @@ public abstract class StructurePlacement {
}
private static boolean legacyArbitrarySaltProbabilityReducer(final long seed, final int salt, final int sourceX, final int sourceZ, final float probability, final @org.jspecify.annotations.Nullable Integer saltOverride) { // Paper - Add missing structure set seed configs
- WorldgenRandom random = new WorldgenRandom(new LegacyRandomSource(0L));
- random.setLargeFeatureWithSalt(seed, sourceX, sourceZ, saltOverride != null ? saltOverride : HIGHLY_ARBITRARY_RANDOM_SALT); // Paper - Add missing structure set seed configs
+ // Leaf start - Matter - Secure Seed
+ WorldgenRandom random;
+ if (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled) {
+ random = new su.plo.matter.WorldgenCryptoRandom(sourceX, sourceZ, su.plo.matter.Globals.Salt.UNDEFINED, saltOverride != null ? saltOverride : HIGHLY_ARBITRARY_RANDOM_SALT);
+ } else {
+ random = new WorldgenRandom(new LegacyRandomSource(0L));
+ random.setLargeFeatureWithSalt(seed, sourceX, sourceZ, saltOverride != null ? saltOverride : HIGHLY_ARBITRARY_RANDOM_SALT); // Paper - Add missing structure set seed configs
+ }
+ // Leaf end - Matter - Secure Seed
+
return random.nextFloat() < probability;
}
diff --git a/net/minecraft/world/level/levelgen/structure/pools/JigsawPlacement.java b/net/minecraft/world/level/levelgen/structure/pools/JigsawPlacement.java
index b92da7acae0789d955a9f71072b95ed030b879e2..2c81e8e7dd0380233b0f17e3d83ff704335dad53 100644
--- a/net/minecraft/world/level/levelgen/structure/pools/JigsawPlacement.java
+++ b/net/minecraft/world/level/levelgen/structure/pools/JigsawPlacement.java
@@ -64,7 +64,11 @@ public class JigsawPlacement {
ChunkGenerator chunkGenerator = context.chunkGenerator();
StructureTemplateManager structureTemplateManager = context.structureTemplateManager();
LevelHeightAccessor heightAccessor = context.heightAccessor();
- WorldgenRandom random = context.random();
+ // Leaf start - Matter - Secure Seed
+ WorldgenRandom random = io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled
+ ? new su.plo.matter.WorldgenCryptoRandom(context.chunkPos().x(), context.chunkPos().z(), su.plo.matter.Globals.Salt.JIGSAW_PLACEMENT, 0)
+ : context.random();
+ // Leaf end - Matter - Secure Seed
Registry<StructureTemplatePool> pools = registryAccess.lookupOrThrow(Registries.TEMPLATE_POOL);
Rotation centerRotation = Rotation.getRandom(random);
StructureTemplatePool centerPool = startPool.unwrapKey()
@@ -0,0 +1,70 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Libalpm64 <libalpm@proton.me>
Date: Mon, 2 Mar 2026 00:00:00 +0000
Subject: [PATCH] Secure seed V2 with Blake3
diff --git a/net/minecraft/world/level/levelgen/RandomState.java b/net/minecraft/world/level/levelgen/RandomState.java
index 7b74440fbbe79c018ad59d24b99da0c6d4a9d007..20536f4ed6d19ec2cc6a54aa9c5c980d2ffea0ef 100644
--- a/net/minecraft/world/level/levelgen/RandomState.java
+++ b/net/minecraft/world/level/levelgen/RandomState.java
@@ -33,10 +33,28 @@ public final class RandomState {
}
private RandomState(final NoiseGeneratorSettings settings, final HolderGetter<NormalNoise.NoiseParameters> noises, final long seed) {
- this.random = settings.getRandomSource().newInstance(seed).forkPositional();
+ // this.random = settings.getRandomSource().newInstance(seed).forkPositional(); // Shiroha - Add secure seed V2 with Blake3
+ // Shiroha start - Add secure seed V2 with Blake3
+ final long[] secureWorldSeed = (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled && io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.version == 2)
+ ? su.plo.matter.HashingV2.expandLevelSeedTo1024Bits(seed)
+ : null;
+
+ long terrainSeed = (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled && io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.version == 2)
+ ? su.plo.matter.HashingV2.getTerrainSeed(secureWorldSeed, su.plo.matter.HashingV2.TerrainType.BASE_TERRAIN)
+ : seed;
+ long aquiferSeed = (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled && io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.version == 2)
+ ? su.plo.matter.HashingV2.getTerrainSeed(secureWorldSeed, su.plo.matter.HashingV2.TerrainType.AQUIFER)
+ : seed;
+ long oreSeed = (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled && io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.version == 2)
+ ? su.plo.matter.HashingV2.getTerrainSeed(secureWorldSeed, su.plo.matter.HashingV2.TerrainType.ORE)
+ : seed;
+ // Shiroha end
+ this.random = settings.getRandomSource().newInstance(terrainSeed).forkPositional(); // Shiroha - Add secure seed V2 with Blake3
this.noises = noises;
- this.aquiferRandom = this.random.fromHashOf(Identifier.withDefaultNamespace("aquifer")).forkPositional();
- this.oreRandom = this.random.fromHashOf(Identifier.withDefaultNamespace("ore")).forkPositional();
+ //this.aquiferRandom = this.random.fromHashOf(Identifier.withDefaultNamespace("aquifer")).forkPositional(); // Shiroha - Add secure seed V2 with Blake3
+ //this.oreRandom = this.random.fromHashOf(Identifier.withDefaultNamespace("ore")).forkPositional(); // Shiroha - Add secure seed V2 with Blake3
+ this.aquiferRandom = settings.getRandomSource().newInstance(aquiferSeed).forkPositional(); // Shiroha - Add secure seed V2 with Blake3
+ this.oreRandom = settings.getRandomSource().newInstance(oreSeed).forkPositional(); // Shiroha - Add secure seed V2 with Blake3
this.noiseIntances = new ConcurrentHashMap<>();
this.positionalRandoms = new ConcurrentHashMap<>();
this.surfaceSystem = new SurfaceSystem(this, settings.defaultBlock(), settings.seaLevel(), this.random);
@@ -46,6 +64,12 @@ public final class RandomState {
private final Map<DensityFunction, DensityFunction> wrapped = new HashMap<>();
private RandomSource newLegacyInstance(final long seedOffset) {
+ // Shiroha start - Add secure seed V2 with Blake3
+ if (io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled && io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.version == 2) {
+ long climateSeed = su.plo.matter.HashingV2.getTerrainSeed(secureWorldSeed, su.plo.matter.HashingV2.TerrainType.CLIMATE);
+ return new su.plo.matter.WorldgenCryptoRandom(0, 0, su.plo.matter.Globals.Salt.UNDEFINED, climateSeed + seed);
+ }
+ // Shiroha end
return new LegacyRandomSource(seed + seedOffset);
}
@@ -71,7 +95,13 @@ public final class RandomState {
: RandomState.this.random.fromHashOf(Identifier.withDefaultNamespace("terrain"));
return noise.withNewRandom(terrainRandom);
} else {
- return function instanceof DensityFunctions.EndIslandDensityFunction ? new DensityFunctions.EndIslandDensityFunction(seed) : function;
+ return function instanceof DensityFunctions.EndIslandDensityFunction //? new DensityFunctions.EndIslandDensityFunction(seed)// Shiroha - Add secure seed V2 with Blake3
+ // Shiroha start - Add secure seed V2 with Blake3
+ ? new DensityFunctions.EndIslandDensityFunction((io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.enabled && io.nanachiyo0721.shiroha.config.modules.function.SecureSeedConfig.version == 2)
+ ? su.plo.matter.HashingV2.getTerrainSeed(secureWorldSeed, su.plo.matter.HashingV2.TerrainType.SURFACE)
+ : seed)
+ // Shiroha end
+ : function;
}
}
@@ -0,0 +1,34 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 18 Apr 2026 12:27:21 +0800
Subject: [PATCH] Leaf: Replace brain maps with optimized collection
Co-authored by: HaHaWTH <102713261+HaHaWTH@users.noreply.github.com>
As part of: Leaf (https://github.com/Winds-Studio/Leaf/blob/7f3e240bbe0970683c40279a7a65f0fde47503b6/leaf-server/minecraft-patches/features/0070-Replace-brain-maps-with-optimized-collection.patch)
Licensed under: MIT (https://github.com/Winds-Studio/Leaf/blob/7f3e240bbe0970683c40279a7a65f0fde47503b6/licenses/MIT.txt)
diff --git a/net/minecraft/world/entity/ai/Brain.java b/net/minecraft/world/entity/ai/Brain.java
index 977a31f995799cf44fa59cc1db73571edbcf36ff..ba28111819aacc30b410763adffc4d4dd2b545d4 100644
--- a/net/minecraft/world/entity/ai/Brain.java
+++ b/net/minecraft/world/entity/ai/Brain.java
@@ -37,14 +37,14 @@ import org.jspecify.annotations.Nullable;
public class Brain<E extends LivingEntity> {
private static final int SCHEDULE_UPDATE_DELAY = 20;
- private final Map<MemoryModuleType<?>, MemorySlot<?>> memories = Maps.newHashMap();
- private final Map<SensorType<? extends Sensor<? super E>>, Sensor<? super E>> sensors = Maps.newLinkedHashMap();
+ private final Map<MemoryModuleType<?>, MemorySlot<?>> memories = new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<>(); // Leaf - Replace brain maps with optimized collection
+ private final Map<SensorType<? extends Sensor<? super E>>, Sensor<? super E>> sensors = new it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap<>(); // Leaf - Replace brain maps with optimized collection
private final Map<Integer, Map<Activity, Set<BehaviorControl<? super E>>>> availableBehaviorsByPriority = Maps.newTreeMap();
private @Nullable EnvironmentAttribute<Activity> schedule;
- private final Map<Activity, Set<Pair<MemoryModuleType<?>, MemoryStatus>>> activityRequirements = Maps.newHashMap();
- private final Map<Activity, Set<MemoryModuleType<?>>> activityMemoriesToEraseWhenStopped = Maps.newHashMap();
- private Set<Activity> coreActivities = Sets.newHashSet();
- private final Set<Activity> activeActivities = Sets.newHashSet();
+ private final Map<Activity, Set<Pair<MemoryModuleType<?>, MemoryStatus>>> activityRequirements = new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<>(); // Leaf - Replace brain maps with optimized collection
+ private final Map<Activity, Set<MemoryModuleType<?>>> activityMemoriesToEraseWhenStopped = new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<>(); // Leaf - Replace brain maps with optimized collection
+ private Set<Activity> coreActivities = new it.unimi.dsi.fastutil.objects.ObjectOpenHashSet<>(); // Leaf - Replace brain maps with optimized collection
+ private final Set<Activity> activeActivities = new it.unimi.dsi.fastutil.objects.ObjectOpenHashSet<>(); // Leaf - Replace brain maps with optimized collection
private Activity defaultActivity = Activity.IDLE;
private long lastScheduleUpdate = -9999L;
@@ -0,0 +1,54 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Sun, 28 Jun 2026 20:51:53 +0800
Subject: [PATCH] Leaf: Remove useless creating stats json bases on player name
logic
Co-authored by: Dreeam <61569423+Dreeam-qwq@users.noreply.github.com>
As part of: Leaf (https://github.com/Winds-Studio/Leaf/blob/7f3e240bbe0970683c40279a7a65f0fde47503b6/leaf-server/minecraft-patches/features/0043-Remove-useless-creating-stats-json-bases-on-player-n.patch)
Licensed under: MIT (https://github.com/Winds-Studio/Leaf/blob/7f3e240bbe0970683c40279a7a65f0fde47503b6/licenses/MIT.txt)
diff --git a/net/minecraft/server/players/PlayerList.java b/net/minecraft/server/players/PlayerList.java
index 9e90197b96fcac958c5073ca8f560e77bb811460..134d74d8ed2c61b28cda0bd5107dea88bc114f51 100644
--- a/net/minecraft/server/players/PlayerList.java
+++ b/net/minecraft/server/players/PlayerList.java
@@ -1294,22 +1294,26 @@ public abstract class PlayerList {
Path uuidStatsFile = statFolder.resolve(gameProfile.id() + ".json");
if (Files.exists(uuidStatsFile)) {
return uuidStatsFile;
- }
-
- String playerNameStatsFile = gameProfile.name() + ".json";
- if (FileUtil.isValidPathSegment(playerNameStatsFile)) {
- Path playerNameStatsPath = statFolder.resolve(playerNameStatsFile);
- if (Files.isRegularFile(playerNameStatsPath)) {
- try {
- return Files.move(playerNameStatsPath, uuidStatsFile);
- } catch (IOException e) {
- LOGGER.warn("Failed to copy file {} to {}", playerNameStatsFile, uuidStatsFile);
- return playerNameStatsPath;
+ } else {
+ // Leaf start - Remove useless creating stats json bases on player name logic
+ /*
+ String playerNameStatsFile = gameProfile.name() + ".json";
+ if (FileUtil.isValidPathSegment(playerNameStatsFile)) {
+ Path playerNameStatsPath = statFolder.resolve(playerNameStatsFile);
+ if (Files.isRegularFile(playerNameStatsPath)) {
+ try {
+ return Files.move(playerNameStatsPath, uuidStatsFile);
+ } catch (IOException e) {
+ LOGGER.warn("Failed to copy file {} to {}", playerNameStatsFile, uuidStatsFile);
+ return playerNameStatsPath;
+ }
}
}
- }
+ */
+ // Leaf end - Remove useless creating stats json bases on player name logic
- return uuidStatsFile;
+ return uuidStatsFile;
+ }
}
public PlayerAdvancements getPlayerAdvancements(final ServerPlayer player) {
@@ -0,0 +1,36 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 2 May 2026 22:26:57 +0800
Subject: [PATCH] Leaf Optimize PatchedDataComponentMap equals
This is a part of Leaf(https://github.com/Winds-Studio/Leaf/blob/db41340915c7768d726342fb29d16bc428081074/leaf-server/minecraft-patches/features/0300-Optimize-PatchedDataComponentMap-equals.patch)
Original author: HaHaWTH <102713261+HaHaWTH@users.noreply.github.com>
Original license: https://github.com/Winds-Studio/Leaf/blob/db41340915c7768d726342fb29d16bc428081074/LICENSE.md
diff --git a/net/minecraft/core/component/PatchedDataComponentMap.java b/net/minecraft/core/component/PatchedDataComponentMap.java
index e59250af5d769076578017fb880e9168bc720947..ae355b2d92090e89ab4671ff13f77d632e7dfcf9 100644
--- a/net/minecraft/core/component/PatchedDataComponentMap.java
+++ b/net/minecraft/core/component/PatchedDataComponentMap.java
@@ -222,7 +222,19 @@ public final class PatchedDataComponentMap implements DataComponentMap, org.leav
@Override
public boolean equals(final Object obj) {
- return this == obj || obj instanceof PatchedDataComponentMap otherMap && this.prototype.equals(otherMap.prototype) && this.patch.equals(otherMap.patch);
+ // return this == obj || obj instanceof PatchedDataComponentMap otherMap && this.prototype.equals(otherMap.prototype) && this.patch.equals(otherMap.patch); // Leaf - Optimize PatchedDataComponentMap equals
+ // Leaf start - Optimize PatchedDataComponentMap equals
+ if (this == obj) return true;
+ if (!(obj instanceof PatchedDataComponentMap that)) return false;
+ if (this.patch.size() != that.patch.size()) {
+ return false;
+ }
+ if (!this.prototype.equals(that.prototype)) {
+ return false;
+ }
+ if (this.patch == that.patch) return true;
+ return this.patch.equals(that.patch);
+ // Leaf end - Optimize PatchedDataComponentMap equals
}
@Override
@@ -0,0 +1,53 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Mon, 4 May 2026 13:44:05 +0800
Subject: [PATCH] Leaf Better checking for useless move packets
A part of leaf(https://github.com/Winds-Studio/Leaf/blob/b794fca6080c47ff305b6d065a579171b1fe1e98/leaf-server/minecraft-patches/features/0018-Better-checking-for-useless-move-packets.patch)
Original license: https://github.com/Winds-Studio/Leaf/blob/b794fca6080c47ff305b6d065a579171b1fe1e98/LICENSE.md
diff --git a/net/minecraft/server/level/ServerEntity.java b/net/minecraft/server/level/ServerEntity.java
index 60af82925d2f7e605bf7340cf01f1a5668f4d725..2e71a1cbabf3405e3e4fd5349a1784d895e7e60c 100644
--- a/net/minecraft/server/level/ServerEntity.java
+++ b/net/minecraft/server/level/ServerEntity.java
@@ -186,18 +186,35 @@ public class ServerEntity {
packet = ClientboundEntityPositionSyncPacket.of(this.entity);
sentPosition = true;
sentRotation = true;
- } else if ((!pos || !shouldSendRotation) && !(this.entity instanceof AbstractArrow)) {
+ /*} else if ((!pos || !shouldSendRotation) && !(this.entity instanceof AbstractArrow)) { // Gale - Airplane - better checking for useless move packets
if (pos) {
packet = new ClientboundMoveEntityPacket.Pos(this.entity.getId(), (short)xa, (short)ya, (short)za, this.entity.onGround());
sentPosition = true;
} else if (shouldSendRotation) {
packet = new ClientboundMoveEntityPacket.Rot(this.entity.getId(), yRotn, xRotn, this.entity.onGround());
sentRotation = true;
- }
+ }*/ // Gale - Airplane - better checking for useless move packets
} else {
- packet = new ClientboundMoveEntityPacket.PosRot(this.entity.getId(), (short)xa, (short)ya, (short)za, yRotn, xRotn, this.entity.onGround());
+ /*packet = new ClientboundMoveEntityPacket.PosRot(this.entity.getId(), (short)xa, (short)ya, (short)za, yRotn, xRotn, this.entity.onGround()); // Gale - Airplane - better checking for useless move packets
sentPosition = true;
- sentRotation = true;
+ sentRotation = true;*/ // Gale - Airplane - better checking for useless move packets
+ // Gale start - Airplane - better checking for useless move packets
+ if (pos || shouldSendRotation || this.entity instanceof AbstractArrow) {
+ if ((!pos || !shouldSendRotation) && !(this.entity instanceof AbstractArrow)) {
+ if (pos) {
+ packet = new ClientboundMoveEntityPacket.Pos(this.entity.getId(), (short) xa, (short) ya, (short) za, this.entity.onGround());
+ sentPosition = true;
+ } else if (shouldSendRotation) {
+ packet = new ClientboundMoveEntityPacket.Rot(this.entity.getId(), yRotn, xRotn, this.entity.onGround());
+ sentRotation = true;
+ }
+ } else {
+ packet = new ClientboundMoveEntityPacket.PosRot(this.entity.getId(), (short) xa, (short) ya, (short) za, yRotn, xRotn, this.entity.onGround());
+ sentPosition = true;
+ sentRotation = true;
+ }
+ }
+ // Gale end - Airplane - better checking for useless move packets
}
if (this.entity.needsSync || this.trackDelta || this.entity instanceof LivingEntity livingEntity && livingEntity.isFallFlying()) {
@@ -0,0 +1,70 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sun, 17 May 2026 10:10:21 +0800
Subject: [PATCH] Leaf fast bit radix sort
This is a part of Leaf(https://github.com/Winds-Studio/Leaf/blob/d0ed97cf45dfa94f686ef32f0eea1ec7323f78d5/leaf-server/minecraft-patches/features/0284-fast-bit-radix-sort.patch)
Original license: https://github.com/Winds-Studio/Leaf/blob/d0ed97cf45dfa94f686ef32f0eea1ec7323f78d5/LICENSE.md
diff --git a/io/papermc/paper/threadedregions/RegionizedWorldData.java b/io/papermc/paper/threadedregions/RegionizedWorldData.java
index fc5161a77a4a846888c564123265a669188646b5..be8f0b5bc26c8384ea027a90e3ab0cdc8f9411fb 100644
--- a/io/papermc/paper/threadedregions/RegionizedWorldData.java
+++ b/io/papermc/paper/threadedregions/RegionizedWorldData.java
@@ -530,6 +530,7 @@ public final class RegionizedWorldData {
public final PathTypeCache pathTypesByPosCache = new PathTypeCache();
public final List<LevelChunk> temporaryChunkTickList = new java.util.ArrayList<>();
public final Set<ChunkHolder> chunkHoldersToBroadcast = new ReferenceLinkedOpenHashSet<>();
+ public final org.dreeam.leaf.util.FastBitRadixSort radixBitSorter = new org.dreeam.leaf.util.FastBitRadixSort(); // Leaf - quick sort
// not transient
public java.util.ArrayDeque<net.minecraft.world.level.block.RedstoneTorchBlock.Toggle> redstoneUpdateInfos;
diff --git a/net/minecraft/world/entity/ai/sensing/NearestItemSensor.java b/net/minecraft/world/entity/ai/sensing/NearestItemSensor.java
index 8aeea55380462421cde43afb4b2fb0ce44b65195..73247b46d778dcb9b3be742e4e4c4c037e3ac0e5 100644
--- a/net/minecraft/world/entity/ai/sensing/NearestItemSensor.java
+++ b/net/minecraft/world/entity/ai/sensing/NearestItemSensor.java
@@ -15,6 +15,7 @@ public class NearestItemSensor extends Sensor<Mob> {
private static final long XZ_RANGE = 32L;
private static final long Y_RANGE = 16L;
public static final int MAX_DISTANCE_TO_WANTED_ITEM = 32;
+ private static final double MAX_DIST_SQ = (double) MAX_DISTANCE_TO_WANTED_ITEM * MAX_DISTANCE_TO_WANTED_ITEM; // Leaf - quick sort
@Override
public Set<MemoryModuleType<?>> requires() {
@@ -24,8 +25,16 @@ public class NearestItemSensor extends Sensor<Mob> {
@Override
protected void doTick(final ServerLevel level, final Mob body) {
Brain<?> brain = body.getBrain();
- List<ItemEntity> items = level.getEntitiesOfClass(ItemEntity.class, body.getBoundingBox().inflate(32.0, 16.0, 32.0), item -> item.closerThan(body, MAX_DISTANCE_TO_WANTED_ITEM) && body.wantsToPickUp(level, item.getItem())); // Paper - Perf: Move predicate into getEntities
- items.sort(Comparator.comparingDouble(body::distanceToSqr));
+ // Leaf start - fast bit radix sort
+ net.minecraft.core.Position pos = body.position();
+ double x = pos.x();
+ double y = pos.y();
+ double z = pos.z();
+ net.minecraft.world.phys.AABB boundingBox = body.getBoundingBox().inflate(32.0, 16.0, 32.0);
+ it.unimi.dsi.fastutil.objects.ObjectArrayList<ItemEntity> items = new it.unimi.dsi.fastutil.objects.ObjectArrayList<>();
+ ((ca.spottedleaf.moonrise.patches.chunk_system.level.ChunkSystemLevel) level).moonrise$getEntityLookup().getEntities(ItemEntity.class, null, boundingBox, items, (ItemEntity itemEntity) -> itemEntity.distanceToSqr(x, y, z) < MAX_DIST_SQ && body.wantsToPickUp(level, itemEntity.getItem())); // Paper - Perf: Move predicate into getEntities
+ level.getCurrentWorldData().radixBitSorter.sort(items.elements(), items.size(), pos);
+ // Leaf end - fast bit radix sort
// Paper start - Perf: remove streams from hot code
ItemEntity nearest = null;
for (final ItemEntity item : items) {
diff --git a/net/minecraft/world/entity/ai/sensing/NearestLivingEntitySensor.java b/net/minecraft/world/entity/ai/sensing/NearestLivingEntitySensor.java
index 3578ece216827fd5d8c1206c689fc608e97b50df..9fbe439663edf57e018369a44ed7576d947d1fbc 100644
--- a/net/minecraft/world/entity/ai/sensing/NearestLivingEntitySensor.java
+++ b/net/minecraft/world/entity/ai/sensing/NearestLivingEntitySensor.java
@@ -17,8 +17,11 @@ public class NearestLivingEntitySensor<T extends LivingEntity> extends Sensor<T>
protected void doTick(final ServerLevel level, final T body) {
double followRange = body.getAttributeValue(Attributes.FOLLOW_RANGE);
AABB boundingBox = body.getBoundingBox().inflate(followRange, followRange, followRange);
- List<LivingEntity> livingEntities = level.getEntitiesOfClass(LivingEntity.class, boundingBox, mob -> mob != body && mob.isAlive());
- livingEntities.sort(Comparator.comparingDouble(body::distanceToSqr));
+ // Leaf start - fast bit radix sort
+ it.unimi.dsi.fastutil.objects.ObjectArrayList<LivingEntity> livingEntities = new it.unimi.dsi.fastutil.objects.ObjectArrayList<>();
+ ((ca.spottedleaf.moonrise.patches.chunk_system.level.ChunkSystemLevel) level).moonrise$getEntityLookup().getEntities(LivingEntity.class, body, boundingBox, livingEntities, LivingEntity::isAlive);
+ level.getCurrentWorldData().radixBitSorter.sort(livingEntities.elements(), livingEntities.size(), body.position());
+ // Leaf end - fast bit radix sort
Brain<?> brain = body.getBrain();
brain.setMemory(MemoryModuleType.NEAREST_LIVING_ENTITIES, livingEntities);
brain.setMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES, new NearestVisibleLivingEntities(level, body, livingEntities));
@@ -0,0 +1,203 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 27 Jun 2026 17:23:22 +0800
Subject: [PATCH] Leaf Configurable vanilla username check
A part of Leaf(https://github.com/Winds-Studio/Leaf/blob/edb0504069139beaa6f39efa4702370c2576b3fc/leaf-server/minecraft-patches/features/0086-Configurable-vanilla-username-check.patch)
License: https://github.com/Winds-Studio/Leaf/blob/edb0504069139beaa6f39efa4702370c2576b3fc/LICENSE.md
diff --git a/net/minecraft/server/MinecraftServer.java b/net/minecraft/server/MinecraftServer.java
index ab8d69fa54203175760d394a5425601073fcd0d9..6d5beffa1a771182d717f2baab5c626b4970c203 100644
--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -217,7 +217,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
public static final NameAndId ANONYMOUS_PLAYER_PROFILE = new NameAndId(Util.NIL_UUID, "Anonymous Player");
public static final String SERVER_THREAD_NAME = "Server thread";
public LevelStorageSource.LevelStorageAccess storageSource;
- protected final PlayerDataStorage playerDataStorage;
+ public final PlayerDataStorage playerDataStorage;
private final SavedDataStorage savedDataStorage;
private final List<Runnable> tickables = Lists.newArrayList();
// Paper - per-level GameRules
diff --git a/net/minecraft/server/network/ServerLoginPacketListenerImpl.java b/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
index 7de3bbecea2f11e4e1cb65408729f346760dc9b8..b72b81849c7fedad8efc5c7b112e89eb01dc74dd 100644
--- a/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
@@ -167,11 +167,20 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener,
public void handleHello(final ServerboundHelloPacket packet) {
Validate.validState(this.state == ServerLoginPacketListenerImpl.State.HELLO, "Unexpected hello packet");
// Paper start - Validate usernames
- if (io.papermc.paper.configuration.GlobalConfiguration.get().proxies.isProxyOnlineMode()
+ // Leaf start - Configurable vanilla username check
+ boolean allPrevChecksPassed;
+ if (io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.enabled
+ && io.papermc.paper.configuration.GlobalConfiguration.get().proxies.isProxyOnlineMode()
&& io.papermc.paper.configuration.GlobalConfiguration.get().unsupportedSettings.performUsernameValidation
&& !this.iKnowThisMayNotBeTheBestIdeaButPleaseDisableUsernameValidation) {
- Validate.validState(StringUtil.isReasonablePlayerName(packet.name()), "Invalid characters in username");
+ allPrevChecksPassed = true;
+ if (!io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.allowOldPlayersJoin) {
+ Validate.validState(StringUtil.isReasonablePlayerName(packet.name()), "Invalid characters in username");
+ }
+ } else {
+ allPrevChecksPassed = false;
}
+ // Leaf end - Configurable vanilla username check
this.requestedUuid = packet.profileId();
// Paper end - Validate usernames
this.requestedUsername = packet.name();
@@ -197,6 +206,15 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener,
authenticatorPool.execute(() -> {
try {
GameProfile gameprofile = ServerLoginPacketListenerImpl.this.createOfflineProfile(ServerLoginPacketListenerImpl.this.requestedUsername); // Spigot
+ // Leaf start - Configurable vanilla username check
+ if (io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.allowOldPlayersJoin) {
+ if (server.playerDataStorage.load(new net.minecraft.server.players.NameAndId(gameprofile)).orElse(null) != null) {
+ server.getPlayerList().playedPlayers.add(packet.name());
+ } else if (allPrevChecksPassed) {
+ Validate.validState(StringUtil.isReasonablePlayerName(packet.name()), "Invalid characters in username");
+ }
+ }
+ // Leaf end - Configurable vanilla username check
gameprofile = ServerLoginPacketListenerImpl.this.callPlayerPreLoginEvents(gameprofile); // Paper - Add more fields to AsyncPlayerPreLoginEvent
ServerLoginPacketListenerImpl.LOGGER.info("UUID of player {} is {}", gameprofile.name(), gameprofile.id());
@@ -341,7 +359,7 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener,
server.getPluginManager().callEvent(asyncEvent);
profile = asyncEvent.getPlayerProfile();
profile.complete(true); // Paper - setPlayerProfileAPI
- gameprofile = com.destroystokyo.paper.profile.CraftPlayerProfile.asAuthlibCopy(profile);
+ gameprofile = com.destroystokyo.paper.profile.CraftPlayerProfile.asAuthlibCopyCustomValidation(profile); // Leaf - Configurable vanilla username check
playerName = gameprofile.name();
uniqueId = gameprofile.id();
// Paper end - Add more fields to AsyncPlayerPreLoginEvent
diff --git a/net/minecraft/server/players/CachedUserNameToIdResolver.java b/net/minecraft/server/players/CachedUserNameToIdResolver.java
index 7443744e3f256983e52a1cefcaf66082e4a46a7b..b7553611723f7120c66e1f3e51d89df28bd2756b 100644
--- a/net/minecraft/server/players/CachedUserNameToIdResolver.java
+++ b/net/minecraft/server/players/CachedUserNameToIdResolver.java
@@ -67,7 +67,7 @@ public class CachedUserNameToIdResolver implements UserNameToIdResolver {
}
private Optional<NameAndId> lookupGameProfile(final GameProfileRepository profileRepository, final String name) {
- if (!StringUtil.isValidPlayerName(name)) {
+ if (!StringUtil.isValidPlayerName(name, false)) { // Leaf - Configurable vanilla username check - Directly return, skip unnecessary following logic
return this.createUnknownProfile(name);
}
diff --git a/net/minecraft/server/players/PlayerList.java b/net/minecraft/server/players/PlayerList.java
index 134d74d8ed2c61b28cda0bd5107dea88bc114f51..0392962ed409e3f970904de05926c356610f0e4c 100644
--- a/net/minecraft/server/players/PlayerList.java
+++ b/net/minecraft/server/players/PlayerList.java
@@ -134,6 +134,7 @@ public abstract class PlayerList {
private org.bukkit.craftbukkit.CraftServer cserver;
private final Map<String,ServerPlayer> playersByName = new java.util.HashMap<>();
public @Nullable String collideRuleTeamName; // Paper - Configurable player collision
+ public final List<String> playedPlayers = new java.util.concurrent.CopyOnWriteArrayList<>(); // Leaf - Configurable vanilla username check
// Folia start - region threading
private final Object connectionsStateLock = new Object();
@@ -581,6 +582,7 @@ public abstract class PlayerList {
player.getAdvancements().clearTriggers();
this.players.remove(player);
this.playersByName.remove(player.getScoreboardName().toLowerCase(java.util.Locale.ROOT)); // Spigot
+ if (io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.allowOldPlayersJoin) this.playedPlayers.remove(player.getGameProfile().name()); // Leaf - Configurable vanilla username check
this.server.getCustomBossEvents().onPlayerDisconnect(player);
UUID uuid = player.getUUID();
ServerPlayer serverPlayer = this.playersByUUID.get(uuid);
diff --git a/net/minecraft/util/StringUtil.java b/net/minecraft/util/StringUtil.java
index 7957e0cfc43909c5268698a11c4933d20b4d9155..1cee7f26a5cd55b146b89da5912952d16269d77e 100644
--- a/net/minecraft/util/StringUtil.java
+++ b/net/minecraft/util/StringUtil.java
@@ -64,6 +64,15 @@ public class StringUtil {
}
public static boolean isValidPlayerName(final String name) {
+ // Leaf start - Configurable vanilla username check
+ return isValidPlayerName(name, io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.shouldSkipNonPlayerNameCheck());
+ }
+ public static boolean isValidPlayerNameVanilla(final String name) {
+ return name.length() <= 16 && name.chars().filter(i -> i <= 32 || i >= 127).findAny().isEmpty();
+ }
+ public static boolean isValidPlayerName(final String name, final boolean bypassCheck) {
+ if (bypassCheck) return name.length() <= 16;
+ // Leaf end - Configurable vanilla username check
return name.length() <= 16 && name.chars().filter(c -> c <= 32 || c >= 127).findAny().isEmpty();
}
@@ -87,6 +96,12 @@ public class StringUtil {
// Paper start - Username validation
public static boolean isReasonablePlayerName(final String name) {
+ // Leaf start - Configurable vanilla username check
+ if (io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.allowOldPlayersJoin && net.minecraft.server.MinecraftServer.getServer().getPlayerList().playedPlayers.contains(name)) return true;
+ if (io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.useCustomUsernameRegex()) {
+ return io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.usernameRegex.matcher(name).matches() && name.length() <= 16; // Leaf - Configurable username check
+ }
+ // Leaf end - Configurable vanilla username check
if (name.isEmpty() || name.length() > 16) {
return false;
}
diff --git a/net/minecraft/world/item/component/ResolvableProfile.java b/net/minecraft/world/item/component/ResolvableProfile.java
index f1b62a6e0d8176d8ba1875e78cc730ee55b1b0c1..c0329b8304cce7ecfe53b102027f73bf4bbf64de 100644
--- a/net/minecraft/world/item/component/ResolvableProfile.java
+++ b/net/minecraft/world/item/component/ResolvableProfile.java
@@ -68,6 +68,30 @@ public abstract sealed class ResolvableProfile implements TooltipProvider permit
public abstract Either<GameProfile, ResolvableProfile.Partial> unpack();
+ // Leaf start - Configurable vanilla username check - Enforce skull validation
+ private static Either<String, UUID> sanitizeDynamicPlayerName(final Either<String, UUID> nameOrId) {
+ if (nameOrId.left().isEmpty()) {
+ return nameOrId;
+ }
+ return io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.enforceSkullValidation && !net.minecraft.util.StringUtil.isValidPlayerNameVanilla(nameOrId.left().get()) ? Either.left("INVALID_OWNER") : nameOrId;
+ }
+
+ private static Optional<String> sanitizePartialPlayerName(final Optional<String> name) {
+ if (name.isEmpty()) {
+ return name;
+ }
+ return io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.enforceSkullValidation && !net.minecraft.util.StringUtil.isValidPlayerNameVanilla(name.get()) ? Optional.of("INVALID_OWNER") : name;
+ }
+
+ private static Either<GameProfile, ResolvableProfile.Partial> sanitizeStaticPlayerName(final Either<GameProfile, ResolvableProfile.Partial> contents) {
+ if (contents.left().isEmpty()) {
+ return contents;
+ }
+ GameProfile gameProfile = contents.left().get();
+ return io.nanachiyo0721.shiroha.config.modules.misc.UsernameCheckConfig.enforceSkullValidation && !net.minecraft.util.StringUtil.isValidPlayerNameVanilla(gameProfile.name()) ? Either.left(new GameProfile(gameProfile.id(), "INVALID_OWNER", gameProfile.properties())) : contents;
+ }
+ // Leaf end - Configurable vanilla username check - Enforce skull validation
+
protected ResolvableProfile(final GameProfile partialProfile, final PlayerSkin.Patch skinPatch) {
this.partialProfile = partialProfile;
this.skinPatch = skinPatch;
@@ -96,6 +120,7 @@ public abstract sealed class ResolvableProfile implements TooltipProvider permit
private final Either<String, UUID> nameOrId;
public Dynamic(final Either<String, UUID> nameOrId, final PlayerSkin.Patch skinPatch) {
+ sanitizeDynamicPlayerName(nameOrId); // Leaf - Configurable vanilla username check
super(ResolvableProfile.createPartialProfile(nameOrId.left(), nameOrId.right(), PropertyMap.EMPTY), skinPatch);
this.nameOrId = nameOrId;
}
@@ -135,6 +160,11 @@ public abstract sealed class ResolvableProfile implements TooltipProvider permit
}
public record Partial(Optional<String> name, Optional<UUID> id, PropertyMap properties) {
+ // Leaf start - Configurable vanilla username check
+ public Partial {
+ name = ResolvableProfile.sanitizePartialPlayerName(name);
+ }
+ // Leaf end - Configurable vanilla username check
public static final ResolvableProfile.Partial EMPTY = new ResolvableProfile.Partial(Optional.empty(), Optional.empty(), PropertyMap.EMPTY);
public static final MapCodec<ResolvableProfile.Partial> MAP_CODEC = RecordCodecBuilder.mapCodec(
i -> i.group(
@@ -165,6 +195,7 @@ public abstract sealed class ResolvableProfile implements TooltipProvider permit
private final Either<GameProfile, ResolvableProfile.Partial> contents;
public Static(final Either<GameProfile, ResolvableProfile.Partial> contents, final PlayerSkin.Patch skinPatch) {
+ sanitizeStaticPlayerName(contents); // Leaf - Configurable vanilla username check
super(contents.map(gameProfile -> (GameProfile)gameProfile, ResolvableProfile.Partial::createProfile), skinPatch);
this.contents = contents;
}
@@ -0,0 +1,61 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Sun, 28 Jun 2026 20:57:48 +0800
Subject: [PATCH] Leaves: Disable packet limit & Shiroha: Option to full
disable packet limiter
diff --git a/net/minecraft/network/Connection.java b/net/minecraft/network/Connection.java
index d0dff5850717bd083b7a29104a61754ce1b2f822..d0809790e3b3526622af4f7a7eca6c52a6b4044e 100644
--- a/net/minecraft/network/Connection.java
+++ b/net/minecraft/network/Connection.java
@@ -258,8 +258,8 @@ public class Connection extends SimpleChannelInboundHandler<Packet<?>> {
if (this.stopReadingPackets) {
return;
}
- if (this.allPacketCounts != null ||
- io.papermc.paper.configuration.GlobalConfiguration.get().packetLimiter.overrides.containsKey(packet.getClass())) {
+ if (!io.nanachiyo0721.shiroha.config.modules.misc.PaperPacketLimiterConfig.forceDisable && (this.allPacketCounts != null || // Shiroha - Add config to force disable the packet limiter of Paper
+ io.papermc.paper.configuration.GlobalConfiguration.get().packetLimiter.overrides.containsKey(packet.getClass()))) { // Shiroha - Add config to force disable the packet limiter of Paper
long time = System.nanoTime();
synchronized (PACKET_LIMIT_LOCK) {
if (this.allPacketCounts != null) {
diff --git a/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/net/minecraft/server/network/ServerGamePacketListenerImpl.java
index 9fe5ee1c5578be6f6c5ad9a58e10669a4b7ac75a..ee4b6d293c32c00e6173cf8efe8aecce67574e6e 100644
--- a/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerGamePacketListenerImpl.java
@@ -877,7 +877,7 @@ public class ServerGamePacketListenerImpl
public void handleCustomCommandSuggestions(final ServerboundCommandSuggestionPacket packet) {
// PacketUtils.ensureRunningOnSameThread(packet, this, this.player.level()); // Paper - AsyncTabCompleteEvent; run this async
// CraftBukkit start
- if (!this.tabSpamThrottler.isIncrementAndUnderThreshold() && !this.server.getPlayerList().isOp(this.player.nameAndId()) && !this.server.isSingleplayerOwner(this.player.nameAndId())) { // Paper - configurable tab spam limits
+ if (!io.nanachiyo0721.shiroha.config.modules.misc.PaperPacketLimiterConfig.forceDisable && !this.tabSpamThrottler.isIncrementAndUnderThreshold() && !this.server.getPlayerList().isOp(this.player.nameAndId()) && !this.server.isSingleplayerOwner(this.player.nameAndId())) { // Paper - configurable tab spam limits // Leaves - can disable
this.disconnectAsync(Component.translatable("disconnect.spam"), org.bukkit.event.player.PlayerKickEvent.Cause.SPAM); // Paper - Kick event cause // Paper - add proper async disconnect
return;
}
@@ -2111,6 +2111,7 @@ public class ServerGamePacketListenerImpl
private long lastLimitedPacket = -1;
private boolean checkLimit(long timestamp) {
+ if (io.nanachiyo0721.shiroha.config.modules.misc.PaperPacketLimiterConfig.forceDisable) return true; // Leaves - disable
if (!io.papermc.paper.configuration.GlobalConfiguration.get().spamLimiter.incomingPacketThreshold.enabled()) {
return true;
}
@@ -2677,6 +2678,8 @@ public class ServerGamePacketListenerImpl
// Spigot start - spam exclusions
private void detectRateSpam(final TickThrottler throttler, final String message) {
+ if (io.nanachiyo0721.shiroha.config.modules.misc.PaperPacketLimiterConfig.forceDisable) return; // Leaves - disable
+ // CraftBukkit start - replaced with thread safe throttle
if (org.spigotmc.SpigotConfig.enableSpamExclusions) {
for (String exclude : org.spigotmc.SpigotConfig.spamExclusions) {
if (exclude != null && message.startsWith(exclude)) {
@@ -3475,7 +3478,7 @@ public class ServerGamePacketListenerImpl
@Override
public void handlePlaceRecipe(final ServerboundPlaceRecipePacket packet) {
// Paper start - auto recipe limit
- if (!org.bukkit.Bukkit.isPrimaryThread()) {
+ if (!io.nanachiyo0721.shiroha.config.modules.misc.PaperPacketLimiterConfig.forceDisable && !org.bukkit.Bukkit.isPrimaryThread()) { // Leaves - can disable
if (!this.recipeSpamPackets.isIncrementAndUnderThreshold()) {
this.disconnectAsync(net.minecraft.network.chat.Component.translatable("disconnect.spam"), org.bukkit.event.player.PlayerKickEvent.Cause.SPAM); // Paper - kick event cause // Paper - add proper async disconnect
return;
@@ -0,0 +1,56 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 18 Apr 2026 12:26:25 +0800
Subject: [PATCH] Leaves: Configurable collision behavior
Co-authored by: Fortern <blueten.ki@gmail.com>
As part of: Leaves (https://github.com/LeavesMC/Leaves/blob/c5f18b7864206cea4411211b51787f10affbcb9c/leaves-server/minecraft-patches/features/0111-Configurable-collision-behavior.patch)
Licensed under: GPL-3.0 (https://www.gnu.org/licenses/gpl-3.0.html)
diff --git a/ca/spottedleaf/moonrise/patches/collisions/CollisionUtil.java b/ca/spottedleaf/moonrise/patches/collisions/CollisionUtil.java
index 8d2518600ad518999b75124f0a87db9efe541f2e..c2c4a83ac4fb787402400d490ecc94be50e49bd8 100644
--- a/ca/spottedleaf/moonrise/patches/collisions/CollisionUtil.java
+++ b/ca/spottedleaf/moonrise/patches/collisions/CollisionUtil.java
@@ -101,6 +101,14 @@ public final class CollisionUtil {
(box1.minZ - box2.maxZ) < -COLLISION_EPSILON && (box1.maxZ - box2.minZ) > COLLISION_EPSILON;
}
+ // Leaves start - Configurable collision behavior
+ public static boolean voxelShapeIntersectVanilla(final AABB box1, final AABB box2) {
+ return box1.minX < box2.maxX && box1.maxX > box2.minX &&
+ box1.minY < box2.maxY && box1.maxY > box2.minY &&
+ box1.minZ < box2.maxZ && box1.maxZ > box2.minZ;
+ }
+ // Leaves end - Configurable collision behavior
+
// assume !isEmpty(target) && abs(source_move) >= COLLISION_EPSILON
public static double collideX(final AABB target, final AABB source, final double source_move) {
if ((source.minY - target.maxY) < -COLLISION_EPSILON && (source.maxY - target.minY) > COLLISION_EPSILON &&
@@ -2033,7 +2041,7 @@ public final class CollisionUtil {
continue;
}
} else {
- if (!voxelShapeIntersect(aabb, singleAABB)) {
+ if (shouldSkip(aabb, blockCollision, singleAABB)) { // Leaves - Configurable collision behavior
continue;
}
}
@@ -2087,6 +2095,18 @@ public final class CollisionUtil {
return ret;
}
+ // Leaves start - Configurable collision behavior
+ private static boolean shouldSkip(AABB aabb, VoxelShape blockCollision, AABB singleAABB) {
+ boolean isBlockShape = blockCollision == Shapes.block();
+ return switch (io.nanachiyo0721.shiroha.config.modules.fixes.CollisionBehaviorConfig.behaviorMode) {
+ case io.nanachiyo0721.shiroha.enums.EnumCollisionBehaviorMode.VANILLA -> !voxelShapeIntersectVanilla(aabb, singleAABB);
+ case io.nanachiyo0721.shiroha.enums.EnumCollisionBehaviorMode.PAPER -> !voxelShapeIntersect(aabb, singleAABB);
+ default -> isBlockShape && !voxelShapeIntersectVanilla(aabb, singleAABB) || !isBlockShape && !voxelShapeIntersect(aabb, singleAABB);
+ // All other value as BLOCK_SHAPE_VANILLA to process
+ };
+ }
+ // Leaves end - Configurable collision behavior
+
public static boolean getEntityHardCollisions(final Level world, final Entity entity, AABB aabb,
final List<AABB> into, final int collisionFlags, final Predicate<Entity> predicate) {
final boolean checkOnly = (collisionFlags & COLLISION_FLAG_CHECK_ONLY) != 0;
@@ -0,0 +1,95 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Tue, 21 Apr 2026 23:52:23 +0800
Subject: [PATCH] Leaves: Optimized dragon respawn
Co-authored by: violetc <58360096+s-yh-china@users.noreply.github.com>
As part of: Leaves (https://github.com/LeavesMC/Leaves/blob/4ade1001e4dd19c47d95c27f0b12df3175697f29/leaves-server/minecraft-patches/features/0049-Optimized-dragon-respawn.patch)
Licensed under: GPL-3.0 (https://www.gnu.org/licenses/gpl-3.0.html)
diff --git a/net/minecraft/world/level/dimension/end/EnderDragonFight.java b/net/minecraft/world/level/dimension/end/EnderDragonFight.java
index 824ef3f458505569fe5b8efb2055ecea7ba6cc56..64a2fc0e49a6fc50773f6e0c40c2535a7533d41b 100644
--- a/net/minecraft/world/level/dimension/end/EnderDragonFight.java
+++ b/net/minecraft/world/level/dimension/end/EnderDragonFight.java
@@ -317,7 +317,67 @@ public class EnderDragonFight extends SavedData {
return false;
}
+ // Leaves start - optimizedDragonRespawn
+ private int cachePortalChunkIteratorX = -8;
+ private int cachePortalChunkIteratorZ = -8;
+ private int cachePortalOriginIteratorY = -1;
+
public BlockPattern.@Nullable BlockPatternMatch findExitPortal() {
+ if (io.nanachiyo0721.shiroha.config.modules.optimizations.OptimizedDragonRespawnConfig.optimizedRespawn) {
+ int i, j;
+ for (i = cachePortalChunkIteratorX; i <= 8; ++i) {
+ for (j = cachePortalChunkIteratorZ; j <= 8; ++j) {
+ LevelChunk worldChunk = this.level.getChunk(i, j);
+ for (BlockEntity blockEntity : worldChunk.getBlockEntities().values()) {
+ if (blockEntity instanceof net.minecraft.world.level.block.entity.TheEndGatewayBlockEntity) {
+ continue;
+ }
+ if (blockEntity instanceof TheEndPortalBlockEntity) {
+ BlockPattern.BlockPatternMatch blockPatternMatch = this.exitPortalPattern.find(this.level, blockEntity.getBlockPos());
+ if (blockPatternMatch != null) {
+ BlockPos blockPos = blockPatternMatch.getBlock(3, 3, 3).getPos();
+ if (this.exitPortalLocation == null) {
+ this.exitPortalLocation = blockPos;
+ }
+ //No need to judge whether optimizing option is open
+ cachePortalChunkIteratorX = i;
+ cachePortalChunkIteratorZ = j;
+ return blockPatternMatch;
+ }
+ }
+ }
+ }
+ }
+
+ if (this.needsStateScanning || this.exitPortalLocation == null) {
+ if (cachePortalOriginIteratorY != -1) {
+ i = cachePortalOriginIteratorY;
+ } else {
+ i = this.level.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, EndPodiumFeature.getLocation(BlockPos.ZERO)).getY();
+ }
+ boolean notFirstSearch = false;
+ for (j = i; j >= 0; --j) {
+ BlockPattern.BlockPatternMatch result2 = null;
+ if (notFirstSearch) {
+ result2 = org.leavesmc.leaves.util.BlockPatternHelper.partialSearchAround(this.exitPortalPattern, this.level, new BlockPos(EndPodiumFeature.getLocation(BlockPos.ZERO).getY(), j, EndPodiumFeature.getLocation(BlockPos.ZERO).getZ()));
+ } else {
+ result2 = this.exitPortalPattern.find(this.level, new BlockPos(EndPodiumFeature.getLocation(BlockPos.ZERO).getX(), j, EndPodiumFeature.getLocation(BlockPos.ZERO).getZ()));
+ }
+ if (result2 != null) {
+ if (this.exitPortalLocation == null) {
+ this.exitPortalLocation = result2.getBlock(3, 3, 3).getPos();
+ }
+ cachePortalOriginIteratorY = j;
+ return result2;
+ }
+ notFirstSearch = true;
+ }
+ }
+
+ return null;
+ }
+ // Leaves end - optimizedDragonRespawn
+
ChunkPos chunkOrigin = ChunkPos.containing(this.origin);
for (int x = -8 + chunkOrigin.x(); x <= 8 + chunkOrigin.x(); x++) {
@@ -623,8 +683,12 @@ public class EnderDragonFight extends SavedData {
}
return false; // CraftBukkit - return value
}
-
public boolean respawnDragon(final List<EndCrystal> crystals) { // CraftBukkit - return boolean
+ // Leaves - start optimizedDragonRespawn
+ cachePortalChunkIteratorX = -8;
+ cachePortalChunkIteratorZ = -8;
+ cachePortalOriginIteratorY = -1;
+ // Leaves - end optimizedDragonRespawn
if (this.dragonKilled && this.respawnStage == null) {
for (BlockPattern.BlockPatternMatch portal = this.findExitPortal(); portal != null; portal = this.findExitPortal()) {
for (int x = 0; x < this.exitPortalPattern.getWidth(); x++) {
@@ -0,0 +1,57 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 18 Apr 2026 12:22:30 +0800
Subject: [PATCH] Gale: Variable entity wake-up duration
Co-authored by: Martijn Muijsers <martijnmuijsers@live.nl>
As part of: Gale (https://github.com/GaleMC/Gale/blob/276e903b2688f23b19bdc8d493c0bf87656d2400/patches/server/0054-Variable-entity-wake-up-duration.patch)
Licensed under: GPL-3.0 (https://www.gnu.org/licenses/gpl-3.0.html)
diff --git a/io/papermc/paper/entity/activation/ActivationRange.java b/io/papermc/paper/entity/activation/ActivationRange.java
index b4f9f41a56bbc40e90217c0344c070ebdd08c119..33cab0d9d144a37d144f18c6fff31afc82d3f8a9 100644
--- a/io/papermc/paper/entity/activation/ActivationRange.java
+++ b/io/papermc/paper/entity/activation/ActivationRange.java
@@ -61,27 +61,39 @@ public final class ActivationRange {
if (entity.activationType == ActivationType.VILLAGER) {
if (inactiveFor > config.wakeUpInactiveVillagersEvery && worldData.wakeupInactiveRemainingVillagers > 0) { // Folia - threaded regions
worldData.wakeupInactiveRemainingVillagers--; // Folia - threaded regions
- return config.wakeUpInactiveVillagersFor;
+ return getWakeUpDurationWithVariance(entity, config.wakeUpInactiveVillagersFor); // Gale - variable entity wake-up duration
}
} else if (entity.activationType == ActivationType.ANIMAL) {
if (inactiveFor > config.wakeUpInactiveAnimalsEvery && worldData.wakeupInactiveRemainingAnimals > 0) { // Folia - threaded regions
worldData.wakeupInactiveRemainingAnimals--; // Folia - threaded regions
- return config.wakeUpInactiveAnimalsFor;
+ return getWakeUpDurationWithVariance(entity, config.wakeUpInactiveAnimalsFor); // Gale - variable entity wake-up duration
}
} else if (entity.activationType == ActivationType.FLYING_MONSTER) {
if (inactiveFor > config.wakeUpInactiveFlyingEvery && worldData.wakeupInactiveRemainingFlying > 0) { // Folia - threaded regions
worldData.wakeupInactiveRemainingFlying--; // Folia - threaded regions
- return config.wakeUpInactiveFlyingFor;
+ return getWakeUpDurationWithVariance(entity, config.wakeUpInactiveFlyingFor); // Gale - variable entity wake-up duration
}
} else if (entity.activationType == ActivationType.MONSTER || entity.activationType == ActivationType.RAIDER) {
if (inactiveFor > config.wakeUpInactiveMonstersEvery && worldData.wakeupInactiveRemainingMonsters > 0) { // Folia - threaded regions
worldData.wakeupInactiveRemainingMonsters--; // Folia - threaded regions
- return config.wakeUpInactiveMonstersFor;
+ return getWakeUpDurationWithVariance(entity, config.wakeUpInactiveMonstersFor); // Gale - variable entity wake-up duration
}
}
return -1;
}
+ // Gale start - variable entity wake-up duration
+ private static final java.util.concurrent.ThreadLocalRandom wakeUpDurationRandom = java.util.concurrent.ThreadLocalRandom.current();
+
+ private static int getWakeUpDurationWithVariance(Entity entity, int wakeUpDuration) {
+ double deviation = io.nanachiyo0721.shiroha.config.modules.optimizations.GaleVariableEntityWakeupConfig.entityWakeUpDurationRatioStandardDeviation;
+ if (deviation <= 0) {
+ return wakeUpDuration;
+ }
+ return (int) Math.min(Integer.MAX_VALUE, Math.max(1, Math.round(wakeUpDuration * wakeUpDurationRandom.nextGaussian(1, deviation))));
+ }
+ // Gale end - variable entity wake-up duration
+
//static AABB maxBB = new AABB(0, 0, 0, 0, 0, 0); // Folia - threaded regions - replaced by local variable
/**
@@ -0,0 +1,30 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 18 Apr 2026 12:23:37 +0800
Subject: [PATCH] Gale: Replace AI attributes with optimized collections
Co-authored by: Martijn Muijsers <martijnmuijsers@live.nl>
2No2Name <2No2Name@web.de>
As part of: Gale (https://github.com/GaleMC/Gale/blob/276e903b2688f23b19bdc8d493c0bf87656d2400/patches/server/0087-Replace-AI-attributes-with-optimized-collections.patch)
Lithium (https://github.com/CaffeineMC/lithium-fabric)
Licensed under: LGPL-3.0 (https://www.gnu.org/licenses/lgpl-3.0.html)
diff --git a/net/minecraft/world/entity/ai/attributes/AttributeMap.java b/net/minecraft/world/entity/ai/attributes/AttributeMap.java
index 68bad6752bd313ca3ebde7fd4e3b2c46c5dee3ef..c951a04126a75c7caf046237ae00768a1114c03f 100644
--- a/net/minecraft/world/entity/ai/attributes/AttributeMap.java
+++ b/net/minecraft/world/entity/ai/attributes/AttributeMap.java
@@ -14,9 +14,11 @@ import net.minecraft.resources.Identifier;
import org.jspecify.annotations.Nullable;
public class AttributeMap {
- private final Map<Holder<Attribute>, AttributeInstance> attributes = new Object2ObjectOpenHashMap<>();
- private final Set<AttributeInstance> attributesToSync = new ObjectOpenHashSet<>();
- private final Set<AttributeInstance> attributesToUpdate = new ObjectOpenHashSet<>();
+ // Gale start - Lithium - replace AI attributes with optimized collections
+ private final Map<Holder<Attribute>, AttributeInstance> attributes = new it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap<>(0);
+ private final Set<AttributeInstance> attributesToSync = new it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet<>(0);
+ private final Set<AttributeInstance> attributesToUpdate = new it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet<>(0);
+ // Gale end - Lithium - replace AI attributes with optimized collections
private final AttributeSupplier supplier;
public AttributeMap(final AttributeSupplier supplier) {
@@ -0,0 +1,42 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 18 Apr 2026 12:24:51 +0800
Subject: [PATCH] Gale: Skip entity move if movement is zero
Co-authored by: Martijn Muijsers <martijnmuijsers@live.nl>
ishland <ishlandmc@yeah.net>
A part of: Gale (https://github.com/GaleMC/Gale/blob/276e903b2688f23b19bdc8d493c0bf87656d2400/patches/server/0103-Skip-entity-move-if-movement-is-zero.patch)
VMP (https://github.com/RelativityMC/VMP-fabric)
Licensed under: MIT (https://opensource.org/licenses/MIT)
diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java
index 83914a091cc8fd6ef726f2732238b164bb590ea2..d66efc7015b00f35d949b952a920f42a957168fa 100644
--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -1152,8 +1152,14 @@ public abstract class Entity
private double moveStartY;
private double moveStartZ;
// Paper end - detailed watchdog information
+ private boolean boundingBoxChanged = false; // Gale - VMP - skip entity move if movement is zero
public void move(final MoverType moverType, Vec3 delta) {
+ // Gale start - VMP - skip entity move if movement is zero
+ if (!this.boundingBoxChanged && delta.equals(Vec3.ZERO)) {
+ return;
+ }
+ // Gale end - VMP - skip entity move if movement is zero
final Vec3 originalMovement = delta; // Paper - Expose pre-collision velocity
// Paper start - detailed watchdog information
ca.spottedleaf.moonrise.common.util.TickThread.ensureTickThread("Cannot move an entity off-main");
@@ -5447,6 +5453,11 @@ public abstract class Entity
}
public final void setBoundingBox(final AABB bb) {
+ // Gale start - VMP - skip entity move if movement is zero
+ if (!this.bb.equals(bb)) {
+ this.boundingBoxChanged = true;
+ }
+ // Gale end - VMP - skip entity move if movement is zero
// CraftBukkit start - block invalid bounding boxes
double minX = bb.minX,
minY = bb.minY,
@@ -0,0 +1,36 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sun, 17 May 2026 08:47:31 +0800
Subject: [PATCH] Gale Store mob counts in an array
License: MIT (https://opensource.org/licenses/MIT)
Gale - https://github.com/GaleMC/Gale
This patch is based on the following mixin:
"com/ishland/vmp/mixins/general/spawn_density_cap/MixinSpawnDensityCapperDensityCap.java"
By: ishland <ishlandmc@yeah.net>
As part of: VMP (https://github.com/RelativityMC/VMP-fabric)
Licensed under: MIT (https://opensource.org/licenses/MIT)
diff --git a/net/minecraft/world/level/LocalMobCapCalculator.java b/net/minecraft/world/level/LocalMobCapCalculator.java
index 5b3808e6ff58d350fe3fd65fb56e8f209e1b2c93..150dfb4c8465dea0139bdbf804a84ce28e8d9023 100644
--- a/net/minecraft/world/level/LocalMobCapCalculator.java
+++ b/net/minecraft/world/level/LocalMobCapCalculator.java
@@ -42,14 +42,14 @@ public class LocalMobCapCalculator {
}
private static class MobCounts {
- private final Object2IntMap<MobCategory> counts = new Object2IntOpenHashMap<>(MobCategory.values().length);
+ private final int[] counts = new int[MobCategory.values().length]; // Gale - VMP - store mob counts in an array
public void add(final MobCategory category) {
- this.counts.computeInt(category, (k, count) -> count == null ? 1 : count + 1);
+ this.counts[category.ordinal()]++; // Gale - VMP - store mob counts in an array
}
public boolean canSpawn(final MobCategory category) {
- return this.counts.getOrDefault(category, 0) < category.getMaxInstancesPerChunk();
+ return this.counts[category.ordinal()] < category.getMaxInstancesPerChunk(); // Gale - VMP - store mob counts in an array
}
}
}
@@ -0,0 +1,113 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 4 Jun 2026 17:15:00 +0800
Subject: [PATCH] Gale: Optimize random calls in chunk ticking
License: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
Gale - https://github.com/GaleMC/Gale
This patch is based on the following patch:
"Optimize random calls in chunk ticking"
By: Paul Sauve <paul@technove.co>
As part of: Airplane (https://github.com/TECHNOVE/Airplane)
Licensed under: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
The patch also received the following subsequent modification:
By: Kevin Raneri <kevin.raneri@gmail.com>
As part of: Pufferfish (https://github.com/pufferfish-gg/Pufferfish)
Licensed under: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
* Description *
Throttling of ice and snow tick has been moved to another patch as
configurable ice and snow tick chance.
* Airplane description *
Especially at over 30,000 chunks these random calls are fairly heavy. We
use a different method here for checking lightning, and for checking
ice.
Lightning: Each chunk now keeps an int of how many ticks until the
lightning should strike. This int is a random number from 0 to 100000 * 2,
the multiplication is required to keep the probability the same.
Ice and snow: We just generate a single random number 0-16 and increment
it, while checking if it's 0 for the current chunk.
Depending on configuration for things that tick in a chunk, this is a
5-10% improvement.
* Airplane copyright *
Airplane
Copyright (C) 2020 Technove LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
diff --git a/net/minecraft/server/level/ServerLevel.java b/net/minecraft/server/level/ServerLevel.java
index fca5017a13148a928ae320ee99cddc45f617ffcd..c22f17a517254541b1ca627ec149cbe956962e61 100644
--- a/net/minecraft/server/level/ServerLevel.java
+++ b/net/minecraft/server/level/ServerLevel.java
@@ -1051,7 +1051,7 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
}
// Paper start - optimise random ticking
- private final io.papermc.paper.threadedregions.util.SimpleThreadLocalRandomSource simpleRandom = io.papermc.paper.threadedregions.util.SimpleThreadLocalRandomSource.INSTANCE; // Folia - region threading
+ public final io.papermc.paper.threadedregions.util.SimpleThreadLocalRandomSource simpleRandom = io.papermc.paper.threadedregions.util.SimpleThreadLocalRandomSource.INSTANCE; // Folia - region threading // Shiroha - Make public for : Gale: Optimize random calls in chunk ticking
private void optimiseRandomTick(final LevelChunk chunk, final int tickSpeed) {
final LevelChunkSection[] sections = chunk.getSections();
@@ -1133,7 +1133,7 @@ public class ServerLevel extends Level implements WorldGenLevel, ServerEntityGet
int minZ = chunkPos.getMinBlockZ();
ProfilerFiller profiler = Profiler.get();
profiler.push("thunder");
- if (!this.paperConfig().environment.disableThunder && raining && this.isThundering() && this.spigotConfig.thunderChance > 0 && this.random.nextInt(this.spigotConfig.thunderChance) == 0) { // Spigot // Paper - Option to disable thunder
+ if (!this.paperConfig().environment.disableThunder && raining && this.isThundering() && this.spigotConfig.thunderChance > 0 /*&& this.random.nextInt(this.spigotConfig.thunderChance) == 0*/ && chunk.shouldDoLightning(this.random)) { // Spigot // Paper - Option to disable thunder // Gale - Airplane - optimize random calls in chunk ticking - replace random with shouldDoLightning
BlockPos pos = this.findLightningTargetAround(this.getBlockRandomPos(minX, 0, minZ, 15));
if (this.isRainingAt(pos)) {
DifficultyInstance difficulty = this.getCurrentDifficultyAt(pos);
diff --git a/net/minecraft/world/level/chunk/LevelChunk.java b/net/minecraft/world/level/chunk/LevelChunk.java
index 3cb6c24a21538569d73b95803dde7e4a2fdb67f5..6b41256e8f5112ed8608870342317ca7503c25d0 100644
--- a/net/minecraft/world/level/chunk/LevelChunk.java
+++ b/net/minecraft/world/level/chunk/LevelChunk.java
@@ -144,6 +144,19 @@ public class LevelChunk extends ChunkAccess implements DebugValueSource, ca.spot
}
// Paper end - get block chunk optimisation
+ // Gale start - Airplane - optimize random calls in chunk ticking - instead of using a random every time the chunk is ticked, define when lightning strikes preemptively
+ private int lightningTick;
+ // shouldDoLightning compiles down to 29 bytes, which with the default of 35 byte inlining should guarantee an inline
+ public final boolean shouldDoLightning(net.minecraft.util.RandomSource random) {
+ if (this.lightningTick-- <= 0) {
+ this.lightningTick = random.nextInt(this.level.spigotConfig.thunderChance) << 1;
+ return true;
+ }
+ return false;
+ }
+ // Gale end - Airplane - optimize random calls in chunk ticking - instead of using a random every time the chunk is ticked, define when lightning strikes preemptively
+
+
public LevelChunk(final Level level, final ChunkPos pos) {
this(level, pos, UpgradeData.EMPTY, new LevelChunkTicks<>(), new LevelChunkTicks<>(), 0L, null, null, null);
}
@@ -180,6 +193,8 @@ public class LevelChunk extends ChunkAccess implements DebugValueSource, ca.spot
this.debug = !empty && this.level.isDebug();
this.defaultBlockState = empty ? VOID_AIR_BLOCKSTATE : AIR_BLOCKSTATE;
// Paper end - get block chunk optimisation
+
+ this.lightningTick = io.papermc.paper.threadedregions.util.SimpleThreadLocalRandomSource.INSTANCE.nextInt(100000) << 1; // Gale - Airplane - optimize random calls in chunk ticking - initialize lightning tick
}
public LevelChunk(final ServerLevel level, final ProtoChunk protoChunk, final LevelChunk.@Nullable PostLoadProcessor postLoad) {
@@ -0,0 +1,58 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 4 Jun 2026 17:22:55 +0800
Subject: [PATCH] Gale: Reduce enderman teleport chunk lookups
License: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
Gale - https://github.com/GaleMC/Gale
This patch is based on the following patch:
"Reduce chunk loading & lookups"
By: Paul Sauve <paul@technove.co>
As part of: Airplane (https://github.com/TECHNOVE/Airplane)
Licensed under: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
* Airplane copyright *
Airplane
Copyright (C) 2020 Technove LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
diff --git a/net/minecraft/world/entity/monster/EnderMan.java b/net/minecraft/world/entity/monster/EnderMan.java
index 9b4ae8afda1f2202761cb49bc4f1181ce4eb55d5..d2ac2a0c5bb18c2bca18e5166ed65afd01166e04 100644
--- a/net/minecraft/world/entity/monster/EnderMan.java
+++ b/net/minecraft/world/entity/monster/EnderMan.java
@@ -298,11 +298,19 @@ public class EnderMan extends Monster implements NeutralMob {
private boolean teleport(final double x, final double y, final double z) {
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(x, y, z);
- while (pos.getY() > this.level().getMinY() && !this.level().getBlockState(pos).blocksMotion()) {
+ // Gale start - Airplane - single chunk lookup
+ net.minecraft.world.level.chunk.LevelChunk chunk = this.level().getChunkIfLoaded(pos);
+
+ if (chunk == null) {
+ return false;
+ }
+
+ while (pos.getY() > this.level().getMinY() && !chunk.getBlockState(pos).blocksMotion()) {
+ // Gale end - Airplane - single chunk lookup
pos.move(Direction.DOWN);
}
- BlockState blockState = this.level().getBlockState(pos);
+ BlockState blockState = chunk.getBlockState(pos); // Gale - Airplane - single chunk lookup
boolean couldStandOn = blockState.blocksMotion();
boolean isWet = blockState.getFluidState().is(FluidTags.WATER);
if (couldStandOn && !isWet) {
@@ -0,0 +1,45 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 4 Jun 2026 17:28:24 +0800
Subject: [PATCH] Gale: Cache ShapePairKey hash
License: LGPL-3.0-only (https://www.gnu.org/licenses/lgpl-3.0.html)
Gale - https://github.com/GaleMC/Gale
The JMH benchmark of this patch can be found in SunBox's `RecordHashCode`
diff --git a/net/minecraft/world/level/block/Block.java b/net/minecraft/world/level/block/Block.java
index 423c45d7be8ac0c27fd3caa0aa8f15f25ad4a3a6..1af396a051cc47dccb973ca864cf1ec2e8b756ed 100644
--- a/net/minecraft/world/level/block/Block.java
+++ b/net/minecraft/world/level/block/Block.java
@@ -696,7 +696,20 @@ public class Block extends BlockBehaviour implements ItemLike {
}
// CraftBukkit end
- private record ShapePairKey(VoxelShape first, VoxelShape second) {
+ // Gale start - cache ShapePairKey hash
+ static class ShapePairKey {
+
+ private final VoxelShape first;
+ private final VoxelShape second;
+ private final int hash;
+
+ private ShapePairKey(VoxelShape first, VoxelShape second) {
+ this.first = first;
+ this.second = second;
+ this.hash = System.identityHashCode(this.first) * 31 + System.identityHashCode(this.second);
+ }
+ // Gale end - cache ShapePairKey hash
+
@Override
public boolean equals(final Object o) {
return o instanceof Block.ShapePairKey that && this.first == that.first && this.second == that.second;
@@ -704,7 +717,7 @@ public class Block extends BlockBehaviour implements ItemLike {
@Override
public int hashCode() {
- return System.identityHashCode(this.first) * 31 + System.identityHashCode(this.second);
+ return this.hash; // Gale - cache ShapePairKey hash
}
}
@@ -0,0 +1,35 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 4 Jun 2026 17:30:18 +0800
Subject: [PATCH] Gale: For collision check has physics before same vehicle
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
License: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
Gale - https://github.com/GaleMC/Gale
This patch is based on the following patch:
"Swaps the predicate order of collision"
By: ㄗㄠˋ ㄑㄧˊ <tsao-chi@the-lingo.org>
As part of: Akarin (https://github.com/Akarin-project/Akarin)
Licensed under: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java
index d66efc7015b00f35d949b952a920f42a957168fa..15c43ee830a8f7b38bb8a65f11d4485a64920450 100644
--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -2438,8 +2438,8 @@ public abstract class Entity
}
public void push(final Entity entity) {
+ if (!entity.noPhysics && !this.noPhysics) { // Gale - Akarin - collision physics check before vehicle check
if (!this.isPassengerOfSameVehicle(entity)) {
- if (!entity.noPhysics && !this.noPhysics) {
if (this.level.paperConfig().collisions.onlyPlayersCollide && !(entity instanceof ServerPlayer || this instanceof ServerPlayer)) return; // Paper - Collision option for requiring a player participant
double xa = entity.getX() - this.getX();
double za = entity.getZ() - this.getZ();
@@ -0,0 +1,32 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 4 Jun 2026 17:32:39 +0800
Subject: [PATCH] Gale: Skip negligible planar movement multiplication
License: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
Gale - https://github.com/GaleMC/Gale
diff --git a/net/minecraft/world/entity/Entity.java b/net/minecraft/world/entity/Entity.java
index 15c43ee830a8f7b38bb8a65f11d4485a64920450..de0858cb11b0dd4d0e35f37cced537a8940f8a4a 100644
--- a/net/minecraft/world/entity/Entity.java
+++ b/net/minecraft/world/entity/Entity.java
@@ -1299,8 +1299,17 @@ public abstract class Entity
}
}
- float blockSpeedFactor = this.getBlockSpeedFactor();
- this.setDeltaMovement(this.getDeltaMovement().multiply(blockSpeedFactor, 1.0, blockSpeedFactor));
+ // Gale start - skip negligible planar movement multiplication
+ Vec3 oldDeltaMovement = this.getDeltaMovement();
+ if (oldDeltaMovement.x < -1e-6 || oldDeltaMovement.x > 1e-6 || oldDeltaMovement.z < -1e-6 || oldDeltaMovement.z > 1e-6) {
+ // Gale end - skip negligible planar movement multiplication
+ float blockSpeedFactor = this.getBlockSpeedFactor();
+ // Gale start - skip negligible planar movement multiplication
+ if (blockSpeedFactor < 1 - 1e-6 || blockSpeedFactor > 1 + 1e-6) {
+ this.setDeltaMovement(oldDeltaMovement.multiply(blockSpeedFactor, 1.0, blockSpeedFactor));
+ }
+ }
+ // Gale end - skip negligible planar movement multiplication
profiler.pop();
}
}
@@ -0,0 +1,26 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Thu, 4 Jun 2026 17:34:43 +0800
Subject: [PATCH] Gale: Optimize matching item checks
License: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
Gale - https://github.com/GaleMC/Gale
diff --git a/net/minecraft/world/item/ItemStack.java b/net/minecraft/world/item/ItemStack.java
index 0bd2f2da669aa1a59d0af65aea3b305dd9be4476..b384ddb0eedb9286f27705554952a2eacc05d6db 100644
--- a/net/minecraft/world/item/ItemStack.java
+++ b/net/minecraft/world/item/ItemStack.java
@@ -841,11 +841,11 @@ public final class ItemStack implements DataComponentHolder, ItemInstance, Chang
}
public static boolean isSameItem(final ItemStack a, final ItemStack b) {
- return a.is(b.getItem());
+ return a == b || a.is(b.getItem()); // Gale - optimize identical item checks
}
public static boolean isSameItemSameComponents(final ItemStack a, final ItemStack b) {
- return a.is(b.getItem()) && (a.isEmpty() && b.isEmpty() || Objects.equals(a.components, b.components));
+ return a == b || a.is(b.getItem()) && (a.isEmpty() && b.isEmpty() || Objects.equals(a.components, b.components)); // Gale - optimize identical item checks
}
public static boolean matchesIgnoringComponents(final ItemStack a, final ItemStack b, final Predicate<DataComponentType<?>> ignoredPredicate) {
@@ -0,0 +1,42 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Sat, 20 Jun 2026 23:16:15 +0800
Subject: [PATCH] Gale Reduce lambda and Optional allocation in
EntityBasedExplosionDamageCalculator
License: LGPL-3.0-only (https://www.gnu.org/licenses/lgpl-3.0.html)
Gale - https://github.com/GaleMC/Gale
This patch is based on the following mixin:
"net/caffeinemc/mods/lithium/mixin/alloc/explosion_behavior/EntityBasedExplosionDamageCalculatorMixin.java"
By: 2No2Name <2No2Name@web.de>
As part of: Lithium (https://github.com/CaffeineMC/lithium)
Licensed under: LGPL-3.0-only (https://www.gnu.org/licenses/lgpl-3.0.html)
diff --git a/net/minecraft/world/level/EntityBasedExplosionDamageCalculator.java b/net/minecraft/world/level/EntityBasedExplosionDamageCalculator.java
index 356a3a0dda09af007c3fbddfe360b38f4d7204ce..aff8d67c9b9797402a3bf6c5bce54af19af0ade7 100644
--- a/net/minecraft/world/level/EntityBasedExplosionDamageCalculator.java
+++ b/net/minecraft/world/level/EntityBasedExplosionDamageCalculator.java
@@ -17,8 +17,20 @@ public class EntityBasedExplosionDamageCalculator extends ExplosionDamageCalcula
public Optional<Float> getBlockExplosionResistance(
final Explosion explosion, final BlockGetter level, final BlockPos pos, final BlockState block, final FluidState fluid
) {
- return super.getBlockExplosionResistance(explosion, level, pos, block, fluid)
- .map(resistance -> this.source.getBlockExplosionResistance(explosion, level, pos, block, fluid, resistance));
+ // Gale start - Lithium - reduce lambda and Optional allocation in EntityBasedExplosionDamageCalculator
+ Optional<Float> optionalBlastResistance = super.getBlockExplosionResistance(explosion, level, pos, block, fluid);
+
+ if (optionalBlastResistance.isPresent()) {
+ float resistance = optionalBlastResistance.get();
+ float effectiveExplosionResistance = this.source.getBlockExplosionResistance(explosion, level, pos, block, fluid, resistance);
+
+ if (effectiveExplosionResistance != resistance) {
+ return Optional.of(effectiveExplosionResistance);
+ }
+ }
+
+ return optionalBlastResistance;
+ // Gale end - Lithium - reduce lambda and Optional allocation in EntityBasedExplosionDamageCalculator
}
@Override
@@ -0,0 +1,441 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Helvetica Volubi <suisuroru@blue-millennium.fun>
Date: Sun, 28 Jun 2026 22:45:55 +0800
Subject: [PATCH] Gale Reduce array allocations
License: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
Gale - https://github.com/GaleMC/Gale
Enum's values returns anew array copy of the enums, this behavior is defined in
`src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java#visitEnumDef`
This is a defensive programming strategy to prevent enums from being modified. However,
copying is unnecessary if we only have read calls.
So we can cache the values result to avoid useless allocations.
Cached as the array since it does not create iterator on the enhanced for loop,
But the list does, and may spend more time than iterating using the array.
One-time calls are excluded from this patch, since no need.
The JMH benchmark of this patch can be found in SunBox's `CachedEnumValuesForLoop`
This patch is based on the following patch:
"reduce allocs"
By: Simon Gardling <titaniumtown@gmail.com>
As part of: JettPack (https://gitlab.com/Titaniumtown/JettPack)
Licensed under: GPL-3.0-only (https://www.gnu.org/licenses/gpl-3.0.html)
diff --git a/ca/spottedleaf/moonrise/patches/chunk_system/level/entity/ChunkEntitySlices.java b/ca/spottedleaf/moonrise/patches/chunk_system/level/entity/ChunkEntitySlices.java
index 8d9ce3d301d5f7e4106587ae00adb8dd5b8b6f88..dd8a4e445928d93667702dedbd35ab3e0f94f3be 100644
--- a/ca/spottedleaf/moonrise/patches/chunk_system/level/entity/ChunkEntitySlices.java
+++ b/ca/spottedleaf/moonrise/patches/chunk_system/level/entity/ChunkEntitySlices.java
@@ -400,7 +400,6 @@ public final class ChunkEntitySlices {
private static final class BasicEntityList<E extends Entity> {
- private static final Entity[] EMPTY = new Entity[0];
private static final int DEFAULT_CAPACITY = 4;
private E[] storage;
@@ -411,7 +410,7 @@ public final class ChunkEntitySlices {
}
public BasicEntityList(final int cap) {
- this.storage = (E[])(cap <= 0 ? EMPTY : new Entity[cap]);
+ this.storage = (E[])(cap <= 0 ? me.titaniumtown.ArrayConstants.emptyEntityArray : new Entity[cap]);// Gale - JettPack - reduce array allocations
}
public boolean isEmpty() {
@@ -423,7 +422,7 @@ public final class ChunkEntitySlices {
}
private void resize() {
- if (this.storage == EMPTY) {
+ if (this.storage == me.titaniumtown.ArrayConstants.emptyEntityArray) { // Gale - JettPack - reduce array allocations
this.storage = (E[])new Entity[DEFAULT_CAPACITY];
} else {
this.storage = Arrays.copyOf(this.storage, this.storage.length * 2);
diff --git a/net/minecraft/nbt/ByteArrayTag.java b/net/minecraft/nbt/ByteArrayTag.java
index 4fc0cfeabf60d4bd0dcfd9814d13858454bc39da..0e4dbc0c736ec2ce4826a81ef561a4cd7a8b974d 100644
--- a/net/minecraft/nbt/ByteArrayTag.java
+++ b/net/minecraft/nbt/ByteArrayTag.java
@@ -144,7 +144,7 @@ public final class ByteArrayTag implements CollectionTag {
@Override
public void clear() {
- this.data = new byte[0];
+ this.data = me.titaniumtown.ArrayConstants.emptyByteArray; // Gale - JettPack - reduce array allocations
}
@Override
diff --git a/net/minecraft/nbt/IntArrayTag.java b/net/minecraft/nbt/IntArrayTag.java
index 8ed91b84eb90cfe31993fa32b35263e7adea918e..bf4fe7956ceb8c79427e4d89d458ed30ee1dcb54 100644
--- a/net/minecraft/nbt/IntArrayTag.java
+++ b/net/minecraft/nbt/IntArrayTag.java
@@ -151,7 +151,7 @@ public final class IntArrayTag implements CollectionTag {
@Override
public void clear() {
- this.data = new int[0];
+ this.data = me.titaniumtown.ArrayConstants.emptyIntArray; // Gale - JettPack - reduce array allocations
}
@Override
diff --git a/net/minecraft/nbt/LongArrayTag.java b/net/minecraft/nbt/LongArrayTag.java
index fe75d82cb43364ff58a531306bac934cbca4f729..5141d9765dc29f23a2a7f0918d2c76ddfe09fa6f 100644
--- a/net/minecraft/nbt/LongArrayTag.java
+++ b/net/minecraft/nbt/LongArrayTag.java
@@ -150,7 +150,7 @@ public final class LongArrayTag implements CollectionTag {
@Override
public void clear() {
- this.data = new long[0];
+ this.data = me.titaniumtown.ArrayConstants.emptyLongArray; // Gale - JettPack - reduce array allocations
}
@Override
diff --git a/net/minecraft/network/CipherBase.java b/net/minecraft/network/CipherBase.java
index 5a1fcd0a552dfcebff351c408a0403a8017930c1..1cdb3a6292133719b2e6b824ed9f78857f7b595e 100644
--- a/net/minecraft/network/CipherBase.java
+++ b/net/minecraft/network/CipherBase.java
@@ -7,8 +7,8 @@ import javax.crypto.ShortBufferException;
public class CipherBase {
private final Cipher cipher;
- private byte[] heapIn = new byte[0];
- private byte[] heapOut = new byte[0];
+ private byte[] heapIn = me.titaniumtown.ArrayConstants.emptyByteArray; // Gale - JettPack - reduce array allocations
+ private byte[] heapOut = me.titaniumtown.ArrayConstants.emptyByteArray; // Gale - JettPack - reduce array allocations
protected CipherBase(final Cipher cipher) {
this.cipher = cipher;
diff --git a/net/minecraft/network/chat/contents/TranslatableContents.java b/net/minecraft/network/chat/contents/TranslatableContents.java
index b6973f9b48092676029ff58485ec8b8dece7387b..785f5c6f683ffdb73a70afabc42d6c09abb1e1d8 100644
--- a/net/minecraft/network/chat/contents/TranslatableContents.java
+++ b/net/minecraft/network/chat/contents/TranslatableContents.java
@@ -28,7 +28,7 @@ import net.minecraft.util.ExtraCodecs;
import org.jspecify.annotations.Nullable;
public class TranslatableContents implements ComponentContents {
- public static final Object[] NO_ARGS = new Object[0];
+ public static final Object[] NO_ARGS = me.titaniumtown.ArrayConstants.emptyObjectArray; // Gale - JettPack - reduce array allocations
public static final Codec<Object> PRIMITIVE_ARG_CODEC = ExtraCodecs.JAVA.validate(TranslatableContents::filterAllowedArguments);
private static final Codec<Object> ARG_CODEC = Codec.either(PRIMITIVE_ARG_CODEC, ComponentSerialization.CODEC)
.xmap(
diff --git a/net/minecraft/server/level/ServerEntity.java b/net/minecraft/server/level/ServerEntity.java
index 2e71a1cbabf3405e3e4fd5349a1784d895e7e60c..42de919064680b1a464d813976ca5e69a0bd3b01 100644
--- a/net/minecraft/server/level/ServerEntity.java
+++ b/net/minecraft/server/level/ServerEntity.java
@@ -364,7 +364,7 @@ public class ServerEntity {
if (this.entity instanceof LivingEntity livingEntity) {
List<Pair<EquipmentSlot, ItemStack>> slots = Lists.newArrayList();
- for (EquipmentSlot slot : EquipmentSlot.VALUES) {
+ for (EquipmentSlot slot : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
ItemStack itemStack = livingEntity.getItemBySlot(slot);
if (!itemStack.isEmpty()) {
slots.add(Pair.of(slot, itemStack.copy()));
diff --git a/net/minecraft/server/level/ServerPlayer.java b/net/minecraft/server/level/ServerPlayer.java
index 336a1ae13810207696a699a936d4031eb904d0dd..82e8b3bfd1c30f6cd4a2af4b67c34e7d16c09cd2 100644
--- a/net/minecraft/server/level/ServerPlayer.java
+++ b/net/minecraft/server/level/ServerPlayer.java
@@ -1422,7 +1422,7 @@ public class ServerPlayer extends Player implements ca.spottedleaf.moonrise.patc
this.getInventory().getNonEquipmentItems().set(i, net.minecraft.world.item.ItemStack.EMPTY);
}
}
- for (final EquipmentSlot value : EquipmentSlot.VALUES) {
+ for (final EquipmentSlot value : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
if (this.getInventory().equipment.has(value) && !shouldKeepDeathEventItem(event, this.getInventory().equipment.get(value))) {
this.getInventory().equipment.set(value, net.minecraft.world.item.ItemStack.EMPTY);
}
diff --git a/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/net/minecraft/server/network/ServerGamePacketListenerImpl.java
index ee4b6d293c32c00e6173cf8efe8aecce67574e6e..15bc120dad98d993f1c8a0a73dbd3be2de37ff72 100644
--- a/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerGamePacketListenerImpl.java
@@ -3009,7 +3009,7 @@ public class ServerGamePacketListenerImpl
// SPIGOT-7136 - Allays
if (target instanceof net.minecraft.world.entity.animal.allay.Allay || target instanceof net.minecraft.world.entity.animal.equine.AbstractHorse) { // Paper - Fix horse armor desync
ServerGamePacketListenerImpl.this.send(new net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket(
- target.getId(), java.util.Arrays.stream(net.minecraft.world.entity.EquipmentSlot.values())
+ target.getId(), java.util.Arrays.stream(net.minecraft.world.entity.EquipmentSlot.VALUES_ARRAY) // Gale - JettPack - reduce array allocations
.map((slot) -> com.mojang.datafixers.util.Pair.of(slot, ((LivingEntity) target).getItemBySlot(slot).copy()))
.collect(Collectors.toList()), true)); // Paper - sanitize
player.containerMenu.sendAllDataToRemote();
diff --git a/net/minecraft/server/players/StoredUserList.java b/net/minecraft/server/players/StoredUserList.java
index cf6c71db3dd39094608755998ceff6ca067238f3..1353fdfb68d8dbedafd64ac69d2869b22c6bfe09 100644
--- a/net/minecraft/server/players/StoredUserList.java
+++ b/net/minecraft/server/players/StoredUserList.java
@@ -96,7 +96,7 @@ public abstract class StoredUserList<K, V extends StoredUserEntry<K>> {
}
public String[] getUserList() {
- return this.map.keySet().toArray(new String[0]);
+ return this.map.keySet().toArray(me.titaniumtown.ArrayConstants.emptyStringArray); // Gale - JettPack - reduce array allocations
}
public boolean isEmpty() {
diff --git a/net/minecraft/util/NullOps.java b/net/minecraft/util/NullOps.java
index c7510c99c68c66a64d391b67d93f31cfcd3dccf0..5785ecf52bbd68e6df0f25b917722999addb6a20 100644
--- a/net/minecraft/util/NullOps.java
+++ b/net/minecraft/util/NullOps.java
@@ -171,7 +171,7 @@ public class NullOps implements DynamicOps<Unit> {
@Override
public DataResult<ByteBuffer> getByteBuffer(final Unit input) {
- return DataResult.success(ByteBuffer.wrap(new byte[0]));
+ return DataResult.success(ByteBuffer.wrap(me.titaniumtown.ArrayConstants.emptyByteArray)); // Gale - JettPack - reduce array allocations
}
@Override
diff --git a/net/minecraft/util/ZeroBitStorage.java b/net/minecraft/util/ZeroBitStorage.java
index 3666c3efd188508153b6482db425648e3ca77dc7..6c52fcac63fb2b79472ff10cb9f544f347a3fcdd 100644
--- a/net/minecraft/util/ZeroBitStorage.java
+++ b/net/minecraft/util/ZeroBitStorage.java
@@ -5,7 +5,7 @@ import java.util.function.IntConsumer;
import org.apache.commons.lang3.Validate;
public class ZeroBitStorage implements BitStorage {
- public static final long[] RAW = new long[0];
+ public static final long[] RAW = me.titaniumtown.ArrayConstants.emptyLongArray; // Gale - JettPack - reduce array allocations
private final int size;
public ZeroBitStorage(final int size) {
diff --git a/net/minecraft/world/entity/ConversionType.java b/net/minecraft/world/entity/ConversionType.java
index e5e268a1b2e8c1d728d39e66a53a5ad17fa6694f..59514750c3024d0f16512d2cd2c5b79f297c7beb 100644
--- a/net/minecraft/world/entity/ConversionType.java
+++ b/net/minecraft/world/entity/ConversionType.java
@@ -37,7 +37,7 @@ public enum ConversionType {
}
if (params.keepEquipment()) {
- for (EquipmentSlot slot : EquipmentSlot.VALUES) {
+ for (EquipmentSlot slot : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
ItemStack itemStack = from.getItemBySlot(slot);
if (!itemStack.isEmpty()) {
to.setItemSlot(slot, itemStack.copyAndClear());
diff --git a/net/minecraft/world/entity/EquipmentSlot.java b/net/minecraft/world/entity/EquipmentSlot.java
index ffb5f07697e9f1fb07f83ea4739c6b9d5a622892..63a9956f4aaf6feb6de2ef59a2211448f816e4fb 100644
--- a/net/minecraft/world/entity/EquipmentSlot.java
+++ b/net/minecraft/world/entity/EquipmentSlot.java
@@ -20,6 +20,7 @@ public enum EquipmentSlot implements StringRepresentable {
SADDLE(EquipmentSlot.Type.SADDLE, 0, 1, 7, "saddle");
public static final int NO_COUNT_LIMIT = 0;
+ public static final EquipmentSlot[] VALUES_ARRAY = values(); // Gale - JettPack - reduce array allocations
public static final List<EquipmentSlot> VALUES = List.of(values());
public static final IntFunction<EquipmentSlot> BY_ID = ByIdMap.continuous(s -> s.id, values(), ByIdMap.OutOfBoundsStrategy.ZERO);
public static final StringRepresentable.EnumCodec<EquipmentSlot> CODEC = StringRepresentable.fromEnum(EquipmentSlot::values);
diff --git a/net/minecraft/world/entity/EquipmentSlotGroup.java b/net/minecraft/world/entity/EquipmentSlotGroup.java
index e9b1290f24ba30663110abc61310d0a1e784e5a1..0112c19b99c62dde19af1009030c1645297163d9 100644
--- a/net/minecraft/world/entity/EquipmentSlotGroup.java
+++ b/net/minecraft/world/entity/EquipmentSlotGroup.java
@@ -24,6 +24,7 @@ public enum EquipmentSlotGroup implements StringRepresentable, Iterable<Equipmen
BODY(9, "body", EquipmentSlot.BODY),
SADDLE(10, "saddle", EquipmentSlot.SADDLE);
+ public static final EquipmentSlotGroup[] VALUES_ARRAY = EquipmentSlotGroup.values(); // Gale - JettPack - reduce array allocations
public static final IntFunction<EquipmentSlotGroup> BY_ID = ByIdMap.continuous(s -> s.id, values(), ByIdMap.OutOfBoundsStrategy.ZERO);
public static final Codec<EquipmentSlotGroup> CODEC = StringRepresentable.fromEnum(EquipmentSlotGroup::values);
public static final StreamCodec<ByteBuf, EquipmentSlotGroup> STREAM_CODEC = ByteBufCodecs.idMapper(BY_ID, s -> s.id);
diff --git a/net/minecraft/world/entity/EquipmentTable.java b/net/minecraft/world/entity/EquipmentTable.java
index 4b018c64d3123bb7a0687491d2ac3a535302890c..0e4d6c9a35d29c240a0cf30694211ea3db66895c 100644
--- a/net/minecraft/world/entity/EquipmentTable.java
+++ b/net/minecraft/world/entity/EquipmentTable.java
@@ -35,7 +35,7 @@ public record EquipmentTable(ResourceKey<LootTable> lootTable, Map<EquipmentSlot
}
private static Map<EquipmentSlot, Float> createForAllSlots(final float dropChance) {
- return createForAllSlots(List.of(EquipmentSlot.values()), dropChance);
+ return createForAllSlots(List.of(EquipmentSlot.VALUES_ARRAY), dropChance); // Gale - JettPack - reduce array allocations
}
private static Map<EquipmentSlot, Float> createForAllSlots(final List<EquipmentSlot> slots, final float dropChance) {
diff --git a/net/minecraft/world/entity/LivingEntity.java b/net/minecraft/world/entity/LivingEntity.java
index 1cb8265c1313ad4893d45c344b03007fc4e2de4b..fcaeb471dada57e9ba4d224693cefbff2fa631be 100644
--- a/net/minecraft/world/entity/LivingEntity.java
+++ b/net/minecraft/world/entity/LivingEntity.java
@@ -3609,7 +3609,7 @@ public abstract class LivingEntity extends Entity implements Attackable, Waypoin
Map<org.bukkit.inventory.EquipmentSlot, io.papermc.paper.event.entity.EntityEquipmentChangedEvent.EquipmentChange> equipmentChanges = null;
// Paper end - EntityEquipmentChangedEvent
- for (EquipmentSlot slot : EquipmentSlot.VALUES) {
+ for (EquipmentSlot slot : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
ItemStack previous = lastEquipmentItems.get(slot);
ItemStack current = this.getItemBySlot(slot);
if (this.equipmentHasChanged(previous, current)) {
@@ -3892,7 +3892,7 @@ public abstract class LivingEntity extends Entity implements Attackable, Waypoin
protected boolean canGlide() {
if (!this.onGround() && !this.isPassenger() && !this.hasEffect(MobEffects.LEVITATION)) {
- for (EquipmentSlot slot : EquipmentSlot.VALUES) {
+ for (EquipmentSlot slot : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
if (canGlideUsing(this.getItemBySlot(slot), slot)) {
return true;
}
diff --git a/net/minecraft/world/entity/decoration/ArmorStand.java b/net/minecraft/world/entity/decoration/ArmorStand.java
index 9e4293c6df1851a852423b469577388d2254e169..952b09fba4cf7de90110a7aa4b96dc03afab25e1 100644
--- a/net/minecraft/world/entity/decoration/ArmorStand.java
+++ b/net/minecraft/world/entity/decoration/ArmorStand.java
@@ -484,7 +484,7 @@ public class ArmorStand extends LivingEntity {
if (this.deathDropItems == null) this.deathDropItems = new java.util.ArrayList<>(); // Paper
this.dropAllDeathLoot(level, source);
- for (EquipmentSlot slot : EquipmentSlot.VALUES) {
+ for (EquipmentSlot slot : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
this.postDeathEventTasks.add(() -> this.equipment.set(slot, ItemStack.EMPTY)); // Paper - move equipment removal past event call
ItemStack itemStack = this.equipment.get(slot); // Paper
if (!itemStack.isEmpty() && !EnchantmentHelper.has(itemStack, EnchantmentEffectComponents.PREVENT_EQUIPMENT_DROP)) {
diff --git a/net/minecraft/world/entity/player/Player.java b/net/minecraft/world/entity/player/Player.java
index ab0f42c6ed9ba4f920eefba4d1449ded6dda0fe9..df412aa8c29307b6186c1c9435cb589c8ed2da22 100644
--- a/net/minecraft/world/entity/player/Player.java
+++ b/net/minecraft/world/entity/player/Player.java
@@ -346,7 +346,7 @@ public abstract class Player extends Avatar implements ContainerUser {
}
private boolean isEquipped(final Item item) {
- for (EquipmentSlot slot : EquipmentSlot.VALUES) {
+ for (EquipmentSlot slot : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
ItemStack itemStack = this.getItemBySlot(slot);
Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE);
if (itemStack.is(item) && equippable != null && equippable.slot() == slot) {
diff --git a/net/minecraft/world/item/ItemStack.java b/net/minecraft/world/item/ItemStack.java
index b384ddb0eedb9286f27705554952a2eacc05d6db..9445551c6c4b67c9c278b541ca2c9b01ab19096a 100644
--- a/net/minecraft/world/item/ItemStack.java
+++ b/net/minecraft/world/item/ItemStack.java
@@ -1182,7 +1182,7 @@ public final class ItemStack implements DataComponentHolder, ItemInstance, Chang
private void addAttributeTooltips(final Consumer<Component> consumer, final TooltipDisplay display, final @Nullable Player player) {
if (display.shows(DataComponents.ATTRIBUTE_MODIFIERS)) {
- for (EquipmentSlotGroup slot : EquipmentSlotGroup.values()) {
+ for (EquipmentSlotGroup slot : EquipmentSlotGroup.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
MutableBoolean first = new MutableBoolean(true);
this.forEachModifier(slot, (attribute, modifier, tooltip) -> {
if (tooltip != ItemAttributeModifiers.Display.hidden()) {
diff --git a/net/minecraft/world/item/crafting/ShapedRecipePattern.java b/net/minecraft/world/item/crafting/ShapedRecipePattern.java
index b2ca30b84a6f498a2b18145eb1efaea7c4c5c943..f60e6188d25c13fc433931b0e8760869ccee8fb0 100644
--- a/net/minecraft/world/item/crafting/ShapedRecipePattern.java
+++ b/net/minecraft/world/item/crafting/ShapedRecipePattern.java
@@ -121,7 +121,7 @@ public final class ShapedRecipePattern {
}
if (pattern.size() == bottom) {
- return new String[0];
+ return me.titaniumtown.ArrayConstants.emptyStringArray; // Gale - JettPack - reduce array allocations
}
String[] result = new String[pattern.size() - bottom - top];
diff --git a/net/minecraft/world/item/enchantment/Enchantment.java b/net/minecraft/world/item/enchantment/Enchantment.java
index 0d981b86fa7ee8713e2a419fc2f377defbc2ed9c..26d850a0ee40c5042e99689f8bd67d8859c42d40 100644
--- a/net/minecraft/world/item/enchantment/Enchantment.java
+++ b/net/minecraft/world/item/enchantment/Enchantment.java
@@ -107,7 +107,7 @@ public record Enchantment(Component description, Enchantment.EnchantmentDefiniti
public Map<EquipmentSlot, ItemStack> getSlotItems(final LivingEntity entity) {
Map<EquipmentSlot, ItemStack> itemStacks = Maps.newEnumMap(EquipmentSlot.class);
- for (EquipmentSlot slot : EquipmentSlot.VALUES) {
+ for (EquipmentSlot slot : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
if (this.matchingSlot(slot)) {
ItemStack itemStack = entity.getItemBySlot(slot);
if (!itemStack.isEmpty()) {
diff --git a/net/minecraft/world/item/enchantment/EnchantmentHelper.java b/net/minecraft/world/item/enchantment/EnchantmentHelper.java
index ed84782f4fcaec8f12ab68641a42ad6e09079875..4f2017c4ca12dcedb9587e0d3d3c9a6be4996167 100644
--- a/net/minecraft/world/item/enchantment/EnchantmentHelper.java
+++ b/net/minecraft/world/item/enchantment/EnchantmentHelper.java
@@ -157,7 +157,7 @@ public class EnchantmentHelper {
}
private static void runIterationOnEquipment(final LivingEntity owner, final EnchantmentHelper.EnchantmentInSlotVisitor method) {
- for (EquipmentSlot slot : EquipmentSlot.VALUES) {
+ for (EquipmentSlot slot : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
runIterationOnItem(owner.getItemBySlot(slot), slot, owner, method);
}
}
@@ -495,7 +495,7 @@ public class EnchantmentHelper {
) {
List<EnchantedItemInUse> items = new ArrayList<>();
- for (EquipmentSlot slot : EquipmentSlot.VALUES) {
+ for (EquipmentSlot slot : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
ItemStack item = source.getItemBySlot(slot);
if (predicate.test(item)) {
ItemEnchantments enchantments = item.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY);
diff --git a/net/minecraft/world/level/Level.java b/net/minecraft/world/level/Level.java
index a6d1f8ccf2e33394508d8d14bec2141942e31ccd..582796847afc202bca408cd6c3135462ecf432a5 100644
--- a/net/minecraft/world/level/Level.java
+++ b/net/minecraft/world/level/Level.java
@@ -1966,7 +1966,7 @@ public abstract class Level implements LevelAccessor, AutoCloseable, ca.spottedl
public org.bukkit.entity.Entity[] getChunkEntities(int chunkX, int chunkZ) {
ca.spottedleaf.moonrise.patches.chunk_system.level.entity.ChunkEntitySlices slices = ((ServerLevel)this).moonrise$getEntityLookup().getChunk(chunkX, chunkZ);
if (slices == null) {
- return new org.bukkit.entity.Entity[0];
+ return me.titaniumtown.ArrayConstants.emptyBukkitEntityArray; // Gale - JettPack - reduce array allocations
}
List<org.bukkit.entity.Entity> ret = new java.util.ArrayList<>();
@@ -1977,7 +1977,7 @@ public abstract class Level implements LevelAccessor, AutoCloseable, ca.spottedl
}
}
- return ret.toArray(new org.bukkit.entity.Entity[0]);
+ return ret.toArray(me.titaniumtown.ArrayConstants.emptyBukkitEntityArray); // Gale - JettPack - reduce array allocations
}
// Paper end - rewrite chunk system
diff --git a/net/minecraft/world/level/block/ComposterBlock.java b/net/minecraft/world/level/block/ComposterBlock.java
index 82f041a6c72eb09d365b5f83dd4731467ad49563..d7a64b74dd3eed07f641cfe6d758a3eb0fb6ef5b 100644
--- a/net/minecraft/world/level/block/ComposterBlock.java
+++ b/net/minecraft/world/level/block/ComposterBlock.java
@@ -434,7 +434,7 @@ public class ComposterBlock extends Block implements WorldlyContainerHolder {
@Override
public int[] getSlotsForFace(final Direction direction) {
- return new int[0];
+ return me.titaniumtown.ArrayConstants.emptyIntArray; // Gale - JettPack - reduce array allocations
}
@Override
@@ -469,7 +469,7 @@ public class ComposterBlock extends Block implements WorldlyContainerHolder {
@Override
public int[] getSlotsForFace(final Direction direction) {
- return direction == Direction.UP ? new int[]{0} : new int[0];
+ return direction == Direction.UP ? me.titaniumtown.ArrayConstants.zeroSingletonIntArray : me.titaniumtown.ArrayConstants.emptyIntArray; // Gale - JettPack - reduce array allocations
}
@Override
@@ -521,7 +521,7 @@ public class ComposterBlock extends Block implements WorldlyContainerHolder {
@Override
public int[] getSlotsForFace(final Direction direction) {
- return direction == Direction.DOWN ? new int[]{0} : new int[0];
+ return direction == Direction.DOWN ? me.titaniumtown.ArrayConstants.zeroSingletonIntArray : me.titaniumtown.ArrayConstants.emptyIntArray; // Gale - JettPack - reduce array allocations
}
@Override
diff --git a/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java b/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java
index 601471d7578b93f30d8033bfab4d4050a8ef78f8..abf73b5f5f780cb3ba947da4067c5ded1a53699a 100644
--- a/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java
+++ b/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java
@@ -44,7 +44,7 @@ public abstract class AbstractFurnaceBlockEntity extends BaseContainerBlockEntit
protected static final int SLOT_FUEL = 1;
protected static final int SLOT_RESULT = 2;
public static final int DATA_LIT_TIME = 0;
- private static final int[] SLOTS_FOR_UP = new int[]{0};
+ private static final int[] SLOTS_FOR_UP = me.titaniumtown.ArrayConstants.zeroSingletonIntArray; // Gale - JettPack - reduce array allocations
private static final int[] SLOTS_FOR_DOWN = new int[]{2, 1};
private static final int[] SLOTS_FOR_SIDES = new int[]{1};
public static final int DATA_LIT_DURATION = 1;
diff --git a/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java b/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java
index e00caf8dc68ce49f4011f881f3558347fe848822..a9201522bdca5a6e6aae48624d3f95fcb0e3d941 100644
--- a/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java
+++ b/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java
@@ -268,7 +268,7 @@ public class MapItemSavedData extends SavedData {
}
private static boolean hasMapInvisibilityItemEquipped(final Player player) {
- for (EquipmentSlot equipmentSlot : EquipmentSlot.values()) {
+ for (EquipmentSlot equipmentSlot : EquipmentSlot.VALUES_ARRAY) { // Gale - JettPack - reduce array allocations
if (equipmentSlot != EquipmentSlot.MAINHAND
&& equipmentSlot != EquipmentSlot.OFFHAND
&& player.getItemBySlot(equipmentSlot).is(ItemTags.MAP_INVISIBILITY_EQUIPMENT)) {
@@ -0,0 +1,80 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: MrHua269 <mrhua269@gmail.com>
Date: Fri, 1 May 2026 21:51:11 +0800
Subject: [PATCH] Some optimizations from krypton
A part of krypton's mixin:
https://github.com/astei/krypton/blob/master/src/main/java/me/steinborn/krypton/mixin/shared/network/microopt/StringEncodingMixin.java and https://github.com/astei/krypton/blob/master/src/main/java/me/steinborn/krypton/mixin/shared/network/microopt/VarIntsMixin.java
Original project license: https://github.com/astei/krypton/blob/master/LICENSE
diff --git a/net/minecraft/network/Utf8String.java b/net/minecraft/network/Utf8String.java
index 8b778744a5f01943976f180ad340a1cbce7db506..f3e514d801ab14d3baaf1943b7cbca1b2a26492b 100644
--- a/net/minecraft/network/Utf8String.java
+++ b/net/minecraft/network/Utf8String.java
@@ -33,6 +33,22 @@ public class Utf8String {
}
public static void write(final ByteBuf output, final CharSequence value, final int maxLength) {
+ // Shiroha start - Krypton optimizations
+ if (true) {
+ if (value.length() > maxLength) {
+ throw new EncoderException("String too big (was " + value.length() + " characters, max " + maxLength + ")");
+ }
+ int utf8Bytes = ByteBufUtil.utf8Bytes(value);
+ int maxBytesPermitted = ByteBufUtil.utf8MaxBytes(maxLength);
+ if (utf8Bytes > maxBytesPermitted) {
+ throw new EncoderException("String too big (was " + utf8Bytes + " bytes encoded, max " + maxBytesPermitted + ")");
+ } else {
+ VarInt.write(output, utf8Bytes);
+ output.writeCharSequence(value, StandardCharsets.UTF_8);
+ }
+ return;
+ }
+ // Shiroha end
if (value.length() > maxLength) {
throw new EncoderException("String too big (was " + value.length() + " characters, max " + maxLength + ")");
}
diff --git a/net/minecraft/network/VarInt.java b/net/minecraft/network/VarInt.java
index 1428ce80e8316a24cfca7b6aafdea8588a5a790e..740182c0b1c6918e81a45dddba1c4f488b8762b3 100644
--- a/net/minecraft/network/VarInt.java
+++ b/net/minecraft/network/VarInt.java
@@ -60,7 +60,8 @@ public class VarInt {
int s = (value & 0x7F | 0x80) << 8 | (value >>> 7);
output.writeShort(s);
} else {
- writeSlow(output, value);
+ // writeSlow(output, value); // Shiroha - Krypton optimizations
+ writeVarIntFull(output, value); // Shiroha - Krypton optimizations
}
return output;
}
@@ -74,4 +75,27 @@ public class VarInt {
output.writeByte(value);
return output;
}
+ // Shiroha start - Krypton optimizations
+ private static void writeVarIntFull(ByteBuf buf, int value) {
+ // See https://steinborn.me/posts/performance/how-fast-can-you-write-a-varint/
+ if ((value & (0xFFFFFFFF << 7)) == 0) {
+ buf.writeByte(value);
+ } else if ((value & (0xFFFFFFFF << 14)) == 0) {
+ int w = (value & 0x7F | 0x80) << 8 | (value >>> 7);
+ buf.writeShort(w);
+ } else if ((value & (0xFFFFFFFF << 21)) == 0) {
+ int w = (value & 0x7F | 0x80) << 16 | ((value >>> 7) & 0x7F | 0x80) << 8 | (value >>> 14);
+ buf.writeMedium(w);
+ } else if ((value & (0xFFFFFFFF << 28)) == 0) {
+ int w = (value & 0x7F | 0x80) << 24 | (((value >>> 7) & 0x7F | 0x80) << 16)
+ | ((value >>> 14) & 0x7F | 0x80) << 8 | (value >>> 21);
+ buf.writeInt(w);
+ } else {
+ int w = (value & 0x7F | 0x80) << 24 | ((value >>> 7) & 0x7F | 0x80) << 16
+ | ((value >>> 14) & 0x7F | 0x80) << 8 | ((value >>> 21) & 0x7F | 0x80);
+ buf.writeInt(w);
+ buf.writeByte(value >>> 28);
+ }
+ }
+ // Shiroha end
}