diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3d87b2d..726217f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1 +1,2 @@
-# ChangeLog- no changes
+# ChangeLog
+- no changes
diff --git a/README.md b/README.md
index 7e09b55..5fb486d 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,17 @@
-# ModularMCLib-Template
\ No newline at end of file
+# ModularMCLib Utils
+
+面向 Minecraft 26.1.2、NeoForge 26.1.2.126 与 Java 25 的通用工具库。模组标识为 `mmclutils`。
+
+## 安装与构建
+
+将发布的完整 JAR 放入客户端或专用服的 `mods` 目录。
+
+在仓库根目录运行 Gradle Wrapper,产物位于 `build/libs/`。
+
+```powershell
+.\gradlew.bat build
+```
+
+## 许可
+
+本项目采用 GNU AGPL 3.0。 [许可证](src/main/resources/META-INF/licenses/AGPL-3.0.txt)
diff --git a/build.gradle b/build.gradle
index 79ecb17..d06d878 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,14 +1,14 @@
plugins {
id 'java-library'
- id 'org.jetbrains.kotlin.jvm'
id 'eclipse'
id 'idea'
id 'maven-publish'
- id 'jacoco'
alias libs.plugins.modDevGradle
//alias libs.plugins.shadow
alias libs.plugins.spotless
alias libs.plugins.lombok
+ alias libs.plugins.kotlin.jvm
+ alias libs.plugins.kotlin.lombok
}
group = maven_group
@@ -32,11 +32,6 @@ sourceSets {
runtimeClasspath += main.output + main.runtimeClasspath
}
- test {
- compileClasspath += main.output + main.compileClasspath
- runtimeClasspath += main.output + main.runtimeClasspath
- }
-
extra {
compileClasspath += main.output
runtimeClasspath += main.output + main.runtimeClasspath
@@ -82,41 +77,9 @@ tasks.withType(JavaCompile).configureEach {
}
tasks.withType(Test).configureEach {
- // Test sources are NeoForge GameTests and are executed by runGameTestServer, not JUnit.
failOnNoDiscoveredTests = false
}
lombok {
version = "1.18.38"
}
-
-jacoco {
- applyTo runGameTestServer
-}
-
-jacocoTestReport {
- doFirst {
- try {
- runGameTestServer.exec()
- } catch (RuntimeException ignored) {}
- }
- doLast {
- println "Coverage report location:"
- println " - file://${layout.buildDirectory.dir('coverage').map(a -> a.file('index.html')).get()}"
- println " - file://${layout.buildDirectory.dir('coverage').map(a -> a.file('coverage.xml')).get()}"
- }
- executionData runGameTestServer
- sourceSets sourceSets.test
- reports {
- csv.required = false
- xml.required = true
- html.outputLocation = layout.buildDirectory.dir('coverage')
- xml.outputLocation = layout.buildDirectory.dir('coverage').map(a -> a.file('coverage.xml'))
- }
- afterEvaluate {
- classDirectories.setFrom(files(classDirectories.files.collect {
- fileTree(dir: it, exclude: '**/client/**')
- fileTree(dir: it, exclude: '**/mixins/**')
- }))
- }
-}
diff --git a/dependencies.gradle b/dependencies.gradle
index 374cb52..662eb14 100644
--- a/dependencies.gradle
+++ b/dependencies.gradle
@@ -1,7 +1,13 @@
dependencies {
compileOnly(libs.jetbrains.annotations)
+ compileOnly(libs.jspecify)
- testImplementation(libs.testframework.get())
+ // 与 Minecraft 共用运行库,供使用原始类型集合的公共接口声明依赖。
+ api(libs.fastutil)
+
+ jarJar(api(libs.kotlin.stdlib.get())) {
+ exclude group: 'org.jetbrains', module: 'annotations'
+ }
// Runtime Recipe Viewers - uncomment whichever one you want to use //
diff --git a/gradle.properties b/gradle.properties
index e6e567a..5ee6016 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -4,11 +4,11 @@ org.gradle.parallel = true
org.gradle.caching = true
# Mod Info
-mod_id = template
-mod_name = Template
+mod_id = mmclutils
+mod_name = ModularMCLibUtils
mod_version = 0.0.3
mod_description =
mod_license = GNU AGPL 3.0
-mod_url = https://github.com/ModularMCLib/SyncedData-Lib/
-mod_issue_tracker = https://github.com/ModularMCLib/SyncedData-Lib/issues/
-maven_group = com.modularmc.synceddata
+mod_url = https://github.com/ModularMCLib/ModularMCLib-Utils/
+mod_issue_tracker = https://github.com/ModularMCLib/ModularMCLib-Utils/issues/
+maven_group = com.modularmc.mmclutils
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index c819654..95277ed 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -1,23 +1,33 @@
[versions]
minecraft = "26.1.2"
-neoForge = "26.1.2.41-beta"
+neoForge = "26.1.2.126"
+lombok = "9.8.2"
loader = "4"
-spotless = "8.4.0"
-modDevGradle = "2.0.141"
-lombok = "9.5.0"
+shadow = "9.6.1"
+spotless = "8.11.0"
+modDevGradle = "2.0.148"
+kotlin = "2.4.21"
jetbrains-annotations = "26.1.0"
-renderNurse = "0.0.14"
+jspecify = "1.0.0"
+fastutil = "8.5.18"
+renderNurse = "0.0.26"
mixin = "0.8.7"
[libraries]
minecraft = { module = "com.mojang:minecraft", version.ref = "minecraft" }
neoForge = { module = "net.neoforged:neoforge", version.ref = "neoForge" }
testframework = { module = "net.neoforged:testframework", version.ref = "neoForge" }
-jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" }
+kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" }
renderNurse = { module = "net.neoforged:render-nurse", version.ref = "renderNurse" }
mixin = { module = "org.spongepowered:mixin", version.ref = "mixin" }
+jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" }
+jspecify = { module = "org.jspecify:jspecify", version.ref = "jspecify" }
+fastutil = { module = "it.unimi.dsi:fastutil", version.ref = "fastutil" }
[plugins]
modDevGradle = { id = "net.neoforged.moddev", version.ref = "modDevGradle" }
+shadow = { id = "com.gradleup.shadow", version.ref = "shadow" }
spotless = { id = "com.diffplug.spotless", version.ref = "spotless" }
-lombok = { id = "io.freefair.lombok", version.ref = "lombok" }
\ No newline at end of file
+lombok = { id = "io.freefair.lombok", version.ref = "lombok" }
+kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
+kotlin-lombok = { id = "org.jetbrains.kotlin.plugin.lombok", version.ref = "kotlin" }
diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle
index e09356e..cd13acd 100644
--- a/gradle/scripts/jars.gradle
+++ b/gradle/scripts/jars.gradle
@@ -12,7 +12,7 @@ java {
withSourcesJar()
}
-// Use delombok'd files for sources
+// 将 Lombok 生成的成员一并纳入源码包。
sourcesJar {
exclude {
sourceSets.main.allSource.contains it.file
@@ -28,7 +28,6 @@ afterEvaluate {
tasks.withType(org.gradle.jvm.tasks.Jar).configureEach {
destinationDirectory = file('build/libs/')
manifest.attributes([
- 'MixinConfigs': "synceddata.mixins.json",
'Specification-Title': project.name,
'Specification-Version': mod_version,
'Specification-Vendor': 'ModularMCLib Team',
diff --git a/gradle/scripts/moddevgradle.gradle b/gradle/scripts/moddevgradle.gradle
index 630b42c..2c0af81 100644
--- a/gradle/scripts/moddevgradle.gradle
+++ b/gradle/scripts/moddevgradle.gradle
@@ -24,7 +24,6 @@ neoForge {
"${mod_id}" {
sourceSet(sourceSets.main)
sourceSet(sourceSets.client)
- sourceSet(sourceSets.test)
sourceSet(sourceSets.extra)
sourceSet(sourceSets.clientExtra)
}
@@ -38,7 +37,6 @@ neoForge {
gameDirectory.set(file('run/client'))
- systemProperty('neoforge.enabledGameTestNamespaces', project.mod_id)
}
server {
@@ -48,60 +46,22 @@ neoForge {
gameDirectory.set(file('run/server'))
programArguments.addAll('--nogui', '--world', 'world-extra')
- systemProperty('neoforge.enabledGameTestNamespaces', project.mod_id)
}
- // This run config launches GameTestServer and runs all registered gametests, then exits.
- // By default, the server will crash when no gametests are provided.
- // The gametest system is also enabled by default for other run configs under the /test command.
+ // 让持续集成使用原版自带用例启动服务器、推进 Tick 并退出。
gameTestServer {
type = "gameTestServer"
- sourceSet = sourceSets.test
+ sourceSet = sourceSets.extra
ideName = "Game Tests"
gameDirectory.set(file('run/gametest/server'))
- systemProperty('neoforge.enabledGameTestNamespaces', project.mod_id)
- environment('TEST', 'true')
- }
-
- gameTestClient {
- client()
- sourceSet = sourceSets.test
- ideName = "Game Tests (Client)"
-
- gameDirectory.set(file('run/gametest/client'))
- systemProperty('neoforge.enabledGameTestNamespaces', project.mod_id)
- environment('TEST', 'true')
- }
-
- data {
- clientData()
- serverData()
- sourceSet = sourceSets.main
- ideName = "Data Generation"
-
- gameDirectory.set(file('run/data'))
- // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
- programArguments.addAll('--mod', project.mod_id)
- programArguments.addAll('--all')
- programArguments.addAll('--output', file('src/generated/resources/').getAbsolutePath())
- programArguments.addAll('--existing', file('src/main/resources/').getAbsolutePath())
+ programArguments.addAll('--tests', 'minecraft:always_pass')
}
// applies to all the run configs above
configureEach {
- // Recommended logging data for a userdev environment
- // The markers can be added/remove as needed separated by commas.
- // "SCAN": For mods scan.
- // "REGISTRIES": For firing of registry events.
- // "REGISTRYDUMP": For getting the contents of all registries.
systemProperty 'forge.logging.markers', 'REGISTRIES'
- // Enable assertions for our classes in dev environment
jvmArgument('-ea:com.modularmc.template...')
-
- // Recommended logging level for the console
- // You can set various levels here.
- // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
logLevel = org.slf4j.event.Level.INFO
}
}
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index f8e1ee3..51cbd2a 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 1a70468..04d7959 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,7 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-bin.zip
networkTimeout=10000
+retries=0
+retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
index adff685..249efbb 100644
--- a/gradlew
+++ b/gradlew
@@ -20,7 +20,7 @@
##############################################################################
#
-# Gradle start up script for POSIX generated by Gradle.
+# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
@@ -29,7 +29,7 @@
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
-# ksh Gradle
+# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
@@ -57,7 +57,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
-# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
diff --git a/gradlew.bat b/gradlew.bat
index c4bdd3a..3185a43 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -19,12 +19,39 @@
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
-@rem Gradle startup script for Windows
+@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
+@rem Set local scope for the variables, and ensure extensions are enabled
+setlocal EnableExtensions
+
+@rem Catch executions from older scripts and ensure they exit cleanly.
+@rem This can be removed once we can be reasonably confident that few people
+@rem will be migrating directly to this new wrapper.
+goto afterSafetyNet
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+goto exitWithErrorLevel
+:afterSafetyNet
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@@ -45,13 +72,14 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
-echo. 1>&2
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
-echo. 1>&2
-echo Please set the JAVA_HOME variable in your environment to match the 1>&2
-echo location of your Java installation. 1>&2
+1>&2 echo.
+1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+1>&2 echo.
+1>&2 echo Please set the JAVA_HOME variable in your environment to match the
+1>&2 echo location of your Java installation.
-goto fail
+"%COMSPEC%" /c exit 1
+goto exitWithErrorLevel
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
@@ -59,35 +87,26 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
-echo. 1>&2
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
-echo. 1>&2
-echo Please set the JAVA_HOME variable in your environment to match the 1>&2
-echo location of your Java installation. 1>&2
+1>&2 echo.
+1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+1>&2 echo.
+1>&2 echo Please set the JAVA_HOME variable in your environment to match the
+1>&2 echo location of your Java installation.
-goto fail
+"%COMSPEC%" /c exit 1
+goto exitWithErrorLevel
:execute
@rem Setup the command line
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
+@rem Execute gradlew
+@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
+@rem which allows us to clear the local environment before executing the java command
+endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
-:end
-@rem End local scope for the variables with windows NT shell
-if %ERRORLEVEL% equ 0 goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-set EXIT_CODE=%ERRORLEVEL%
-if %EXIT_CODE% equ 0 set EXIT_CODE=1
-if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
-exit /b %EXIT_CODE%
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
+@rem This label must not be changed. We rely on old scripts being able to jump to this point.
+:exitWithErrorLevel
+@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
+"%COMSPEC%" /c exit %ERRORLEVEL%
diff --git a/settings.gradle b/settings.gradle
index 5c1624c..3253339 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -5,13 +5,10 @@ pluginManagement {
maven { url = 'https://maven.neoforged.net/releases' }
maven { url = "https://maven.quiltmc.org/repository/release" }
}
- plugins {
- id 'org.jetbrains.kotlin.jvm' version '2.3.20'
- }
}
plugins {
- id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0'
+ id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
}
dependencyResolutionManagement {
diff --git a/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java
new file mode 100644
index 0000000..1d087a4
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/ModularMCLibUtils.java
@@ -0,0 +1,108 @@
+package com.modularmc.mmclutils;
+
+import com.modularmc.mmclutils.api.input.SyncedKeyMappings;
+import com.modularmc.mmclutils.client.ModularMCLibUtilsClient;
+
+import net.minecraft.resources.Identifier;
+import net.minecraft.server.MinecraftServer;
+import net.neoforged.bus.api.IEventBus;
+import net.neoforged.fml.ModList;
+import net.neoforged.fml.common.Mod;
+import net.neoforged.fml.loading.FMLEnvironment;
+import net.neoforged.fml.loading.FMLLoader;
+import net.neoforged.fml.loading.FMLPaths;
+import net.neoforged.neoforge.data.loading.DatagenModLoader;
+import net.neoforged.neoforge.server.ServerLifecycleHooks;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.jspecify.annotations.Nullable;
+
+import java.nio.file.Path;
+
+/** 注册双端入口,并提供模组标识、服务器访问和运行环境查询。 */
+@Mod(ModularMCLibUtils.MOD_ID)
+public class ModularMCLibUtils {
+
+ /** 该模组在加载器和资源标识中使用的命名空间。 */
+ public static final String MOD_ID = "mmclutils";
+ /** 面向加载器显示的模组名称。 */
+ public static final String MOD_NAME = "ModularMCLib Utils";
+ /** 用于库自身运行日志的记录器。 */
+ public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
+
+ /**
+ * 登记双端共用的模组总线监听器。
+ *
+ * @param modBus 当前模组的事件总线
+ */
+ public ModularMCLibUtils(IEventBus modBus) {
+ SyncedKeyMappings.init(modBus);
+ }
+
+ /**
+ * 使用库的命名空间构造资源标识。
+ *
+ * @param path 标识路径
+ * @return 属于 {@link #MOD_ID} 的标识
+ */
+ public static Identifier id(String path) {
+ return Identifier.fromNamespaceAndPath(MOD_ID, path);
+ }
+
+ /** 返回当前专用服或本地集成服。服务器尚未启动或已停止时返回空值。 */
+ public static @Nullable MinecraftServer getServer() {
+ return ServerLifecycleHooks.getCurrentServer();
+ }
+
+ /**
+ * 在所属服务器主线程执行命令,并抑制命令反馈。
+ *
+ * @param server 要执行命令的服务器
+ * @param command 不带斜杠前缀的命令文本
+ */
+ public static void runCommandSilent(MinecraftServer server, String command) {
+ server.getCommands().performPrefixedCommand(server.createCommandSourceStack().withSuppressedOutput(), command);
+ }
+
+ /** 返回当前游戏实例目录。 */
+ public static Path getGameDir() {
+ return FMLPaths.GAMEDIR.get();
+ }
+
+ /** 判断当前运行是否为生产环境。 */
+ public static boolean isProd() {
+ return FMLEnvironment.isProduction();
+ }
+
+ /** 判断当前运行是否为开发环境。 */
+ public static boolean isDev() {
+ return !isProd();
+ }
+
+ /** 判断加载器是否正在运行数据生成。 */
+ public static boolean isDataGen() {
+ return DatagenModLoader.isRunningDataGen();
+ }
+
+ /**
+ * 判断模组是否已加载。在模组列表尚未创建的加载早期使用加载列表查询。
+ *
+ * @param modId 要查询的命名空间
+ * @return 存在对应模组时为 {@code true}
+ */
+ public static boolean isModLoaded(String modId) {
+ ModList mods = ModList.get();
+ return mods == null ? FMLLoader.getCurrent().getLoadingModList().getModFileById(modId) != null : mods.isLoaded(modId);
+ }
+
+ /** 判断物理运行端。集成服务器所在进程同样返回真。 */
+ public static boolean isClientSide() {
+ return FMLEnvironment.getDist().isClient();
+ }
+
+ /** 判断当前线程是否为物理客户端主线程。专用服务器上始终返回假。 */
+ public static boolean isClientThread() {
+ return isClientSide() && ModularMCLibUtilsClient.isClientThread();
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityIndex.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityIndex.java
new file mode 100644
index 0000000..b949c20
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityIndex.java
@@ -0,0 +1,149 @@
+package com.modularmc.mmclutils.api.blockentity;
+
+import com.modularmc.mmclutils.api.level.BlockIndex;
+import com.modularmc.mmclutils.api.level.BlockRange;
+import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder;
+
+import net.minecraft.core.BlockPos;
+import net.minecraft.world.level.Level;
+import net.minecraft.world.level.block.entity.BlockEntity;
+
+import org.jspecify.annotations.Nullable;
+
+import java.util.Collection;
+import java.util.function.Consumer;
+import java.util.function.Predicate;
+
+/**
+ * 按类型维护方块实体索引。区块放入、替换、移除方块实体以及区块卸载时会自动更新。
+ * 必须在模组加载阶段创建(声明成静态常量,并在模组构造时触发所在类初始化),维度开始加载方块实体后再创建会抛异常。功能:
+ *
+ * - {@link #create(Class)}:收录运行时类是该类型子类型的方块实体;{@link #create(Class, Predicate)}:另在登记时判一次条件,只收录通过的
+ * - {@link #all()}:全部方块实体共用的一份索引,供只能逐个判断能力的查找和 {@link ProbedBlockEntityIndex} 的待探测部分使用;第一次调用时创建,同样必须在加载阶段调用
+ * - {@link #query}/{@link #forEach}/{@link #findAny}/{@link #findNearest}:按 {@link BlockRange} 查某维度范围内的方块实体,语义同
+ * {@link BlockIndex}
+ * - {@link #findAny(Level, Predicate)}/{@link #forEach(Level, Consumer)}:遍历某维度全部收录的方块实体
+ * - {@link #get}/{@link #size}/{@link #version}:按坐标取、数量、内容变化计数
+ * - 索引存放在维度实例上,随维度回收;只在拥有该维度的线程上查询
+ *
+ *
+ * @param 收录的方块实体类型或由方块实体实现的接口
+ */
+public final class BlockEntityIndex {
+
+ private final TypedSink sink;
+
+ private BlockEntityIndex(TypedSink sink) {
+ this.sink = sink;
+ }
+
+ /** 为指定类或接口建立索引,兼容实现该类型的方块实体。 */
+ public static BlockEntityIndex create(Class type) {
+ return create(type, null);
+ }
+
+ /**
+ * 在模组加载阶段创建一个按类型自动登记的索引。
+ *
+ * @param 收录的方块实体类型或接口
+ * @param type 用于筛选方块实体的运行时类型
+ * @param admit 只在方块实体登记时执行的附加条件,为空时接纳全部对应类型
+ * @return 由加载区块维护的索引
+ * @throws IllegalStateException 已开始跟踪方块实体
+ */
+ public static BlockEntityIndex create(Class type, @Nullable Predicate super T> admit) {
+ return new BlockEntityIndex<>(BlockEntityTracking.TRACKER.register(new TypedSink<>(type, admit)));
+ }
+
+ /** 返回包含所有已登记原版方块实体的共享索引。 */
+ public static BlockEntityIndex all() {
+ return All.INDEX;
+ }
+
+ private static final class All {
+
+ static final BlockEntityIndex INDEX = create(BlockEntity.class);
+ }
+
+ TypedSink sink() {
+ return sink;
+ }
+
+ private @Nullable BlockIndex index(Level level) {
+ return sink.index((SlotHolder) level);
+ }
+
+ /** 向集合追加范围内通过筛选的方块实体。筛选可为空,返回集合实际增加的数量。 */
+ public int query(Level level, int x, int y, int z, BlockRange range, @Nullable Predicate super T> filter, Collection super T> out) {
+ BlockIndex index = index(level);
+ return index == null ? 0 : index.query(x, y, z, range, filter, out);
+ }
+
+ /** 使用方块位置作为查询中心,并将结果加入调用方提供的集合。 */
+ public int query(Level level, BlockPos center, BlockRange range, @Nullable Predicate super T> filter, Collection super T> out) {
+ return query(level, center.getX(), center.getY(), center.getZ(), range, filter, out);
+ }
+
+ /** 在世界线程访问范围内的匹配实体。回调不应修改正在遍历的索引。 */
+ public void forEach(Level level, int x, int y, int z, BlockRange range, @Nullable Predicate super T> filter, Consumer super T> action) {
+ BlockIndex index = index(level);
+ if (index != null) index.query(x, y, z, range, filter, action);
+ }
+
+ /** 以方块位置作为中心连续处理匹配值。 */
+ public void forEach(Level level, BlockPos center, BlockRange range, @Nullable Predicate super T> filter, Consumer super T> action) {
+ forEach(level, center.getX(), center.getY(), center.getZ(), range, filter, action);
+ }
+
+ /** 查找范围内任一符合条件的实体,未命中时返回空值。 */
+ public @Nullable T findAny(Level level, int x, int y, int z, BlockRange range, @Nullable Predicate super T> filter) {
+ BlockIndex index = index(level);
+ return index == null ? null : index.findAny(x, y, z, range, filter);
+ }
+
+ /** 以方块位置为中心查找任一匹配实体。 */
+ public @Nullable T findAny(Level level, BlockPos center, BlockRange range, @Nullable Predicate super T> filter) {
+ return findAny(level, center.getX(), center.getY(), center.getZ(), range, filter);
+ }
+
+ /** 按平方欧氏距离查找最近实体,未命中时返回空值。 */
+ public @Nullable T findNearest(Level level, int x, int y, int z, BlockRange range, @Nullable Predicate super T> filter) {
+ BlockIndex index = index(level);
+ return index == null ? null : index.findNearest(x, y, z, range, filter);
+ }
+
+ /** 以方块位置为中心查找最近的匹配实体。 */
+ public @Nullable T findNearest(Level level, BlockPos center, BlockRange range, @Nullable Predicate super T> filter) {
+ return findNearest(level, center.getX(), center.getY(), center.getZ(), range, filter);
+ }
+
+ /** 在当前维度的全部已索引实体中查找任意匹配项。 */
+ public @Nullable T findAny(Level level, Predicate super T> filter) {
+ BlockIndex index = index(level);
+ return index == null ? null : index.findAny(filter);
+ }
+
+ /** 遍历该维度已索引的实体,回调中不要修改索引。 */
+ public void forEach(Level level, Consumer super T> action) {
+ BlockIndex index = index(level);
+ if (index != null) index.forEach(action);
+ }
+
+ /** 按位置查询当前索引中的实体。条目缺失时返回空值。 */
+ public @Nullable T get(Level level, BlockPos pos) {
+ BlockIndex index = index(level);
+ return index == null ? null : index.get(pos);
+ }
+
+ /** 读取此维度内保存的条目总数。 */
+ public int size(Level level) {
+ BlockIndex index = index(level);
+ return index == null ? 0 : index.size();
+ }
+
+ /** 读取本维度索引的修改版本,索引尚未创建时返回零。 */
+ public int version(Level level) {
+ BlockIndex index = index(level);
+ return index == null ? 0 : index.version();
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityTracking.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityTracking.java
new file mode 100644
index 0000000..a4bec78
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/BlockEntityTracking.java
@@ -0,0 +1,93 @@
+package com.modularmc.mmclutils.api.blockentity;
+
+import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder;
+
+import net.minecraft.core.BlockPos;
+import net.minecraft.world.level.block.entity.BlockEntity;
+import net.minecraft.world.level.chunk.LevelChunk;
+
+import org.jetbrains.annotations.ApiStatus;
+import org.jspecify.annotations.Nullable;
+
+/** 维护方块实体与区块可见性变化对应的空间索引状态。 */
+@ApiStatus.Internal
+public final class BlockEntityTracking {
+
+ static final Tracker TRACKER = new Tracker<>(new Tracker.Access<>() {
+
+ @Override
+ public @Nullable SlotHolder holder(BlockEntity be) {
+ return be.getLevel() instanceof SlotHolder holder ? holder : null;
+ }
+
+ @Override
+ public BlockPos pos(BlockEntity be) {
+ return be.getBlockPos();
+ }
+
+ @Override
+ public boolean live(BlockEntity be) {
+ return !be.isRemoved();
+ }
+
+ @Override
+ public int probedMask(BlockEntity be) {
+ return ((TrackedBlockEntity) be).mmclutils$probedMask();
+ }
+
+ @Override
+ public void setProbedMask(BlockEntity be, int mask) {
+ ((TrackedBlockEntity) be).mmclutils$setProbedMask(mask);
+ }
+ });
+
+ private BlockEntityTracking() {}
+
+ /** 在实体加入其所在区块后登记可探测索引。 */
+ public static void added(BlockEntity be) {
+ TRACKER.added(be);
+ }
+
+ /** 在实体移除或替换前撤销其索引登记。 */
+ public static void removed(BlockEntity be) {
+ TRACKER.removed(be);
+ }
+
+ /**
+ * 切换整个区块在空间索引中的可见性,并同步处理当前保存的方块实体。
+ *
+ * @param chunk 要更新的区块
+ * @param visible 区块应参与索引查询时为 {@code true}
+ */
+ public static void setVisible(LevelChunk chunk, boolean visible) {
+ TrackedChunk tracked = (TrackedChunk) chunk;
+ if (tracked.mmclutils$hidden() != visible) return;
+ tracked.mmclutils$setHidden(!visible);
+ for (BlockEntity be : chunk.getBlockEntities().values()) {
+ if (visible) TRACKER.added(be);
+ else TRACKER.removed(be);
+ }
+ }
+
+ /** 方块实体在探测索引中使用的候选位标记。 */
+ @ApiStatus.Internal
+ public interface TrackedBlockEntity {
+
+ /** 返回已通过探测并登记的索引位掩码。 */
+ int mmclutils$probedMask();
+
+ /** 将索引登记位掩码替换为指定值。 */
+ void mmclutils$setProbedMask(int mask);
+ }
+
+ /** 区块从可见列表移除时用于暂停其中的方块实体登记。 */
+ @ApiStatus.Internal
+ public interface TrackedChunk {
+
+ /** 查询区块当前是否已从索引隐藏。 */
+ boolean mmclutils$hidden();
+
+ /** 记录显隐切换,由索引同步方块实体。 */
+ void mmclutils$setHidden(boolean hidden);
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedBlockEntityIndex.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedBlockEntityIndex.java
new file mode 100644
index 0000000..a2643fc
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedBlockEntityIndex.java
@@ -0,0 +1,106 @@
+package com.modularmc.mmclutils.api.blockentity;
+
+import com.modularmc.mmclutils.api.level.BlockRange;
+import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder;
+
+import net.minecraft.core.BlockPos;
+import net.minecraft.world.level.Level;
+import net.minecraft.world.level.block.entity.BlockEntity;
+
+import org.jspecify.annotations.Nullable;
+
+import java.util.Collection;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Predicate;
+
+/**
+ * 按能力自动维护的方块实体索引:分类器按类把方块实体分为不收录、候选(确定提供)、待探测(可能提供)三种,
+ * 待探测的不另外存放,查询第一次覆盖到所在区段时从 {@link BlockEntityIndex#all()} 取出来用探测条件判一次,结果按实例记在方块实体上,
+ * 之后只走候选。适合能力挂在任意方块实体上、逐个判断很贵的查找;能力会随时变化的,查询结果使用前仍要再取一次能力。
+ * 创建时机要求同 {@link BlockEntityIndex},最多 32 个。功能:
+ *
+ * - {@link #create(Function, Predicate)}:分类器每个类只调用一次,返回 null
+ * 视为不收录;{@link #create(Function, Predicate, Predicate)}:另在登记时判一次条件
+ * - {@link #query}/{@link #forEach}/{@link #findAny}:先探测范围内还没探测过的方块实体,再按 {@link BlockRange} 查候选
+ * - {@link #candidateCount}/{@link #sweptSectionCount}:某维度候选数与已扫过的区段数
+ *
+ */
+public final class ProbedBlockEntityIndex {
+
+ /** 按方块实体类型为自动索引选择的处理方式。 */
+ public enum Kind {
+ /** 不把此类型登记到索引。 */
+ NONE,
+ /** 登记为可直接参与空间查询的候选。 */
+ CANDIDATE,
+ /** 仅在查询覆盖所在区段时按需执行探测条件。 */
+ PROBE
+ }
+
+ private final ProbedSink sink;
+
+ private ProbedBlockEntityIndex(ProbedSink sink) {
+ this.sink = sink;
+ }
+
+ /**
+ * 创建按类型分类并按需探测的方块实体索引。
+ *
+ * @param classifier 将方块实体类型分类为不收录、候选或按需探测
+ * @param probe 匹配查询触达的待探测实体时执行的能力检查
+ * @return 新的索引,登记在创建后出现的索引条目上
+ */
+ public static ProbedBlockEntityIndex create(Function, Kind> classifier, Predicate super BlockEntity> probe) {
+ return create(classifier, probe, null);
+ }
+
+ /**
+ * 创建具有额外登记过滤条件的按需探测索引。
+ *
+ * @param classifier 将方块实体类型分类为不收录、候选或按需探测
+ * @param probe 查询触达待探测实体时的能力检查
+ * @param admit 登记或实体状态变化时的候选过滤条件,可以为空
+ * @return 新的按需探测索引
+ */
+ public static ProbedBlockEntityIndex create(Function, Kind> classifier, Predicate super BlockEntity> probe,
+ @Nullable Predicate super BlockEntity> admit) {
+ Tracker tracker = BlockEntityTracking.TRACKER;
+ TypedSink all = BlockEntityIndex.all().sink();
+ return new ProbedBlockEntityIndex(tracker.register(new ProbedSink<>(tracker, all, classifier, probe, admit)));
+ }
+
+ /**
+ * 在指定范围查找候选,并把匹配项追加至输出集合。
+ *
+ * @param level 要查询的维度
+ * @param center 范围中心
+ * @param range 球形或长方体范围
+ * @param filter 可选的最终结果过滤条件
+ * @param out 接收匹配方块实体的集合
+ * @return 追加到集合中的条目数
+ */
+ public int query(Level level, BlockPos center, BlockRange range, @Nullable Predicate super BlockEntity> filter, Collection super BlockEntity> out) {
+ return sink.query((SlotHolder) level, center.getX(), center.getY(), center.getZ(), range, filter, out);
+ }
+
+ /** 对范围内匹配的方块实体依次执行操作。 */
+ public void forEach(Level level, BlockPos center, BlockRange range, @Nullable Predicate super BlockEntity> filter, Consumer super BlockEntity> action) {
+ sink.forEach((SlotHolder) level, center.getX(), center.getY(), center.getZ(), range, filter, action);
+ }
+
+ /** 返回范围内第一个满足过滤条件的方块实体,没有匹配项时返回空值。 */
+ public @Nullable BlockEntity findAny(Level level, BlockPos center, BlockRange range, @Nullable Predicate super BlockEntity> filter) {
+ return sink.findAny((SlotHolder) level, center.getX(), center.getY(), center.getZ(), range, filter);
+ }
+
+ /** 返回此维度当前已登记的候选实体数量。 */
+ public int candidateCount(Level level) {
+ return sink.candidateCount((SlotHolder) level);
+ }
+
+ /** 返回此维度已执行过按需探测的区段数量。 */
+ public int sweptSectionCount(Level level) {
+ return sink.sweptSectionCount((SlotHolder) level);
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedSink.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedSink.java
new file mode 100644
index 0000000..0c2b9d6
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/ProbedSink.java
@@ -0,0 +1,180 @@
+package com.modularmc.mmclutils.api.blockentity;
+
+import com.modularmc.mmclutils.api.level.BlockIndex;
+import com.modularmc.mmclutils.api.level.BlockRange;
+import com.modularmc.mmclutils.api.level.LevelStore;
+import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder;
+
+import net.minecraft.core.BlockPos;
+import net.minecraft.core.SectionPos;
+
+import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
+import org.jspecify.annotations.Nullable;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Predicate;
+
+/**
+ * 按能力收录对象的自动索引:类确定提供的直接进候选树;类可能提供的不另存,查询第一次覆盖到某个 16³ 区段时,从共用的全量索引里取出
+ * 区段内还没被本索引探测过的对象探测一次,通过的进候选树,区段记为已扫过;之后落进已扫过区段的对象记进新增树,被查询覆盖时再探测。功能:
+ *
+ * - {@link #accepts}:按类分为不收录、候选、待探测三种,每个类只判一次;同一分发器下最多 32 个本类索引,每个占对象上探测标记的一位
+ * - {@link #added}:候选类登记时判一次条件后进候选树;待探测类只有落进已扫过的区段时才记进新增树,其余不占任何存储
+ * - {@link #removed}:从候选树和新增树注销这个对象本身,并清掉它的探测标记;已扫过的区段保持有效
+ * - {@link #forEach}/{@link #findAny}/{@link #query}:先扫范围内未扫过的区段、探测范围内的新增对象(已失效的不探测),再查候选树;
+ * 范围覆盖的区段超过 {@link #MAX_SECTIONS} 个时直接逐个检查范围内的对象,不记区段;探测中再次查询也安全
+ * - {@link #candidateCount}/{@link #sweptSectionCount}/{@link #freshCount}:某维度候选数、已扫过的区段数与待探测的新增数
+ *
+ */
+final class ProbedSink extends Tracker.Sink {
+
+ static final int MAX_SECTIONS = 4096;
+
+ static final class State {
+
+ final BlockIndex candidates = new BlockIndex<>();
+ final BlockIndex fresh = new BlockIndex<>();
+ final LongOpenHashSet swept = new LongOpenHashSet();
+ final ArrayList scratch = new ArrayList<>();
+ int depth;
+ }
+
+ private final ClassValue kinds;
+ private final Predicate super E> probe;
+ private final @Nullable Predicate super E> admit;
+ private final Tracker.Access access;
+ private final TypedSink all;
+ private final int bit;
+ private final LevelStore> store = LevelStore.create(State::new);
+
+ ProbedSink(Tracker tracker, TypedSink all, Function, ProbedBlockEntityIndex.Kind> classifier,
+ Predicate super E> probe, @Nullable Predicate super E> admit) {
+ this.bit = tracker.allocateProbeBit();
+ this.access = tracker.access();
+ this.all = all;
+ this.probe = probe;
+ this.admit = admit;
+ this.kinds = new ClassValue<>() {
+
+ @Override
+ protected ProbedBlockEntityIndex.Kind computeValue(Class> type) {
+ ProbedBlockEntityIndex.Kind kind = classifier.apply(type);
+ return kind == null ? ProbedBlockEntityIndex.Kind.NONE : kind;
+ }
+ };
+ }
+
+ @Override
+ boolean accepts(Class> type) {
+ return kinds.get(type) != ProbedBlockEntityIndex.Kind.NONE;
+ }
+
+ @Override
+ void added(SlotHolder holder, E e, BlockPos pos) {
+ if (kinds.get(e.getClass()) == ProbedBlockEntityIndex.Kind.CANDIDATE) {
+ if (admit != null && !admit.test(e)) return;
+ store.forHolder(holder).candidates.put(pos, e);
+ } else {
+ State state = store.forHolderIfPresent(holder);
+ if (state != null && state.swept.contains(SectionPos.asLong(pos))) state.fresh.put(pos, e);
+ }
+ }
+
+ @Override
+ void removed(SlotHolder holder, E e, BlockPos pos) {
+ int mask = access.probedMask(e);
+ if ((mask & bit) != 0) access.setProbedMask(e, mask & ~bit);
+ State state = store.forHolderIfPresent(holder);
+ if (state == null) return;
+ state.candidates.remove(pos, e);
+ state.fresh.remove(pos, e);
+ }
+
+ void forEach(SlotHolder holder, int x, int y, int z, BlockRange range, @Nullable Predicate super E> filter, Consumer super E> action) {
+ State state = prepare(holder, x, y, z, range);
+ if (state != null && !state.candidates.isEmpty()) state.candidates.query(x, y, z, range, filter, action);
+ }
+
+ int query(SlotHolder holder, int x, int y, int z, BlockRange range, @Nullable Predicate super E> filter, Collection super E> out) {
+ State state = prepare(holder, x, y, z, range);
+ return state == null || state.candidates.isEmpty() ? 0 : state.candidates.query(x, y, z, range, filter, out);
+ }
+
+ @Nullable
+ E findAny(SlotHolder holder, int x, int y, int z, BlockRange range, @Nullable Predicate super E> filter) {
+ State state = prepare(holder, x, y, z, range);
+ return state == null || state.candidates.isEmpty() ? null : state.candidates.findAny(x, y, z, range, filter);
+ }
+
+ int candidateCount(SlotHolder holder) {
+ State state = store.forHolderIfPresent(holder);
+ return state == null ? 0 : state.candidates.size();
+ }
+
+ int sweptSectionCount(SlotHolder holder) {
+ State state = store.forHolderIfPresent(holder);
+ return state == null ? 0 : state.swept.size();
+ }
+
+ int freshCount(SlotHolder holder) {
+ State state = store.forHolderIfPresent(holder);
+ return state == null ? 0 : state.fresh.size();
+ }
+
+ @Nullable
+ private State prepare(SlotHolder holder, int x, int y, int z, BlockRange range) {
+ BlockIndex source = all.index(holder);
+ if (source == null || source.isEmpty() || range.isEmpty()) return store.forHolderIfPresent(holder);
+ State state = store.forHolder(holder);
+ long minX = Math.max((long) x - range.radiusX(), BlockIndex.MIN_XZ), maxX = Math.min((long) x + range.radiusX(), BlockIndex.MAX_XZ);
+ long minY = Math.max((long) y - range.radiusY(), BlockIndex.MIN_Y), maxY = Math.min((long) y + range.radiusY(), BlockIndex.MAX_Y);
+ long minZ = Math.max((long) z - range.radiusZ(), BlockIndex.MIN_XZ), maxZ = Math.min((long) z + range.radiusZ(), BlockIndex.MAX_XZ);
+ if (minX > maxX || minY > maxY || minZ > maxZ) return state;
+ int sx0 = (int) minX >> 4, sx1 = (int) maxX >> 4, sy0 = (int) minY >> 4, sy1 = (int) maxY >> 4, sz0 = (int) minZ >> 4, sz1 = (int) maxZ >> 4;
+ long sections = (long) (sx1 - sx0 + 1) * (sy1 - sy0 + 1) * (sz1 - sz0 + 1);
+ if (sections > MAX_SECTIONS) {
+ sweep(state, source, x, y, z, range, Integer.MIN_VALUE, 0, 0);
+ return state;
+ }
+ for (int sx = sx0; sx <= sx1; sx++) {
+ for (int sz = sz0; sz <= sz1; sz++) {
+ for (int sy = sy0; sy <= sy1; sy++) {
+ if (!state.swept.add(SectionPos.asLong(sx, sy, sz))) continue;
+ sweep(state, source, (sx << 4) + 8, (sy << 4) + 8, (sz << 4) + 8, BlockRange.box(8), sx, sy, sz);
+ }
+ }
+ }
+ if (!state.fresh.isEmpty()) sweep(state, state.fresh, x, y, z, range, Integer.MIN_VALUE, 0, 0);
+ return state;
+ }
+
+ private void sweep(State state, BlockIndex source, int x, int y, int z, BlockRange range, int sx, int sy, int sz) {
+ boolean section = sx != Integer.MIN_VALUE;
+ List found = state.depth == 0 ? state.scratch : new ArrayList<>();
+ found.clear();
+ source.query(x, y, z, range, null, found);
+ if (found.isEmpty()) return;
+ state.depth++;
+ try {
+ for (int i = 0, n = found.size(); i < n; i++) {
+ E e = found.get(i);
+ if (kinds.get(e.getClass()) != ProbedBlockEntityIndex.Kind.PROBE) continue;
+ BlockPos pos = access.pos(e);
+ if (section && ((pos.getX() >> 4) != sx || (pos.getY() >> 4) != sy || (pos.getZ() >> 4) != sz)) continue;
+ int mask = access.probedMask(e);
+ if ((mask & bit) != 0) continue;
+ access.setProbedMask(e, mask | bit);
+ if (!section && !state.fresh.isEmpty()) state.fresh.remove(pos, e);
+ if (admit != null && !admit.test(e)) continue;
+ if (access.live(e) && probe.test(e)) state.candidates.put(pos, e);
+ }
+ } finally {
+ state.depth--;
+ found.clear();
+ }
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/Tracker.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/Tracker.java
new file mode 100644
index 0000000..be01b8c
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/Tracker.java
@@ -0,0 +1,113 @@
+package com.modularmc.mmclutils.api.blockentity;
+
+import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder;
+
+import net.minecraft.core.BlockPos;
+
+import org.jspecify.annotations.Nullable;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * 把带坐标对象的登记、注销分发给关心它的索引:按对象的运行时类缓存一次关心它的索引列表,没有索引关心的类只做一次缓存查找。功能:
+ *
+ * - {@link #register}:登记一个索引;第一次分发之后再登记会抛 {@link IllegalStateException},保证类缓存与已登记的对象一致
+ * - {@link #added}/{@link #removed}:把对象交给按类缓存的索引,对象不在任何维度时忽略
+ * - {@link #started}:是否已经分发过;{@link #allocateProbeBit}:给按能力收录的索引分配对象探测标记里的一位,最多 32 位
+ *
+ */
+final class Tracker {
+
+ interface Access {
+
+ @Nullable
+ SlotHolder holder(E e);
+
+ BlockPos pos(E e);
+
+ boolean live(E e);
+
+ int probedMask(E e);
+
+ void setProbedMask(E e, int mask);
+ }
+
+ abstract static class Sink {
+
+ abstract boolean accepts(Class> type);
+
+ abstract void added(SlotHolder holder, E e, BlockPos pos);
+
+ abstract void removed(SlotHolder holder, E e, BlockPos pos);
+ }
+
+ private final Access access;
+ private final List> sinks = new CopyOnWriteArrayList<>();
+ private final ClassValue[]> byClass = new ClassValue<>() {
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected Sink[] computeValue(Class> type) {
+ List> list = new ArrayList<>();
+ for (Sink sink : sinks) {
+ if (sink.accepts(type)) list.add(sink);
+ }
+ return list.toArray(new Sink[0]);
+ }
+ };
+ private volatile boolean started;
+ private int probeBits;
+
+ Tracker(Access access) {
+ this.access = access;
+ }
+
+ Access access() {
+ return access;
+ }
+
+ synchronized > S register(S sink) {
+ if (started) {
+ throw new IllegalStateException("block entity indexes must be created during mod loading, before any level loads block entities");
+ }
+ sinks.add(sink);
+ return sink;
+ }
+
+ synchronized int allocateProbeBit() {
+ if (probeBits >= 32) throw new IllegalStateException("too many probed indexes (max 32)");
+ return 1 << probeBits++;
+ }
+
+ boolean started() {
+ return started;
+ }
+
+ private void start() {
+ synchronized (this) {
+ started = true;
+ }
+ }
+
+ void added(E e) {
+ if (!started) start();
+ Sink[] targets = byClass.get(e.getClass());
+ if (targets.length == 0) return;
+ SlotHolder holder = access.holder(e);
+ if (holder == null) return;
+ BlockPos pos = access.pos(e);
+ for (Sink sink : targets) sink.added(holder, e, pos);
+ }
+
+ void removed(E e) {
+ if (!started) start();
+ Sink[] targets = byClass.get(e.getClass());
+ if (targets.length == 0) return;
+ SlotHolder holder = access.holder(e);
+ if (holder == null) return;
+ BlockPos pos = access.pos(e);
+ for (Sink sink : targets) sink.removed(holder, e, pos);
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/blockentity/TypedSink.java b/src/main/java/com/modularmc/mmclutils/api/blockentity/TypedSink.java
new file mode 100644
index 0000000..dd692f0
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/blockentity/TypedSink.java
@@ -0,0 +1,55 @@
+package com.modularmc.mmclutils.api.blockentity;
+
+import com.modularmc.mmclutils.api.level.BlockIndex;
+import com.modularmc.mmclutils.api.level.LevelStore;
+import com.modularmc.mmclutils.api.level.LevelStore.SlotHolder;
+
+import net.minecraft.core.BlockPos;
+
+import org.jspecify.annotations.Nullable;
+
+import java.util.function.Predicate;
+
+/**
+ * 按类型收录对象的自动索引:对象的运行时类是 {@code type} 的子类型、且登记时通过 {@code admit} 的对象进入所在维度的 {@link BlockIndex}。功能:
+ *
+ * - {@link #accepts}:按类判断是否关心,供 {@link Tracker} 缓存
+ * - {@link #added}:登记时判一次 {@code admit},通过就放进该维度的索引,同一坐标已有对象时替换
+ * - {@link #removed}:只有该坐标登记的正是这个对象时才注销
+ * - {@link #index}:取某维度的索引,没有登记过时返回 null
+ *
+ */
+final class TypedSink extends Tracker.Sink {
+
+ private final Class type;
+ private final @Nullable Predicate super T> admit;
+ private final LevelStore> store = LevelStore.create(BlockIndex::new);
+
+ TypedSink(Class type, @Nullable Predicate super T> admit) {
+ this.type = type;
+ this.admit = admit;
+ }
+
+ @Override
+ boolean accepts(Class> c) {
+ return type.isAssignableFrom(c);
+ }
+
+ @Override
+ void added(SlotHolder holder, E e, BlockPos pos) {
+ T t = type.cast(e);
+ if (admit != null && !admit.test(t)) return;
+ store.forHolder(holder).put(pos, t);
+ }
+
+ @Override
+ void removed(SlotHolder holder, E e, BlockPos pos) {
+ BlockIndex index = store.forHolderIfPresent(holder);
+ if (index != null) index.remove(pos, type.cast(e));
+ }
+
+ @Nullable
+ BlockIndex index(SlotHolder holder) {
+ return store.forHolderIfPresent(holder);
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/capability/AdjacentBlockCapabilityCache.java b/src/main/java/com/modularmc/mmclutils/api/capability/AdjacentBlockCapabilityCache.java
new file mode 100644
index 0000000..c8dba88
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/capability/AdjacentBlockCapabilityCache.java
@@ -0,0 +1,103 @@
+package com.modularmc.mmclutils.api.capability;
+
+import net.minecraft.core.BlockPos;
+import net.minecraft.core.Direction;
+import net.minecraft.server.level.ServerLevel;
+import net.neoforged.neoforge.capabilities.BlockCapability;
+import net.neoforged.neoforge.capabilities.BlockCapabilityCache;
+
+import it.unimi.dsi.fastutil.objects.ObjectArrayList;
+import it.unimi.dsi.fastutil.objects.ObjectList;
+import it.unimi.dsi.fastutil.objects.ObjectLists;
+import org.jspecify.annotations.Nullable;
+
+import java.util.EnumMap;
+import java.util.function.BooleanSupplier;
+
+/**
+ * 为固定原点周围的六个方块保留 NeoForge 能力缓存。
+ *
+ * @param 能力类型
+ */
+public final class AdjacentBlockCapabilityCache {
+
+ private final BlockCapability capability;
+ private final ServerLevel level;
+ private final BlockPos origin;
+ private final BooleanSupplier isValid;
+ private final EnumMap> caches = new EnumMap<>(Direction.class);
+
+ /**
+ * 按需建立各方向缓存。失效监听器随所属对象的有效期释放。
+ *
+ * @param capability 查询的方块能力
+ * @param level 目标方块所在的服务端维度
+ * @param origin 查询原点
+ * @param isValid 所属对象的存活判定
+ */
+ public AdjacentBlockCapabilityCache(
+ BlockCapability capability,
+ ServerLevel level,
+ BlockPos origin,
+ BooleanSupplier isValid) {
+ this.capability = capability;
+ this.level = level;
+ this.origin = origin.immutable();
+ this.isValid = isValid;
+ }
+
+ /**
+ * 查询邻接方块朝向原点的面所提供的能力。
+ *
+ * @param side 从原点指向目标的方向
+ * @return 当前能力,目标未暴露该能力时返回 {@code null}
+ */
+ @Nullable
+ public T get(Direction side) {
+ return this.caches.computeIfAbsent(side, this::createCache).getCapability();
+ }
+
+ /**
+ * 按传入的方向顺序查询能力。
+ *
+ * @param sides 参与查询的方向
+ * @return 当前已暴露能力的不可变列表
+ */
+ public ObjectList getAll(Iterable sides) {
+ ObjectList resolved = new ObjectArrayList<>();
+ for (Direction side : sides) {
+ T value = get(side);
+ if (value != null) {
+ resolved.add(value);
+ }
+ }
+ return resolved.isEmpty() ? ObjectList.of() : ObjectLists.unmodifiable(resolved);
+ }
+
+ /**
+ * 查询能力并保留每项对应的方向。
+ *
+ * @param sides 参与查询的方向
+ * @return 按枚举顺序返回方向与能力的独立映射,修改结果不会影响缓存
+ */
+ public EnumMap getAllBySide(Iterable sides) {
+ EnumMap resolved = new EnumMap<>(Direction.class);
+ for (Direction side : sides) {
+ T value = get(side);
+ if (value != null) {
+ resolved.put(side, value);
+ }
+ }
+ return resolved;
+ }
+
+ private BlockCapabilityCache createCache(Direction side) {
+ return BlockCapabilityCache.create(
+ this.capability,
+ this.level,
+ this.origin.relative(side),
+ side.getOpposite(),
+ this.isValid,
+ () -> {});
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/CyclicIterator.java b/src/main/java/com/modularmc/mmclutils/api/collection/CyclicIterator.java
new file mode 100644
index 0000000..4c635ef
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/CyclicIterator.java
@@ -0,0 +1,47 @@
+package com.modularmc.mmclutils.api.collection;
+
+import java.util.Iterator;
+
+/** 依次遍历非空元素集合,到达末尾后从头继续。 */
+public final class CyclicIterator implements Iterable, Iterator {
+
+ /** 供空遍历共用的实例。泛型调用使用 {@link #empty()}。 */
+ public static final CyclicIterator EMPTY = new CyclicIterator(new Object[0]);
+
+ /** 取得可用作任意元素类型的空迭代器。 */
+ public static CyclicIterator empty() {
+ return EMPTY;
+ }
+
+ /** 保留的原始数组引用,迭代器直接读取此数组中的元素。 */
+ public final T[] array;
+ /** 一次遍历所包含的元素数。 */
+ public final int size;
+ private int index;
+ private int remaining;
+
+ /** 包装数组。每次调用 {@link #iterator()} 重置剩余次数,沿用上次停下的数组位置。 */
+ public CyclicIterator(T[] array) {
+ this.array = array;
+ this.size = this.array.length;
+ }
+
+ @Override
+ public Iterator iterator() {
+ remaining = size;
+ return this;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return remaining > 0;
+ }
+
+ @Override
+ public T next() {
+ if (index == size) index = 0;
+ T element = array[index++];
+ remaining--;
+ return element;
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/IntrusiveDeque.java b/src/main/java/com/modularmc/mmclutils/api/collection/IntrusiveDeque.java
new file mode 100644
index 0000000..0bd4150
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/IntrusiveDeque.java
@@ -0,0 +1,272 @@
+package com.modularmc.mmclutils.api.collection;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.function.Consumer;
+
+/** 将链接字段保存在节点上,提供常数时间的队头和队尾操作。 */
+public class IntrusiveDeque> implements Iterable {
+
+ /** 由队列链接操作维护的首节点,空队列时为空值。 */
+ protected T first;
+ /** 由队列链接操作维护的尾节点,空队列时为空值。 */
+ protected T last;
+ /** 当前链接在此队列上的节点数。 */
+ protected int size;
+
+ /** 判断队列是否没有链接节点。 */
+ public boolean isEmpty() {
+ return first == null;
+ }
+
+ /** 取得当前节点数,时间复杂度为常数。 */
+ public int size() {
+ return size;
+ }
+
+ /** 读取首节点,空队列时返回空值。 */
+ public T peekFirst() {
+ return first;
+ }
+
+ /** 读取尾节点,空队列时返回空值。 */
+ public T peekLast() {
+ return last;
+ }
+
+ /** 在队尾链接一个游离节点。调用方须保证该节点未加入任何队列。 */
+ public void addLast(T node) {
+ final T l = last;
+ if (l == null) {
+ first = node;
+ } else {
+ l.setNext(node);
+ node.setPrev(l);
+ }
+ last = node;
+ size++;
+ }
+
+ /** 在队首链接一个游离节点。调用方须保证该节点未加入任何队列。 */
+ public void addFirst(T node) {
+ final T f = first;
+ if (f == null) {
+ last = node;
+ } else {
+ f.setPrev(node);
+ node.setNext(f);
+ }
+ first = node;
+ size++;
+ }
+
+ /** 直接移除且清除已有节点的链接。传入的节点须已属于此队列。 */
+ public void unlink(T node) {
+ final T prev = node.getPrev();
+ final T next = node.getNext();
+ if (prev == null) {
+ first = next;
+ } else {
+ prev.setNext(next);
+ node.setPrev(null);
+ }
+ if (next == null) {
+ last = prev;
+ } else {
+ next.setPrev(prev);
+ node.setNext(null);
+ }
+ size--;
+ }
+
+ /** 若节点已在此队列中则移除。请勿传入属于其他队列的节点。 */
+ public boolean remove(T node) {
+ if (node.getPrev() != null || node.getNext() != null || node == first) {
+ unlink(node);
+ return true;
+ }
+ return false;
+ }
+
+ /** 取出首节点并清理其链接,空队列时返回空值。 */
+ public T pollFirst() {
+ final T f = first;
+ if (f == null) return null;
+ unlink(f);
+ return f;
+ }
+
+ /** 取出尾节点并清理其链接,空队列时返回空值。 */
+ public T pollLast() {
+ final T l = last;
+ if (l == null) return null;
+ unlink(l);
+ return l;
+ }
+
+ /** 取出首节点。空队列时抛出 {@link NoSuchElementException}。 */
+ public T removeFirst() {
+ final T f = pollFirst();
+ if (f == null) throw new NoSuchElementException();
+ return f;
+ }
+
+ /** 取出尾节点。空队列时抛出 {@link NoSuchElementException}。 */
+ public T removeLast() {
+ final T l = pollLast();
+ if (l == null) throw new NoSuchElementException();
+ return l;
+ }
+
+ /** 将另一个队列拼到尾端并清空对方队列。时间复杂度为常数。 */
+ public void merge(IntrusiveDeque other) {
+ if (other.first == null || other == this) return;
+ final T otherFirst = other.first;
+ final T otherLast = other.last;
+ if (last == null) {
+ first = otherFirst;
+ } else {
+ last.setNext(otherFirst);
+ otherFirst.setPrev(last);
+ }
+ last = otherLast;
+ size += other.size;
+ other.first = null;
+ other.last = null;
+ other.size = 0;
+ }
+
+ /** 断开队列中所有节点的前后链接。被清出的节点可以加入另一条队列。 */
+ public void clear() {
+ for (T node = first; node != null;) {
+ T next = node.getNext();
+ node.setPrev(null);
+ node.setNext(null);
+ node = next;
+ }
+ first = null;
+ last = null;
+ size = 0;
+ }
+
+ @Override
+ public Iterator iterator() {
+ return new QueueIterator();
+ }
+
+ /** 按节点身份线性查找。可用于调用者没有节点所属队列信息的情况。 */
+ public boolean contains(T node) {
+ for (T n = first; n != null; n = n.getNext()) {
+ if (n == node) return true;
+ }
+ return false;
+ }
+
+ /** 按队头到队尾的顺序复制节点引用。 */
+ public Object[] toArray() {
+ Object[] arr = new Object[size];
+ int i = 0;
+ for (T n = first; n != null; n = n.getNext()) {
+ arr[i++] = n;
+ }
+ return arr;
+ }
+
+ @Override
+ public void forEach(Consumer super T> action) {
+ for (T n = first; n != null; n = n.getNext()) {
+ action.accept(n);
+ }
+ }
+
+ @Override
+ public Spliterator spliterator() {
+ return Spliterators.spliterator(iterator(), size, Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL);
+ }
+
+ private final class QueueIterator implements Iterator {
+
+ private T nextNode = first;
+ private T currentNode;
+
+ @Override
+ public boolean hasNext() {
+ return nextNode != null;
+ }
+
+ @Override
+ public T next() {
+ var nextNode = this.nextNode;
+ if (nextNode == null) throw new NoSuchElementException();
+ this.currentNode = nextNode;
+ this.nextNode = nextNode.getNext();
+ return nextNode;
+ }
+
+ @Override
+ public void remove() {
+ var currentNode = this.currentNode;
+ if (currentNode == null) throw new IllegalStateException();
+ IntrusiveDeque.this.unlink(currentNode);
+ this.currentNode = null;
+ }
+
+ @Override
+ public void forEachRemaining(Consumer super T> action) {
+ while (hasNext()) action.accept(next());
+ }
+ }
+
+ /**
+ * 为侵入式双端队列提供前后节点链接。
+ * 实现对象同一时刻只能加入一条链,链接初始为空且由所属队列维护。
+ *
+ * @param 实际节点类型
+ */
+ public interface LinkNode> {
+
+ /** 返回当前节点的前驱,作为队首时返回空值。 */
+ T getPrev();
+
+ /** 更新前驱链接,由所属队列调用。 */
+ void setPrev(T prev);
+
+ /** 返回当前节点的后继,作为队尾时返回空值。 */
+ T getNext();
+
+ /** 更新后继链接,由所属队列调用。 */
+ void setNext(T next);
+ }
+
+ /** 直接保存前后链接的节点基类。链接只能由所属队列维护。 */
+ public abstract static class AbstractLinkNode> implements LinkNode {
+
+ /** 前驱节点,游离或在队首时为空值。 */
+ protected T prev;
+
+ /** 后继节点,游离或在队尾时为空值。 */
+ protected T next;
+
+ @Override
+ public T getPrev() {
+ return prev;
+ }
+
+ @Override
+ public void setPrev(T prev) {
+ this.prev = prev;
+ }
+
+ @Override
+ public T getNext() {
+ return next;
+ }
+
+ @Override
+ public void setNext(T next) {
+ this.next = next;
+ }
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/ByteCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ByteCache.java
new file mode 100644
index 0000000..e451d49
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ByteCache.java
@@ -0,0 +1,180 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import it.unimi.dsi.fastutil.HashCommon;
+import it.unimi.dsi.fastutil.bytes.Byte2ObjectFunction;
+
+/**
+ * 使用原始类型 {@code byte} 作为键,强引用缓存值,直到缓存条目被清除。
+ * 计算函数在分段锁外运行,并发写入在锁内合并。
+ *
+ * @param 缓存值类型
+ */
+public final class ByteCache extends SegmentedCache> {
+
+ private final Byte2ObjectFunction extends V> createFunction;
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public ByteCache() {
+ this(SegmentedCache.DEFAULT_CONCURRENCY, null);
+ }
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public ByteCache(Byte2ObjectFunction extends V> createFunction) {
+ this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction);
+ }
+
+ /** 按给定的并发度初始化缓存。并发度必须大于零。 */
+ public ByteCache(int concurrencyLevel) {
+ this(concurrencyLevel, null);
+ }
+
+ /** 按给定的并发度初始化缓存。并发度必须大于零。 */
+ public ByteCache(int concurrencyLevel, Byte2ObjectFunction extends V> createFunction) {
+ super(concurrencyLevel, i -> new Segment<>());
+ this.createFunction = createFunction;
+ }
+
+ /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */
+ public V getCache(final byte k) {
+ int mix = HashCommon.mix(k);
+ return segmentFor(mix).getCache(k, mix, createFunction);
+ }
+
+ /** 在锁外执行计算,允许回调再次访问同一缓存。 */
+ public V getCache(final byte k, Byte2ObjectFunction extends V> createFunction) {
+ int mix = HashCommon.mix(k);
+ return segmentFor(mix).getCache(k, mix, createFunction);
+ }
+
+ /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */
+ public V getIfPresent(final byte k) {
+ int mix = HashCommon.mix(k);
+ return segmentFor(mix).getIfAbsent(k, mix);
+ }
+
+ /** 只在没有有效值时写入,返回最终关联的值。 */
+ public V putIfAbsent(final byte k, final V v) {
+ int mix = HashCommon.mix(k);
+ return segmentFor(mix).put(k, v, mix);
+ }
+
+ /** 清除全部条目。 */
+ public void clear() {
+ clearSegments();
+ }
+
+ static final class Segment extends HashSegment> {
+
+ private Segment() {}
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected Node[] newArray(int capacity) {
+ return new Node[capacity];
+ }
+
+ @Override
+ protected int nodeHash(Node node) {
+ return node.key;
+ }
+
+ /** 在写锁内合并并发变更。 */
+ private V getCache(final byte k, final int mix, Byte2ObjectFunction extends V> createFunction) {
+ long stamp = readLock();
+ try {
+ Node curr = table[mix & mask];
+ while (curr != null) {
+ if (curr.key == k) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ } finally {
+ unlockRead(stamp);
+ }
+ // 在锁外执行计算,允许回调再次访问同一缓存。
+ final var v = createFunction.get(k);
+ stamp = writeLock();
+ try {
+ final int index = mix & mask;
+ Node curr = table[index];
+ while (curr != null) {
+ if (curr.key == k) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ table[index] = new Node<>(k, v, table[index]);
+ if (++size > maxFill) {
+ resize();
+ }
+ return v;
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+
+ /** 只读取现有条目。 */
+ private V getIfAbsent(final byte k, final int mix) {
+ long stamp = readLock();
+ try {
+ Node curr = table[mix & mask];
+ while (curr != null) {
+ if (curr.key == k) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ return null;
+ } finally {
+ unlockRead(stamp);
+ }
+ }
+
+ /** 只在缺少该键时写入。 */
+ private V put(final byte k, final V v, final int mix) {
+ long stamp = writeLock();
+ try {
+ final int index = mix & mask;
+ final Node node = table[index];
+ Node curr = node;
+ while (curr != null) {
+ if (curr.key == k) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ table[index] = new Node<>(k, v, node);
+ if (++size > maxFill) {
+ resize();
+ }
+ return v;
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+ }
+
+ static final class Node implements ChainNode> {
+
+ private final byte key;
+ private final V value;
+ private volatile Node next;
+
+ private Node(byte key, V value, Node next) {
+ this.key = key;
+ this.value = value;
+ this.next = next;
+ }
+
+ @Override
+ public Node getNext() {
+ return next;
+ }
+
+ @Override
+ public void setNext(Node next) {
+ this.next = next;
+ }
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/CacheReferenceQueue.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CacheReferenceQueue.java
new file mode 100644
index 0000000..8ea7a1b
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CacheReferenceQueue.java
@@ -0,0 +1,46 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import java.lang.ref.WeakReference;
+import java.util.concurrent.ConcurrentLinkedDeque;
+
+/** 集中清理由引用队列报告的失效项,避免为每个弱引用缓存启动线程。 */
+final class CacheReferenceQueue {
+
+ private CacheReferenceQueue() {}
+
+ private static final long INTERVAL_MS = 500L;
+
+ private static final ConcurrentLinkedDeque>> CACHES = new ConcurrentLinkedDeque<>();
+
+ static {
+ Thread thread = new Thread(() -> {
+ while (true) {
+ try {
+ Thread.sleep(INTERVAL_MS);
+ } catch (InterruptedException e) {
+ return;
+ }
+ sweep();
+ }
+ }, "mmclutils-cache-drainer");
+ thread.setDaemon(true);
+ thread.setPriority(Thread.MIN_PRIORITY);
+ thread.start();
+ }
+
+ public static void add(WeakSegmentedCache> cache) {
+ CACHES.offerLast(new WeakReference<>(cache));
+ }
+
+ private static void sweep() {
+ var it = CACHES.iterator();
+ while (it.hasNext()) {
+ WeakSegmentedCache> cache = it.next().get();
+ if (cache == null) {
+ it.remove();
+ } else {
+ cache.drainCollected();
+ }
+ }
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/ChainNode.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ChainNode.java
new file mode 100644
index 0000000..5989c4c
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ChainNode.java
@@ -0,0 +1,9 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+/** 分段哈希表的链式节点。重排时只修改后继引用。 */
+interface ChainNode> {
+
+ N getNext();
+
+ void setNext(N next);
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/ConcurrentWeakIdentityHashMap.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ConcurrentWeakIdentityHashMap.java
new file mode 100644
index 0000000..96368be
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/ConcurrentWeakIdentityHashMap.java
@@ -0,0 +1,257 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
+
+import java.io.Serial;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * 支持并发访问的弱键映射。按对象身份比较键,键被回收后由后续访问清理对应的映射。
+ * 值由映射强引用。值若持有其键,键会随值保持可达。
+ *
+ * @param 非空键的类型
+ * @param 非空值的类型
+ */
+@NullMarked
+public class ConcurrentWeakIdentityHashMap extends AbstractMap implements ConcurrentMap {
+
+ private final ConcurrentMap, V> map;
+ private final ReferenceQueue queue = new ReferenceQueue<>();
+ private transient @Nullable Set> entrySet;
+
+ /**
+ * 按预计元素数量创建空映射。
+ *
+ * @param initialCapacity 预计同时保存的键数量,须为非负数
+ * @throws IllegalArgumentException 初始容量为负数
+ */
+ public ConcurrentWeakIdentityHashMap(int initialCapacity) {
+ this.map = new ConcurrentHashMap<>(initialCapacity);
+ }
+
+ /** 使用并发映射的默认初始容量。 */
+ public ConcurrentWeakIdentityHashMap() {
+ this.map = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ public @Nullable V get(Object key) {
+ purgeKeys();
+ return map.get(new Key<>(key, null));
+ }
+
+ @Override
+ public @Nullable V put(K key, V value) {
+ purgeKeys();
+ return map.put(new Key<>(key, queue), value);
+ }
+
+ @Override
+ public int size() {
+ purgeKeys();
+ return map.size();
+ }
+
+ @SuppressWarnings({ "ReassignedVariable", "SuspiciousMethodCalls" })
+ private void purgeKeys() {
+ Reference extends K> reference;
+ while ((reference = queue.poll()) != null) {
+ map.remove(reference);
+ }
+ }
+
+ @Override
+ public Set> entrySet() {
+ Set> entrySet = this.entrySet;
+ return entrySet == null ? this.entrySet = new EntrySet() : entrySet;
+ }
+
+ @Override
+ public @Nullable V putIfAbsent(K key, V value) {
+ purgeKeys();
+ return map.putIfAbsent(new Key<>(key, queue), value);
+ }
+
+ @Override
+ public @Nullable V remove(Object key) {
+ return map.remove(new Key<>(key, null));
+ }
+
+ @Override
+ public boolean remove(Object key, Object value) {
+ purgeKeys();
+ return map.remove(new Key<>(key, null), value);
+ }
+
+ @Override
+ public boolean replace(K key, V oldValue, V newValue) {
+ purgeKeys();
+ return map.replace(new Key<>(key, null), oldValue, newValue);
+ }
+
+ @Override
+ public @Nullable V replace(K key, V value) {
+ purgeKeys();
+ return map.replace(new Key<>(key, null), value);
+ }
+
+ @Override
+ public boolean containsKey(Object key) {
+ purgeKeys();
+ return map.containsKey(new Key<>(key, null));
+ }
+
+ @SuppressWarnings("StatementWithEmptyBody")
+ @Override
+ public void clear() {
+ while (queue.poll() != null);
+ map.clear();
+ }
+
+ @Override
+ public boolean containsValue(Object value) {
+ purgeKeys();
+ return map.containsValue(value);
+ }
+
+ private static class Key extends WeakReference {
+
+ private final int hash;
+
+ Key(T t, @Nullable ReferenceQueue queue) {
+ super(t, queue);
+ if (t == null) {
+ throw new NullPointerException("key");
+ }
+ hash = System.identityHashCode(t);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) return true;
+ T value = get();
+ return value != null && obj instanceof Key> key && key.get() == value;
+ }
+
+ @Override
+ public int hashCode() {
+ return hash;
+ }
+ }
+
+ private class Iter implements Iterator> {
+
+ private final Iterator, V>> it;
+ private Map.@Nullable Entry nextValue;
+ private @Nullable K lastKey;
+
+ Iter(Iterator, V>> it) {
+ this.it = it;
+ }
+
+ @Override
+ public boolean hasNext() {
+ if (nextValue != null) {
+ return true;
+ }
+ while (it.hasNext()) {
+ Map.Entry, V> entry = it.next();
+ K key = entry.getKey().get();
+ if (key != null) {
+ nextValue = new Entry(key, entry.getValue());
+ return true;
+ } else {
+ it.remove();
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public Map.Entry next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ Map.Entry entry = nextValue;
+ nextValue = null;
+ lastKey = entry.getKey();
+ return entry;
+ }
+
+ @Override
+ public void remove() {
+ if (lastKey == null) throw new IllegalStateException();
+ ConcurrentWeakIdentityHashMap.this.remove(lastKey);
+ lastKey = null;
+ }
+ }
+
+ private class EntrySet extends AbstractSet> {
+
+ @Override
+ public Iterator> iterator() {
+ return new Iter(map.entrySet().iterator());
+ }
+
+ @Override
+ public int size() {
+ return ConcurrentWeakIdentityHashMap.this.size();
+ }
+
+ @Override
+ public void clear() {
+ ConcurrentWeakIdentityHashMap.this.clear();
+ }
+
+ @Override
+ public boolean contains(Object o) {
+ if (!(o instanceof Map.Entry, ?> e)) {
+ return false;
+ }
+ return e.getValue() != null && ConcurrentWeakIdentityHashMap.this.get(e.getKey()) == e.getValue();
+ }
+
+ @Override
+ public boolean remove(Object o) {
+ if (!(o instanceof Map.Entry, ?> e)) {
+ return false;
+ }
+ return ConcurrentWeakIdentityHashMap.this.remove(e.getKey(), e.getValue());
+ }
+ }
+
+ private class Entry extends AbstractMap.SimpleEntry {
+
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ Entry(K key, V value) {
+ super(key, value);
+ }
+
+ @Override
+ public V setValue(V value) {
+ ConcurrentWeakIdentityHashMap.this.put(getKey(), value);
+ return super.setValue(value);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof Map.Entry, ?> e) {
+ return getKey() == e.getKey() && getValue() == e.getValue();
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return System.identityHashCode(getKey()) ^ System.identityHashCode(getValue());
+ }
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashCache.java
new file mode 100644
index 0000000..ace3028
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashCache.java
@@ -0,0 +1,218 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import it.unimi.dsi.fastutil.Hash;
+import it.unimi.dsi.fastutil.HashCommon;
+
+import java.util.function.Function;
+import java.util.function.UnaryOperator;
+
+/**
+ * 按指定的哈希与相等策略保存强引用值。计算在分段锁外执行。
+ *
+ * @param 缓存键类型
+ * @param 缓存值类型
+ */
+public final class CustomHashCache extends SegmentedCache> implements LoadingCache {
+
+ private final Hash.Strategy super K> strategy;
+ private final Function super K, ? extends V> createFunction;
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public CustomHashCache(Hash.Strategy super K> strategy) {
+ this(strategy, SegmentedCache.DEFAULT_CONCURRENCY, null);
+ }
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public CustomHashCache(Hash.Strategy super K> strategy, Function super K, ? extends V> createFunction) {
+ this(strategy, SegmentedCache.DEFAULT_CONCURRENCY, createFunction);
+ }
+
+ /** 使用二的幂次容量和位掩码定位。 */
+ public CustomHashCache(Hash.Strategy super K> strategy, int concurrencyLevel) {
+ this(strategy, concurrencyLevel, null);
+ }
+
+ /** 使用二的幂次容量和位掩码定位。 */
+ public CustomHashCache(Hash.Strategy super K> strategy, int concurrencyLevel, Function super K, ? extends V> createFunction) {
+ super(concurrencyLevel, i -> new Segment<>(strategy));
+ this.strategy = strategy;
+ this.createFunction = createFunction;
+ }
+
+ @Override
+ public Function super K, ? extends V> createFunction() {
+ return createFunction;
+ }
+
+ @Override
+ public V getCache(final K k, Function super K, ? extends V> createFunction) {
+ int hash = strategy.hashCode(k);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).getCache(k, hash, mix, createFunction, Interner.identityMappingFunction());
+ }
+
+ @Override
+ public V getCache(K k, Function super K, ? extends V> createFunction, UnaryOperator keyMappingFunction) {
+ int hash = strategy.hashCode(k);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).getCache(k, hash, mix, createFunction, keyMappingFunction);
+ }
+
+ @Override
+ public V getCacheRecursive(final K k, Function super K, ? extends V> createFunction) {
+ int hash = strategy.hashCode(k);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).getCache(k, hash, mix, createFunction, Interner.identityMappingFunction());
+ }
+
+ @Override
+ public V getCacheRecursive(final K k, Function super K, ? extends V> createFunction, UnaryOperator keyMappingFunction) {
+ int hash = strategy.hashCode(k);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).getCache(k, hash, mix, createFunction, keyMappingFunction);
+ }
+
+ @Override
+ public V getIfPresent(final K k) {
+ int hash = strategy.hashCode(k);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).getIfAbsent(k, hash, mix);
+ }
+
+ @Override
+ public V putIfAbsent(final K k, final V v) {
+ int hash = strategy.hashCode(k);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).put(k, v, hash, mix);
+ }
+
+ @Override
+ public void clear() {
+ clearSegments();
+ }
+
+ final static class Segment extends HashSegment> {
+
+ private final Hash.Strategy super K> strategy;
+
+ private Segment(Hash.Strategy super K> strategy) {
+ this.strategy = strategy;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected Node[] newArray(int capacity) {
+ return new Node[capacity];
+ }
+
+ @Override
+ protected int nodeHash(Node node) {
+ return node.hash;
+ }
+
+ /** 在写锁内合并并发变更。 */
+ private V getCache(final K k, final int hash, int mix,
+ Function super K, ? extends V> createFunction, UnaryOperator keyMappingFunction) {
+ long stamp = readLock();
+ try {
+ Node curr = table[mix & mask];
+ while (curr != null) {
+ if (curr.hash == hash && (k == curr.key || strategy.equals(k, curr.key))) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ } finally {
+ unlockRead(stamp);
+ }
+ // 在锁外执行计算,允许回调再次访问同一缓存。
+ final var mapped = keyMappingFunction.apply(k);
+ final var v = createFunction.apply(mapped);
+ stamp = writeLock();
+ try {
+ final int index = mix & mask;
+ final Node node = table[index];
+ Node curr = table[index];
+ while (curr != null) {
+ if (curr.hash == hash && (mapped == curr.key || strategy.equals(mapped, curr.key))) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ table[index] = new Node<>(mapped, v, hash, node);
+ if (++size > maxFill) {
+ resize();
+ }
+ return v;
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+
+ /** 只读取现有条目。 */
+ private V getIfAbsent(final K k, final int hash, int mix) {
+ long stamp = readLock();
+ try {
+ final int index = mix & mask;
+ Node curr = table[index];
+ while (curr != null) {
+ if (curr.hash == hash && (k == curr.key || strategy.equals(k, curr.key))) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ return null;
+ } finally {
+ unlockRead(stamp);
+ }
+ }
+
+ /** 只在缺少该键时写入。 */
+ private V put(final K k, final V v, final int hash, int mix) {
+ long stamp = writeLock();
+ try {
+ final int index = mix & mask;
+ final Node node = table[index];
+ Node curr = node;
+ while (curr != null) {
+ if (curr.hash == hash && (k == curr.key || strategy.equals(k, curr.key))) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ table[index] = new Node<>(k, v, hash, node);
+ if (++size > maxFill) {
+ resize();
+ }
+ return v;
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+ }
+
+ static final class Node implements ChainNode> {
+
+ private final K key;
+ private final V value;
+ private final int hash;
+ private volatile Node next;
+
+ private Node(K key, V value, int hash, Node next) {
+ this.key = key;
+ this.value = value;
+ this.hash = hash;
+ this.next = next;
+ }
+
+ @Override
+ public Node getNext() {
+ return next;
+ }
+
+ @Override
+ public void setNext(Node next) {
+ this.next = next;
+ }
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashInterner.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashInterner.java
new file mode 100644
index 0000000..8d5311e
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/CustomHashInterner.java
@@ -0,0 +1,181 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import it.unimi.dsi.fastutil.Hash;
+import it.unimi.dsi.fastutil.HashCommon;
+
+import java.util.function.UnaryOperator;
+
+/**
+ * 按调用方提供的哈希与相等策略驻留对象。驻留条目由该实例强引用。
+ *
+ * @param 驻留对象类型
+ */
+public final class CustomHashInterner extends SegmentedCache> implements Interner {
+
+ private final Hash.Strategy super T> strategy;
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public CustomHashInterner(Hash.Strategy super T> strategy) {
+ this(SegmentedCache.DEFAULT_CONCURRENCY, strategy);
+ }
+
+ /** 按给定的并发度初始化缓存。并发度必须大于零。 */
+ public CustomHashInterner(int concurrencyLevel, Hash.Strategy super T> strategy) {
+ super(concurrencyLevel, i -> new Segment<>(strategy));
+ this.strategy = strategy;
+ }
+
+ @Override
+ public T intern(final T sample) {
+ int hash = strategy.hashCode(sample);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).intern(sample, hash, mix, Interner.identityMappingFunction());
+ }
+
+ @Override
+ public T intern(T sample, UnaryOperator mappingFunction) {
+ int hash = strategy.hashCode(sample);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).intern(sample, hash, mix, mappingFunction);
+ }
+
+ @Override
+ public boolean isPresent(final T sample) {
+ int hash = strategy.hashCode(sample);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).contains(sample, hash, mix);
+ }
+
+ @Override
+ public boolean addIfAbsent(final T sample) {
+ int hash = strategy.hashCode(sample);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).add(sample, hash, mix);
+ }
+
+ @Override
+ public void clear() {
+ clearSegments();
+ }
+
+ final static class Segment extends HashSegment> {
+
+ private final Hash.Strategy super T> strategy;
+
+ private Segment(Hash.Strategy super T> strategy) {
+ this.strategy = strategy;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected Node[] newArray(int capacity) {
+ return new Node[capacity];
+ }
+
+ @Override
+ protected int nodeHash(Node node) {
+ return node.hash;
+ }
+
+ /** 在写锁内合并并发变更。 */
+ private T intern(final T k, final int hash, int mix, UnaryOperator mappingFunction) {
+ long stamp = readLock();
+ try {
+ Node curr = table[mix & mask];
+ while (curr != null) {
+ var key = curr.key;
+ if (curr.hash == hash && (key == k || strategy.equals(k, key))) {
+ return key;
+ }
+ curr = curr.next;
+ }
+ } finally {
+ unlockRead(stamp);
+ }
+ final T v = mappingFunction.apply(k);
+ stamp = writeLock();
+ try {
+ final int index = mix & mask;
+ final Node node = table[index];
+ Node curr = node;
+ while (curr != null) {
+ var key = curr.key;
+ if (curr.hash == hash && (key == v || strategy.equals(v, key))) {
+ return key;
+ }
+ curr = curr.next;
+ }
+ table[index] = new Node<>(v, hash, node);
+ if (++size > maxFill) {
+ resize();
+ }
+ return v;
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+
+ private boolean contains(final T k, final int hash, int mix) {
+ long stamp = readLock();
+ try {
+ final int index = mix & mask;
+ Node curr = table[index];
+ while (curr != null) {
+ if (curr.hash == hash && (curr.key == k || strategy.equals(k, curr.key))) {
+ return true;
+ }
+ curr = curr.next;
+ }
+ return false;
+ } finally {
+ unlockRead(stamp);
+ }
+ }
+
+ /** 只在缺少该键时写入。 */
+ private boolean add(final T k, final int hash, int mix) {
+ long stamp = writeLock();
+ try {
+ final int index = mix & mask;
+ final Node node = table[index];
+ Node curr = node;
+ while (curr != null) {
+ if (curr.hash == hash && (curr.key == k || strategy.equals(k, curr.key))) {
+ return false;
+ }
+ curr = curr.next;
+ }
+ table[index] = new Node<>(k, hash, node);
+ if (++size > maxFill) {
+ resize();
+ }
+ return true;
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+ }
+
+ static final class Node implements ChainNode> {
+
+ private final T key;
+ private final int hash;
+ private volatile Node next;
+
+ private Node(T key, int hash, Node next) {
+ this.key = key;
+ this.hash = hash;
+ this.next = next;
+ }
+
+ @Override
+ public Node getNext() {
+ return next;
+ }
+
+ @Override
+ public void setNext(Node next) {
+ this.next = next;
+ }
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/DoubleCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/DoubleCache.java
new file mode 100644
index 0000000..2d81d63
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/DoubleCache.java
@@ -0,0 +1,182 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import it.unimi.dsi.fastutil.HashCommon;
+
+import java.util.function.DoubleFunction;
+
+/**
+ * 使用原始类型 {@code double} 作为键,强引用缓存值,直到缓存条目被清除。
+ * 计算函数在分段锁外运行,并发写入在锁内合并。
+ * 浮点键区分正负零,同一类型的 NaN 使用相同的键。
+ *
+ * @param 缓存值类型
+ */
+public final class DoubleCache extends SegmentedCache> {
+
+ private final DoubleFunction extends V> createFunction;
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public DoubleCache() {
+ this(SegmentedCache.DEFAULT_CONCURRENCY, null);
+ }
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public DoubleCache(DoubleFunction extends V> createFunction) {
+ this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction);
+ }
+
+ /** 按给定的并发度初始化缓存。并发度必须大于零。 */
+ public DoubleCache(int concurrencyLevel) {
+ this(concurrencyLevel, null);
+ }
+
+ /** 按给定的并发度初始化缓存。并发度必须大于零。 */
+ public DoubleCache(int concurrencyLevel, DoubleFunction extends V> createFunction) {
+ super(concurrencyLevel, i -> new Segment<>());
+ this.createFunction = createFunction;
+ }
+
+ /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */
+ public V getCache(final double k) {
+ int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k)));
+ return segmentFor(mix).getCache(k, mix, createFunction);
+ }
+
+ /** 在锁外执行计算,允许回调再次访问同一缓存。 */
+ public V getCache(final double k, DoubleFunction extends V> createFunction) {
+ int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k)));
+ return segmentFor(mix).getCache(k, mix, createFunction);
+ }
+
+ /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */
+ public V getIfPresent(final double k) {
+ int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k)));
+ return segmentFor(mix).getIfAbsent(k, mix);
+ }
+
+ /** 只在没有有效值时写入,返回最终关联的值。 */
+ public V putIfAbsent(final double k, final V v) {
+ int mix = HashCommon.mix(Long.hashCode(Double.doubleToLongBits(k)));
+ return segmentFor(mix).put(k, v, mix);
+ }
+
+ /** 清除全部条目。 */
+ public void clear() {
+ clearSegments();
+ }
+
+ static final class Segment extends HashSegment> {
+
+ private Segment() {}
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected Node[] newArray(int capacity) {
+ return new Node[capacity];
+ }
+
+ @Override
+ protected int nodeHash(Node node) {
+ return Long.hashCode(Double.doubleToLongBits(node.key));
+ }
+
+ /** 在写锁内合并并发变更。 */
+ private V getCache(final double k, final int mix, DoubleFunction extends V> createFunction) {
+ long stamp = readLock();
+ try {
+ Node curr = table[mix & mask];
+ while (curr != null) {
+ if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ } finally {
+ unlockRead(stamp);
+ }
+ // 在锁外执行计算,允许回调再次访问同一缓存。
+ final var v = createFunction.apply(k);
+ stamp = writeLock();
+ try {
+ final int index = mix & mask;
+ Node curr = table[index];
+ while (curr != null) {
+ if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ table[index] = new Node<>(k, v, table[index]);
+ if (++size > maxFill) {
+ resize();
+ }
+ return v;
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+
+ /** 只读取现有条目。 */
+ private V getIfAbsent(final double k, final int mix) {
+ long stamp = readLock();
+ try {
+ Node curr = table[mix & mask];
+ while (curr != null) {
+ if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ return null;
+ } finally {
+ unlockRead(stamp);
+ }
+ }
+
+ /** 只在缺少该键时写入。 */
+ private V put(final double k, final V v, final int mix) {
+ long stamp = writeLock();
+ try {
+ final int index = mix & mask;
+ final Node node = table[index];
+ Node curr = node;
+ while (curr != null) {
+ if (Double.doubleToLongBits(curr.key) == Double.doubleToLongBits(k)) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ table[index] = new Node<>(k, v, node);
+ if (++size > maxFill) {
+ resize();
+ }
+ return v;
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+ }
+
+ static final class Node implements ChainNode> {
+
+ private final double key;
+ private final V value;
+ private volatile Node next;
+
+ private Node(double key, V value, Node next) {
+ this.key = key;
+ this.value = value;
+ this.next = next;
+ }
+
+ @Override
+ public Node getNext() {
+ return next;
+ }
+
+ @Override
+ public void setNext(Node next) {
+ this.next = next;
+ }
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/FloatCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/FloatCache.java
new file mode 100644
index 0000000..00ba8ff
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/FloatCache.java
@@ -0,0 +1,181 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import it.unimi.dsi.fastutil.HashCommon;
+import it.unimi.dsi.fastutil.floats.Float2ObjectFunction;
+
+/**
+ * 使用原始类型 {@code float} 作为键,强引用缓存值,直到缓存条目被清除。
+ * 计算函数在分段锁外运行,并发写入在锁内合并。
+ * 浮点键区分正负零,同一类型的 NaN 使用相同的键。
+ *
+ * @param 缓存值类型
+ */
+public final class FloatCache extends SegmentedCache> {
+
+ private final Float2ObjectFunction extends V> createFunction;
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public FloatCache() {
+ this(SegmentedCache.DEFAULT_CONCURRENCY, null);
+ }
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public FloatCache(Float2ObjectFunction extends V> createFunction) {
+ this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction);
+ }
+
+ /** 按给定的并发度初始化缓存。并发度必须大于零。 */
+ public FloatCache(int concurrencyLevel) {
+ this(concurrencyLevel, null);
+ }
+
+ /** 按给定的并发度初始化缓存。并发度必须大于零。 */
+ public FloatCache(int concurrencyLevel, Float2ObjectFunction extends V> createFunction) {
+ super(concurrencyLevel, i -> new Segment<>());
+ this.createFunction = createFunction;
+ }
+
+ /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */
+ public V getCache(final float k) {
+ int mix = HashCommon.mix(Float.floatToIntBits(k));
+ return segmentFor(mix).getCache(k, mix, createFunction);
+ }
+
+ /** 在锁外执行计算,允许回调再次访问同一缓存。 */
+ public V getCache(final float k, Float2ObjectFunction extends V> createFunction) {
+ int mix = HashCommon.mix(Float.floatToIntBits(k));
+ return segmentFor(mix).getCache(k, mix, createFunction);
+ }
+
+ /** 返回现有缓存值。缺失时按该方法提供的计算函数生成,查找方法直接返回空值。 */
+ public V getIfPresent(final float k) {
+ int mix = HashCommon.mix(Float.floatToIntBits(k));
+ return segmentFor(mix).getIfAbsent(k, mix);
+ }
+
+ /** 只在没有有效值时写入,返回最终关联的值。 */
+ public V putIfAbsent(final float k, final V v) {
+ int mix = HashCommon.mix(Float.floatToIntBits(k));
+ return segmentFor(mix).put(k, v, mix);
+ }
+
+ /** 清除全部条目。 */
+ public void clear() {
+ clearSegments();
+ }
+
+ static final class Segment extends HashSegment> {
+
+ private Segment() {}
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected Node[] newArray(int capacity) {
+ return new Node[capacity];
+ }
+
+ @Override
+ protected int nodeHash(Node node) {
+ return Float.floatToIntBits(node.key);
+ }
+
+ /** 在写锁内合并并发变更。 */
+ private V getCache(final float k, final int mix, Float2ObjectFunction extends V> createFunction) {
+ long stamp = readLock();
+ try {
+ Node curr = table[mix & mask];
+ while (curr != null) {
+ if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ } finally {
+ unlockRead(stamp);
+ }
+ // 在锁外执行计算,允许回调再次访问同一缓存。
+ final var v = createFunction.get(k);
+ stamp = writeLock();
+ try {
+ final int index = mix & mask;
+ Node curr = table[index];
+ while (curr != null) {
+ if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ table[index] = new Node<>(k, v, table[index]);
+ if (++size > maxFill) {
+ resize();
+ }
+ return v;
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+
+ /** 只读取现有条目。 */
+ private V getIfAbsent(final float k, final int mix) {
+ long stamp = readLock();
+ try {
+ Node curr = table[mix & mask];
+ while (curr != null) {
+ if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ return null;
+ } finally {
+ unlockRead(stamp);
+ }
+ }
+
+ /** 只在缺少该键时写入。 */
+ private V put(final float k, final V v, final int mix) {
+ long stamp = writeLock();
+ try {
+ final int index = mix & mask;
+ final Node node = table[index];
+ Node curr = node;
+ while (curr != null) {
+ if (Float.floatToIntBits(curr.key) == Float.floatToIntBits(k)) {
+ return curr.value;
+ }
+ curr = curr.next;
+ }
+ table[index] = new Node<>(k, v, node);
+ if (++size > maxFill) {
+ resize();
+ }
+ return v;
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+ }
+
+ static final class Node implements ChainNode> {
+
+ private final float key;
+ private final V value;
+ private volatile Node next;
+
+ private Node(float key, V value, Node next) {
+ this.key = key;
+ this.value = value;
+ this.next = next;
+ }
+
+ @Override
+ public Node getNext() {
+ return next;
+ }
+
+ @Override
+ public void setNext(Node next) {
+ this.next = next;
+ }
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashCache.java
new file mode 100644
index 0000000..499bf81
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashCache.java
@@ -0,0 +1,90 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+import java.util.function.UnaryOperator;
+
+/**
+ * 按键的值相等性保存强引用值。计算依赖同一缓存内的其他键时使用递归加载入口。
+ *
+ * @param 缓存键类型
+ * @param 缓存值类型
+ */
+public final class HashCache implements LoadingCache {
+
+ private final ConcurrentHashMap map;
+ private final Function super K, ? extends V> createFunction;
+
+ /** 使用键的相等性创建无默认加载器的缓存。缺失值可由调用处提供加载函数。 */
+ public HashCache() {
+ this(null);
+ }
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public HashCache(Function super K, ? extends V> createFunction) {
+ this.map = new ConcurrentHashMap<>();
+ this.createFunction = createFunction;
+ }
+
+ @Override
+ public Function super K, ? extends V> createFunction() {
+ return createFunction;
+ }
+
+ @Override
+ public V getCache(final K k, Function super K, ? extends V> createFunction) {
+ return map.computeIfAbsent(k, createFunction);
+ }
+
+ @Override
+ public V getCache(final K k, Function super K, ? extends V> createFunction, UnaryOperator keyMappingFunction) {
+ V v = map.get(k);
+ if (v != null) {
+ return v;
+ }
+ K mapped = keyMappingFunction.apply(k);
+ v = createFunction.apply(mapped);
+ V prev = map.putIfAbsent(mapped, v);
+ return prev == null ? v : prev;
+ }
+
+ @Override
+ public V getCacheRecursive(final K k, Function super K, ? extends V> createFunction) {
+ V v = map.get(k);
+ if (v != null) {
+ return v;
+ }
+
+ v = createFunction.apply(k);
+ V prev = map.putIfAbsent(k, v);
+ return prev == null ? v : prev;
+ }
+
+ @Override
+ public V getCacheRecursive(final K k, Function super K, ? extends V> createFunction, UnaryOperator keyMappingFunction) {
+ V v = map.get(k);
+ if (v != null) {
+ return v;
+ }
+ K mapped = keyMappingFunction.apply(k);
+ v = createFunction.apply(mapped);
+ V prev = map.putIfAbsent(mapped, v);
+ return prev == null ? v : prev;
+ }
+
+ @Override
+ public V getIfPresent(final K k) {
+ return map.get(k);
+ }
+
+ @Override
+ public V putIfAbsent(final K k, final V v) {
+ V prev = map.putIfAbsent(k, v);
+ return prev == null ? v : prev;
+ }
+
+ @Override
+ public void clear() {
+ map.clear();
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashInterner.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashInterner.java
new file mode 100644
index 0000000..20b99ec
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashInterner.java
@@ -0,0 +1,52 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+import java.util.function.UnaryOperator;
+
+/**
+ * 按值相等性驻留对象。驻留条目由该实例强引用。
+ *
+ * @param 驻留对象类型
+ */
+public final class HashInterner implements Interner {
+
+ private final ConcurrentHashMap map;
+ private final Function function = Function.identity();
+
+ /** 按值的相等性创建驻留表,已登记者保留强引用。 */
+ public HashInterner() {
+ this.map = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ public T intern(final T sample) {
+ return map.computeIfAbsent(sample, function);
+ }
+
+ @Override
+ public T intern(T sample, UnaryOperator mappingFunction) {
+ var v = map.get(sample);
+ if (v != null) {
+ return v;
+ }
+ v = mappingFunction.apply(sample);
+ var prev = map.putIfAbsent(v, v);
+ return prev == null ? v : prev;
+ }
+
+ @Override
+ public boolean isPresent(final T sample) {
+ return map.containsKey(sample);
+ }
+
+ @Override
+ public boolean addIfAbsent(final T sample) {
+ return map.putIfAbsent(sample, sample) == null;
+ }
+
+ @Override
+ public void clear() {
+ map.clear();
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashSegment.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashSegment.java
new file mode 100644
index 0000000..a7280bc
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/HashSegment.java
@@ -0,0 +1,91 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import it.unimi.dsi.fastutil.Hash;
+import it.unimi.dsi.fastutil.HashCommon;
+
+import java.util.Arrays;
+import java.util.concurrent.locks.StampedLock;
+
+import static it.unimi.dsi.fastutil.HashCommon.arraySize;
+
+/** 分段缓存中的拉链哈希表,读写由此分段自己的锁保护。 */
+abstract class HashSegment> extends StampedLock {
+
+ protected volatile N[] table;
+ protected volatile int mask;
+ protected volatile int size;
+ protected volatile int maxFill;
+
+ protected HashSegment() {
+ int n = arraySize(Hash.DEFAULT_INITIAL_SIZE, Hash.DEFAULT_LOAD_FACTOR);
+ this.table = newArray(n);
+ this.mask = n - 1;
+ this.maxFill = (int) (n * Hash.DEFAULT_LOAD_FACTOR);
+ }
+
+ protected abstract int nodeHash(N node);
+
+ protected abstract N[] newArray(int capacity);
+
+ /** 在写锁内合并并发变更。 */
+ protected final void resize() {
+ N[] oldTab = this.table;
+ int oldCap = oldTab.length;
+ int newCap = oldCap << 1;
+ N[] newTab = newArray(newCap);
+ int newMask = newCap - 1;
+ for (int i = 0; i < oldCap; ++i) {
+ N e;
+ if ((e = oldTab[i]) != null) {
+ oldTab[i] = null;
+ if (e.getNext() == null) {
+ newTab[HashCommon.mix(nodeHash(e)) & newMask] = e;
+ } else {
+ N loHead = null, loTail = null;
+ N hiHead = null, hiTail = null;
+ N next;
+ do {
+ next = e.getNext();
+ if ((HashCommon.mix(nodeHash(e)) & oldCap) == 0) {
+ if (loTail == null)
+ loHead = e;
+ else
+ loTail.setNext(e);
+ loTail = e;
+ } else {
+ if (hiTail == null)
+ hiHead = e;
+ else
+ hiTail.setNext(e);
+ hiTail = e;
+ }
+ } while ((e = next) != null);
+ if (loTail != null) {
+ loTail.setNext(null);
+ newTab[HashCommon.mix(nodeHash(loHead)) & newMask] = loHead;
+ }
+ if (hiTail != null) {
+ hiTail.setNext(null);
+ newTab[HashCommon.mix(nodeHash(hiHead)) & newMask] = hiHead;
+ }
+ }
+ }
+ }
+ this.table = newTab;
+ this.mask = newMask;
+ this.maxFill = (int) (newCap * Hash.DEFAULT_LOAD_FACTOR);
+ }
+
+ /** 在写锁内合并并发变更。 */
+ protected void clear() {
+ long stamp = writeLock();
+ try {
+ if (size != 0) {
+ size = 0;
+ Arrays.fill(table, null);
+ }
+ } finally {
+ unlockWrite(stamp);
+ }
+ }
+}
diff --git a/src/main/java/com/modularmc/mmclutils/api/collection/cache/IdentityHashCache.java b/src/main/java/com/modularmc/mmclutils/api/collection/cache/IdentityHashCache.java
new file mode 100644
index 0000000..56fcbed
--- /dev/null
+++ b/src/main/java/com/modularmc/mmclutils/api/collection/cache/IdentityHashCache.java
@@ -0,0 +1,207 @@
+package com.modularmc.mmclutils.api.collection.cache;
+
+import it.unimi.dsi.fastutil.HashCommon;
+
+import java.util.function.Function;
+import java.util.function.UnaryOperator;
+
+/**
+ * 按键的引用身份保存强引用值。计算在分段锁外执行。
+ *
+ * @param 缓存键类型
+ * @param 缓存值类型
+ */
+public final class IdentityHashCache extends SegmentedCache> implements LoadingCache {
+
+ private final Function super K, ? extends V> createFunction;
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public IdentityHashCache() {
+ this(SegmentedCache.DEFAULT_CONCURRENCY, null);
+ }
+
+ /** 使用默认并发度。创建函数由参数决定,可省略。 */
+ public IdentityHashCache(Function super K, ? extends V> createFunction) {
+ this(SegmentedCache.DEFAULT_CONCURRENCY, createFunction);
+ }
+
+ /** 按给定的并发度初始化缓存。并发度必须大于零。 */
+ public IdentityHashCache(int concurrencyLevel) {
+ this(concurrencyLevel, null);
+ }
+
+ /** 按给定的并发度初始化缓存。并发度必须大于零。 */
+ public IdentityHashCache(int concurrencyLevel, Function super K, ? extends V> createFunction) {
+ super(concurrencyLevel, i -> new Segment<>());
+ this.createFunction = createFunction;
+ }
+
+ @Override
+ public Function super K, ? extends V> createFunction() {
+ return createFunction;
+ }
+
+ @Override
+ public V getCache(final K k, Function super K, ? extends V> createFunction) {
+ int hash = System.identityHashCode(k);
+ int mix = HashCommon.mix(hash);
+ return segmentFor(mix).getCache(k, mix, createFunction, Interner.identityMappingFunction());
+ }
+
+ @Override
+ public V getCache(K k, Function super K, ? extends V> createFunction, UnaryOperator