diff --git a/.gitignore b/.gitignore index ab1c4d8..af53e1b 100644 --- a/.gitignore +++ b/.gitignore @@ -21,7 +21,9 @@ classes/ .settings *.launch .architectury-transformer/debug.log -**/resources/ +**/src/generated/ +!test/src/main/resources/ +!test/src/main/resources/** *.patch *.DS_Store diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ba9f119..53db024 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,7 @@ - `RegistrateLib` 是本分支的库模组入口点,同时持有共享元数据/常量 `RegistrateLib` is the library mod entrypoint for the fork and also holds shared metadata/constants -- `src/test/java/com/modularmc/registrate/test/meta` 包含用于生成的桥接方法的维护辅助工具 - `src/test/java/com/modularmc/registrate/test/meta` contains maintenance helpers for generated bridge methods +- `test/src/main/java/com/modularmc/registratetest` 包含用于生成的桥接方法的维护辅助工具 + `test/src/main/java/com/modularmc/registratetest` contains maintenance helpers for generated bridge methods - 当上游 Registrate 变更时,先更新实现类,然后对照 `docs/architecture.md` 重新验证包所有权 When upstream Registrate changes, update implementation classes first and then re-verify package ownership against `docs/architecture.md` diff --git a/README.md b/README.md index 0ac669f..f4532cb 100644 --- a/README.md +++ b/README.md @@ -55,9 +55,9 @@ This repository is the `com.modularmc.registrate` fork maintained for the Modula - `com.modularmc.registrate.internal.event` — 用于构建器和注册生命周期钩子的一次性事件连接 / one-shot event wiring used by builders and registration lifecycle hooks - `com.modularmc.registrate.internal.lifecycle` — 实例级生命周期桥接 / per-instance lifecycle bridges - `com.modularmc.registrate.internal.util` — 分发限制执行与内部日志辅助 / dist-gated execution and internal logging helpers -- `com.modularmc.registrate.test.mod` — 集成测试示例模组 / the integration-style sample mod -- `com.modularmc.registrate.test.gametests` — 可执行的运行时验证场景 / executable validation scenarios for runtime behavior -- `com.modularmc.registrate.test.meta` — 维护工具,使生成的桥接方法与上游 API 保持一致 / maintenance utilities that keep generated bridge methods aligned with upstream APIs +- `com.modularmc.registratetest.mod` — 集成测试示例模组 / the integration-style sample mod +- `com.modularmc.registratetest.gametests` — 可执行的运行时验证场景 / executable validation scenarios for runtime behavior +- `com.modularmc.registratetest.meta` — 维护工具,使生成的桥接方法与上游 API 保持一致 / maintenance utilities that keep generated bridge methods aligned with upstream APIs --- diff --git a/build.gradle b/build.gradle index 6fd234e..fc9ea0d 100644 --- a/build.gradle +++ b/build.gradle @@ -9,7 +9,6 @@ plugins { //alias libs.plugins.shadow alias libs.plugins.spotless alias libs.plugins.kotlin.jvm - alias libs.plugins.ksp } group = maven_group @@ -40,14 +39,6 @@ sourceSets { runtimeClasspath += main.output + main.runtimeClasspath } - test { - compileClasspath += main.output + main.compileClasspath - runtimeClasspath += main.output + main.runtimeClasspath - resources { - srcDir 'src/test/generated/resources' - } - } - extra { compileClasspath += main.output runtimeClasspath += main.output + main.runtimeClasspath @@ -55,9 +46,7 @@ sourceSets { clientExtra { compileClasspath += client.output + extra.compileClasspath - // The normal client run also mounts the test mod, so include the test source set - // here to keep generated test resources synchronized into build/resources/test. - runtimeClasspath += client.output + client.runtimeClasspath + extra.runtimeClasspath + test.output + test.runtimeClasspath + runtimeClasspath += client.output + client.runtimeClasspath + extra.runtimeClasspath } } @@ -66,8 +55,6 @@ configurations { clientRuntimeOnly.canBeResolved = false extraRuntimeOnly.canBeResolved = false clientExtraRuntimeOnly.canBeResolved = false - testImplementation.canBeResolved = false - testRuntimeOnly.canBeResolved = false runtimeClasspath.extendsFrom localRuntime extraRuntimeClasspath.extendsFrom extraLocalRuntime @@ -92,8 +79,3 @@ tasks.withType(JavaCompile).configureEach { options.compilerArgs << '-Xmaxerrs' << '2000' options.compilerArgs << "-Xlint:-removal" } - -tasks.named('test') { - // The test source set is exercised by NeoForge's GameTest server. - failOnNoDiscoveredTests = false -} diff --git a/dependencies.gradle b/dependencies.gradle index 70a5865..18b211b 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -8,13 +8,7 @@ dependencies { additionalRuntimeClasspath(libs.kotlin.stdlib.get()) { exclude group: 'org.jetbrains', module: 'annotations' } - - testImplementation(libs.testframework.get()) - testAnnotationProcessor(project(':localization-processor')) - kspTest(project(':localization-processor')) - - // Standard runtime mods // - localRuntime(libs.testframework) + jarJar(implementation(forge.mmclutils.get())) renderNurseCfg(libs.renderNurse) diff --git a/docs/architecture.md b/docs/architecture.md index 1050ab7..0f7af06 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -47,14 +47,14 @@ RegistrateLib is a maintained fork of Registrate for the `com.modularmc.registra - `com.modularmc.registrate.internal.util` - 分发限制执行与内部调试日志辅助 / Dist-gated execution and internal debug logging helpers -- `com.modularmc.registrate.test.mod` +- `com.modularmc.registratetest.mod` - 用作集成测试的示例模组 / Sample mod used as an integration harness -- `com.modularmc.registrate.test.gametests` +- `com.modularmc.registratetest.gametests` - 可执行的运行时检查 / Executable runtime checks -- `com.modularmc.registrate.test.meta` - - 用于生成的桥接方法和受保护 API 快照的维护工具 / Maintenance tooling for generated bridge methods and protected API snapshots +- `com.modularmc.registratetest.meta` + - 维护生成的桥接方法和受保护的 API 清单 / Maintains generated bridge methods and protected API listings ## 公开 API 边界 / Public API Boundary @@ -75,8 +75,8 @@ Treat the root package plus `builders` and `util.entry` as the main downstream-f Event-bus plumbing and other implementation-only helpers belong under `internal` - 实例级 NeoForge 生命周期编排放在 `internal.lifecycle` Instance-scoped NeoForge lifecycle orchestration belongs in `internal.lifecycle` -- 仅测试用的框架放在 `src/test/java` - Test-only scaffolding belongs under `src/test/java` +- 仅测试用的框架放在 `test/src/main/java` + Test-only scaffolding belongs under `test/src/main/java` ## 现代化原则 / Modernization Principles diff --git a/docs/localization-exchange.schema.json b/docs/localization-exchange.schema.json new file mode 100644 index 0000000..a0487b9 --- /dev/null +++ b/docs/localization-exchange.schema.json @@ -0,0 +1,94 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Registrate Localization Exchange", + "type": "object", + "required": ["formatVersion", "modId", "sourceLocale", "entries"], + "properties": { + "formatVersion": { "const": 1 }, + "modId": { "type": "string" }, + "sourceLocale": { "$ref": "#/$defs/locale" }, + "entries": { + "type": "array", + "items": { "$ref": "#/$defs/entry" } + } + }, + "additionalProperties": false, + "$defs": { + "locale": { + "type": "string", + "pattern": "^[a-z]{2}_[a-z]{2}$" + }, + "revision": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "entry": { + "type": "object", + "required": ["namespace", "key", "source", "context", "translations"], + "properties": { + "namespace": { "type": "string" }, + "key": { "type": "string" }, + "source": { "$ref": "#/$defs/sourceText" }, + "context": { "$ref": "#/$defs/context" }, + "translations": { + "type": "array", + "items": { "$ref": "#/$defs/translation" } + } + }, + "additionalProperties": false + }, + "sourceText": { + "type": "object", + "required": ["locale", "text", "revision"], + "properties": { + "locale": { "$ref": "#/$defs/locale" }, + "text": { "type": "string" }, + "revision": { "$ref": "#/$defs/revision" } + }, + "additionalProperties": false + }, + "context": { + "type": "object", + "required": ["domains", "type", "glossaryIds", "unitIds", "placeholderSignature"], + "properties": { + "domains": { "type": "array", "items": { "type": "string" } }, + "type": { "type": ["string", "null"] }, + "glossaryIds": { "type": "array", "items": { "type": "string" } }, + "unitIds": { "type": "array", "items": { "type": "string" } }, + "placeholderSignature": { + "type": "object", + "propertyNames": { "pattern": "^(0|[1-9][0-9]*)$" }, + "additionalProperties": { "type": "integer", "minimum": 1 } + } + }, + "additionalProperties": false + }, + "translation": { + "type": "object", + "required": ["locale", "text", "source", "sourceRevision", "status", "locked"], + "properties": { + "locale": { "$ref": "#/$defs/locale" }, + "text": { "type": "string" }, + "source": { "$ref": "#/$defs/translationSource" }, + "sourceRevision": { "$ref": "#/$defs/revision" }, + "status": { + "type": ["string", "null"], + "enum": ["stale", "draft", "in_review", "approved", null] + }, + "locked": { "type": "boolean" } + }, + "additionalProperties": false + }, + "translationSource": { + "type": "object", + "required": ["kind", "location"], + "properties": { + "kind": { + "enum": ["fallback", "variant", "automatic", "glossary", "imported", "declared"] + }, + "location": { "type": "string" } + }, + "additionalProperties": false + } + } +} diff --git a/docs/localization.md b/docs/localization.md index 311353b..8f6490b 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -7,10 +7,16 @@ ```java import com.modularmc.registrate.Registrate; import com.modularmc.registrate.localization.MinecraftLocale; +import java.nio.file.Path; Registrate registrate = Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US); +registrate.export().localization() + .path(Path.of("build", "localization", "mymod.json")) + .build(); ``` +`path` is the destination JSON file. Relative paths resolve against the DataGen process working directory. The export request is fulfilled after language callbacks have run once; the same declarations produce both Minecraft language files and the exchange document. + ## 声明文本 物品、方块、实体和流体的 Builder 从注册对象取 Minecraft 原生翻译 Key。通用 Builder 可用 `.localization(keyFunction, text -> ...)` 指定取 Key 的方式。 @@ -30,35 +36,72 @@ var title = registrate.addLocalization(new TranslationKey(MOD_ID, "gui.mymod.vol `addLocalization` 返回可用于 GUI 的翻译组件。进度标题等跨侧文本可在模组构造期间声明,在服务端 DataGen 的进度回调中引用组件。`addLang`、`addRawLang` 和 `ProviderType.LANG` 回调都使用同一个源 Locale。 -在 `registrate.localizationCatalog()` 中登记 `Domain`、`GlossaryTerm` 和 `Unit`。Builder 的 `.profile(profile)` 可复用领域、文本类型和术语。条目的显式参数覆盖 Profile 的相应字段。 +在 `registrate.terminology()` 中登记 `Domain`、`GlossaryTerm` 和 `MeasurementUnit`。用 `.localizationDefaults(defaults)` 设置模组级默认值,Builder 的 `.defaults(defaults)` 可设置条目级默认值。条目的显式参数覆盖对应默认值。 -## 接入注解处理器 +### 按语境选取术语 -用 `./gradlew :localization-processor:jar` 构建与库版本对应的处理器。Java 源码使用 `annotationProcessor`,Kotlin 源码使用 KSP 插件和 `ksp`。混合项目可同时使用两项配置,主库作为模组依赖。 +词表按声明所属的模组查询。完整源文本与词条匹配时,优先使用 `.glossaryIds("electric_potential")` 或 `.glossary(term)` 指定的术语。其余候选按 `Domain` 和 `TextType` 筛选,匹配程度相同的词条会报告声明位置与术语 ID。词表的首选译名可以补充缺少的译文。条目已有译文时,解析保留显式值,并提示禁用译名或词表未收录的写法。 -```groovy -dependencies { - def processor = files("libs/registratelib-1.21.1-${registratelib_version}-localization-processor.jar") - annotationProcessor(processor) - ksp(processor) -} +通过 `registrate.terminology().register(glossary)` 接入项目自己的 `Glossary` 实现。接口通过 `find(id)` 查单条定义,通过 `findBySource(normalizedSource)` 返回完整标签的所有词义。源文本查询使用与 Locale 无关的小写形式。同一模组内的词条 ID 对应唯一的定义。 + +词条可登记缩写和别名、用 `TermRelation` 指定与其他词条的关系,以及关联已登记的单位 ID。单位通过 `MeasurementUnit.format(value, locale)` 格式化数值和符号。`UnitFormat` 配置 `DecimalFormat` 模式、小数分隔符和数值与符号之间的间距。 + +`DeclarationDefaults.Builder` 依次应用基础默认值、继承值和组合值,对应 `defaults`、`inherits` 和 `include`。同层的集合值可合并,冲突的文本类型或同 ID 词条会报错。声明可用 `.units("ohm")`、`.glossaryIds(...)` 等显式字段覆盖对应的默认值。 + +### 语言转换与回退 + +`registrate.deriveLocale(new LocaleDerivation(EN_US, EN_GB, converter))` 为模组注册转换规则。转换器处理未受保护的文本片段,可读取语言、Key 和声明。`LocaleDerivation.fallback(EN_GB, EN_AU)` 在缺少目标译文时使用已解析的输入语言。规则允许组成多步路径,循环会在 DataGen 收集时报告。已有译文优先于转换和回退。 + +转换会保留 Minecraft 参数、样式标记、URL、换行和已声明的单位符号。默认的 `en_us → en_ud` 同样遵循这些规则,并用显式索引保持倒置后的参数含义。 + +### 导出交换数据 + +导出文档的 `formatVersion` 当前为 `1`。每个条目保留输出命名空间、原始 Key、源文本、SHA-256 源修订、领域、TextType、词条与单位引用、占位符签名和译文候选。译文记录包含 Locale、文本、来源类型与位置、源修订、审核状态和锁定标记。自动 Locale 变体也会进入记录,`source.location` 标明原始声明与转换路径。 + +JSON Schema 位于 [`localization-exchange.schema.json`](localization-exchange.schema.json)。条目按命名空间和 Key 排序,译文按 Locale、来源类型和来源位置排序。显式译文的 `status` 为 `null`;导入译文保留当前审核状态和其审核时使用的源修订。 + +### 导入人工译文 + +在模组初始化时用 `importTranslation` 登记已读入的译文。提供译者审核时对应的源文本修订,以及可以定位到文件或平台条目的来源。 + +```java +import com.modularmc.registrate.localization.ImportedTranslation; +import com.modularmc.registrate.localization.MinecraftLocale; +import com.modularmc.registrate.localization.SourceRevision; +import com.modularmc.registrate.localization.TranslationKey; +import com.modularmc.registrate.localization.TranslationStatus; + +registrate.importTranslation(new ImportedTranslation( + new TranslationKey(MOD_ID, "item.mymod.copper_ingot"), + MinecraftLocale.ZH_CN, + "铜锭", + SourceRevision.of("Copper Ingot"), + TranslationStatus.APPROVED, + false, + "translations/zh_cn.json")); ``` -`@Trans` 和 `@TransVariants` 可以声明在类型或字段上。`modId` 选择声明归属的模组和源 Locale。省略 `namespace` 时,资源命名空间取 `modId`。 +DataGen 用模组当前选中的源文本核对修订。源文本变化会将译文标为 `STALE`。锁定译文仍可参与选择,未锁定的过期译文仅用于诊断,此时配置的术语、转换和回退规则可以继续解析目标 Locale。开发者显式声明优先,其次是锁定的导入译文和当前修订的普通导入译文。同一层级中,已批准、审核中和草稿依次参与选择。 + +## 注解声明 + +添加 RegistrateLib 模组依赖即可在 Java 和 Kotlin 源码中使用本地化注解。DataGen 从 NeoForge 的扫描结果读取所属模组文件中的声明。升级时移除 RegistrateLib 的 `annotationProcessor` 和 `ksp` 依赖。旧构建目录里有索引文件时,清理一次再构建。 + +`@Trans` 和 `@TransVariants` 可以声明在类型或字段上。文件只包含一个 Mod 时可以省略 `modId`,DataGen 使用该 Mod 的源 Locale。文件包含多个 Mod 时,每条声明都必须填写 `modId`。省略 `namespace` 时,资源命名空间取所属 Mod 的 ID。 ```java -@TransVariants(modId = "mymod", keyPrefix = "gui.mymod.power", value = { +@TransVariants(keyPrefix = "gui.mymod.power", value = { @Variant(id = "low", source = "Low power"), @Variant(id = "high", source = "High power") }) final class Labels { - @Trans(modId = "mymod", key = "gui.mymod.container", source = "Test Container", + @Trans(key = "gui.mymod.container", source = "Test Container", translations = @Translation(locale = MinecraftLocale.ZH_CN, text = "测试容器")) static final String CONTAINER = "gui.mymod.container"; } ``` -Kotlin 中在带有后备字段的属性上使用 `@field:Trans` 或 `@field:TransVariants`。两个处理器按 Mod ID 写入各自的版本化声明索引,DataGen 从所属模组读取并合并。变体的 Key 由前缀和 ID 拼接,例如 `gui.mymod.power.low`。同一命名空间、Key 和 Locale 下,同级异值声明会报告双方来源。`%s` 的隐式索引按出现顺序分配,译文可用 `%1$s` 等显式索引重排。 +Kotlin 中在带有后备字段的属性上使用 `@field:Trans` 或 `@field:TransVariants`。变体的 Key 由前缀和 ID 拼接,例如 `gui.mymod.power.low`。同一命名空间、Key 和 Locale 下,同级异值声明会报告双方来源,并用类名、字段名和变体 ID 定位注解。`%s` 的隐式索引按出现顺序分配,译文可用 `%1$s` 等显式索引重排。 ## 注册兼容性 diff --git a/gradle/forge.versions.toml b/gradle/forge.versions.toml index eb179be..db490af 100644 --- a/gradle/forge.versions.toml +++ b/gradle/forge.versions.toml @@ -1,4 +1,5 @@ [versions] +mmclutils = "0.1.0-SNAPSHOT" ## modrinth maven ## @@ -9,5 +10,6 @@ [libraries] +mmclutils = { module = "com.modularmc.mmclutils:mmclutils-1.21.1", version.ref = "mmclutils" } [bundles] \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 468b355..ca20da7 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -7,7 +7,6 @@ shadow = "9.6.1" spotless = "8.11.0" modDevGradle = "2.0.148" kotlin = "2.4.21" -ksp = "2.3.14" jetbrains-annotations = "26.1.0" jspecify = "1.0.1" renderNurse = "0.0.26" @@ -18,7 +17,6 @@ minecraft = { module = "com.mojang:minecraft", version.ref = "mine neoForge = { module = "net.neoforged:neoforge", version.ref = "neoForge" } testframework = { module = "net.neoforged:testframework", version.ref = "neoForge" } kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } -ksp-api = { module = "com.google.devtools.ksp:symbol-processing-api", version.ref = "ksp" } 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" } @@ -29,4 +27,3 @@ modDevGradle = { id = "net.neoforged.moddev", version.ref = "modDevGr shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } -ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index e60d0db..b1a28bc 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -3,10 +3,6 @@ jar { exclude "**/SimplifiedToTraditional.properties" } -tasks.named('assemble') { - dependsOn(':localization-processor:jar') -} - tasks.register('slimJar', Jar) { dependsOn("classes") archiveClassifier = "slim" diff --git a/gradle/scripts/moddevgradle.gradle b/gradle/scripts/moddevgradle.gradle index c82b568..243e14b 100644 --- a/gradle/scripts/moddevgradle.gradle +++ b/gradle/scripts/moddevgradle.gradle @@ -1,7 +1,5 @@ import org.slf4j.event.Level -def devTestModId = 'testmod' - neoForge { version = libs.versions.neoForge.get() @@ -25,7 +23,6 @@ neoForge { // // interfaceInjectionData = project.files('injected_interfaces/interfaces.json') - addModdingDependenciesTo(sourceSets.test) addModdingDependenciesTo(sourceSets.extra) mods { @@ -36,9 +33,6 @@ neoForge { sourceSet(sourceSets.extra) sourceSet(sourceSets.clientExtra) } - "${devTestModId}" { - sourceSet(sourceSets.test) - } } runs { @@ -60,58 +54,10 @@ neoForge { programArguments.addAll('--nogui', '--world', 'world-extra') } - // 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. - gameTestServer { - type = "gameTestServer" - sourceSet = sourceSets.test - ideName = "Game Tests" - - gameDirectory.set(file('run/gametest/server')) - systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) - environment('TEST', 'true') - } - - gameTestClient { - client() - sourceSet = sourceSets.test - ideName = "Game Tests (Client)" - - gameDirectory.set(file('run/gametest/client')) - systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) - environment('TEST', 'true') - } - - Testdata { - data() - sourceSet = sourceSets.test - ideName = "Test 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', "${devTestModId},localetest", '--flat') - programArguments.add(providers.gradleProperty('testDataSide').orElse('all').map { "--${it}".toString() }) - programArguments.add('--output') - programArguments.add(providers.gradleProperty('testDataOutput').orElse('src/test/generated/resources').map { file(it).absolutePath }) - programArguments.addAll('--existing', file('src/test/resources/').getAbsolutePath()) - } - // 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.registrate...') - - // 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 = Level.INFO } } diff --git a/gradle/scripts/publishing.gradle b/gradle/scripts/publishing.gradle index 149eb38..c00da5b 100644 --- a/gradle/scripts/publishing.gradle +++ b/gradle/scripts/publishing.gradle @@ -1,21 +1,22 @@ publishing { -// publications { -// mavenJava(MavenPublication) { -// artifactId = base.archivesName.get() -// artifact(reobfSlimJar) -// from components.java -// } -// } + publications { + mavenJava(MavenPublication) { + artifactId = base.archivesName.get() + from components.java + } + } - // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. repositories { -// Add repositories to publish to here. -// maven { -// url = "https://maven.gtceu.com" -// credentials { -// username = System.getenv("MAVEN_USER") -// password = System.getenv("MAVEN_PASSWORD") -// } -// } + maven { + name = "furyMaven" + url = uri("https://maven.fury.io/modularmclib/") + authentication { + basic(BasicAuthentication) + } + credentials { + username = System.getenv("MAVEN_USER") + password = System.getenv("MAVEN_PASSWORD") + } + } } } \ No newline at end of file diff --git a/gradle/scripts/repositories.gradle b/gradle/scripts/repositories.gradle index ed998d0..48fd867 100644 --- a/gradle/scripts/repositories.gradle +++ b/gradle/scripts/repositories.gradle @@ -1,5 +1,10 @@ repositories { mavenLocal() + maven { + name = "fury" + url = uri("https://maven.fury.io/modularmclib/") + content { includeGroup("com.modularmc.mmclutils") } + } mavenCentral() // Resolve libraries hosted on Maven Central without querying mod repositories. exclusiveContent { // Force @@ -8,7 +13,6 @@ repositories { includeGroup("it.unimi.dsi") includeGroup("org.lwjgl") includeGroup("com.google.guava") - includeGroup("com.google.devtools.ksp") includeGroupAndSubgroups("io.netty") includeGroupAndSubgroups("org.jetbrains") } diff --git a/gradle/scripts/spotless.gradle b/gradle/scripts/spotless.gradle index 7f8f125..6a5dbbb 100644 --- a/gradle/scripts/spotless.gradle +++ b/gradle/scripts/spotless.gradle @@ -9,7 +9,7 @@ spotless { endWithNewline() } java { - target 'src/*/java/**/*.java', 'localization-processor/src/main/java/**/*.java' + target 'src/*/java/**/*.java' def orderFile = file("$rootDir/gradle/spotless/spotless.importorder") def formatFile = file("$rootDir/gradle/spotless/spotless.eclipseformat.xml") @@ -23,7 +23,7 @@ spotless { eclipse('4.31').configFile(formatFile) } kotlin { - target 'src/*/java/**/*.kt', 'localization-processor/src/*/java/**/*.kt' + target 'src/*/java/**/*.kt' def orderFile = file("$rootDir/gradle/spotless/spotless.ktlint") ktlint().setEditorConfigPath(orderFile) diff --git a/localization-processor/build.gradle b/localization-processor/build.gradle deleted file mode 100644 index 26605dd..0000000 --- a/localization-processor/build.gradle +++ /dev/null @@ -1,48 +0,0 @@ -plugins { - alias libs.plugins.kotlin.jvm -} - -group = rootProject.group -version = rootProject.version - -java { - toolchain.languageVersion.set(rootProject.java.toolchain.languageVersion) -} - -kotlin { - jvmToolchain(rootProject.java.toolchain.languageVersion.get().asInt()) -} - -configurations { - processorKotlinRuntime { - canBeConsumed = false - } -} - -dependencies { - compileOnly(libs.ksp.api) - compileOnly(project(':')) { - transitive = false - } - processorKotlinRuntime(libs.kotlin.stdlib) { - transitive = false - } -} - -tasks.named('jar', Jar) { - archiveBaseName.set(rootProject.base.archivesName) - archiveClassifier = 'localization-processor' - destinationDirectory.set(rootProject.layout.buildDirectory.dir('libs')) - - // The processor needs these types on javac's isolated processor path. - from(rootProject.sourceSets.main.output.classesDirs) { - include 'com/modularmc/registrate/localization/annotation/**' - include 'com/modularmc/registrate/localization/MinecraftLocale.class' - include 'com/modularmc/registrate/localization/index/LocalizationIndex*.class' - } - - // Keep the standalone compiler path working for Java consumers. - from({ zipTree(configurations.processorKotlinRuntime.singleFile) }) { - include 'kotlin/**', 'META-INF/*.kotlin_module', 'META-INF/LICENSE*', 'META-INF/NOTICE*' - } -} diff --git a/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/TranslationProcessor.kt b/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/TranslationProcessor.kt deleted file mode 100644 index cce465d..0000000 --- a/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/TranslationProcessor.kt +++ /dev/null @@ -1,78 +0,0 @@ -package com.modularmc.registrate.localization.processor - -import com.modularmc.registrate.localization.MinecraftLocale -import com.modularmc.registrate.localization.annotation.Trans -import com.modularmc.registrate.localization.annotation.TransVariants -import com.modularmc.registrate.localization.annotation.Translation -import com.modularmc.registrate.localization.index.LocalizationIndex -import com.modularmc.registrate.localization.index.LocalizationIndex.Entry - -import java.io.DataOutputStream -import java.io.IOException -import java.util.EnumMap -import javax.annotation.processing.AbstractProcessor -import javax.annotation.processing.RoundEnvironment -import javax.annotation.processing.SupportedSourceVersion -import javax.lang.model.SourceVersion -import javax.lang.model.element.Element -import javax.lang.model.element.TypeElement -import javax.tools.StandardLocation - -/** Collects the annotated declarations from all rounds of a downstream Java compilation. */ -@SupportedSourceVersion(SourceVersion.RELEASE_21) -class TranslationProcessor : AbstractProcessor() { - private val declarations = LinkedHashMap>() - - private data class Declaration(val element: Element, val entry: Entry) - - override fun getSupportedAnnotationTypes(): Set = setOf(Trans::class.java.name, TransVariants::class.java.name) - - override fun process(annotations: Set, round: RoundEnvironment): Boolean { - for (element in round.getElementsAnnotatedWith(Trans::class.java)) { - val trans = element.getAnnotation(Trans::class.java) - add(trans.modId, trans.namespace, trans.key, trans.source, trans.translations, element, "@Trans ${location(element)}") - } - for (element in round.getElementsAnnotatedWith(TransVariants::class.java)) { - val group = element.getAnnotation(TransVariants::class.java) - for (variant in group.value) { - val key = LocalizationIndex.variantKey(group.keyPrefix, variant.id) - add(group.modId, group.namespace, key, variant.source, variant.translations, element, "@TransVariants ${location(element)} [${variant.id}]") - } - } - if (round.processingOver() && !round.errorRaised()) { - declarations.forEach(::write) - } - return true - } - - private fun add(modId: String, namespace: String, key: String, source: String, translations: Array, element: Element, location: String) { - val texts = if (translations.isEmpty()) { - emptyMap() - } else { - EnumMap(MinecraftLocale::class.java).apply { - for (translation in translations) put(translation.locale, translation.text) - } - } - val entry = Entry(namespace.ifEmpty { modId }, key, source, location, texts) - declarations.getOrPut(modId, ::ArrayList).add(Declaration(element, entry)) - } - - private fun write(modId: String, declarations: List) { - val path = LocalizationIndex.path(modId) - val origins = declarations.mapTo(LinkedHashSet(), Declaration::element).toTypedArray() - try { - val resource = processingEnv.filer.createResource(StandardLocation.CLASS_OUTPUT, "", path, *origins) - DataOutputStream(resource.openOutputStream().buffered()).use { output -> - LocalizationIndex.write(output, declarations.map(Declaration::entry)) - } - } catch (error: IOException) { - processingEnv.messager.printError("Cannot write localization index $path: ${error.message}") - } - } - - private fun location(element: Element): String { - if (element is TypeElement) return element.qualifiedName.toString() - val owner = element.enclosingElement as TypeElement - return "${owner.qualifiedName}#${element.simpleName}" - } -} diff --git a/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/ksp/LocalizationSymbolProcessorProvider.kt b/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/ksp/LocalizationSymbolProcessorProvider.kt deleted file mode 100644 index 65b3194..0000000 --- a/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/ksp/LocalizationSymbolProcessorProvider.kt +++ /dev/null @@ -1,107 +0,0 @@ -package com.modularmc.registrate.localization.processor.ksp - -import com.modularmc.registrate.localization.MinecraftLocale -import com.modularmc.registrate.localization.annotation.Trans -import com.modularmc.registrate.localization.annotation.TransVariants -import com.modularmc.registrate.localization.index.LocalizationIndex -import com.modularmc.registrate.localization.index.LocalizationIndex.Entry -import com.modularmc.registrate.localization.index.LocalizationIndex.Frontend - -import com.google.devtools.ksp.processing.CodeGenerator -import com.google.devtools.ksp.processing.Dependencies -import com.google.devtools.ksp.processing.Resolver -import com.google.devtools.ksp.processing.SymbolProcessor -import com.google.devtools.ksp.processing.SymbolProcessorEnvironment -import com.google.devtools.ksp.processing.SymbolProcessorProvider -import com.google.devtools.ksp.symbol.FileLocation -import com.google.devtools.ksp.symbol.KSAnnotated -import com.google.devtools.ksp.symbol.KSAnnotation -import com.google.devtools.ksp.symbol.KSClassDeclaration -import com.google.devtools.ksp.symbol.KSDeclaration -import com.google.devtools.ksp.symbol.KSFile -import com.google.devtools.ksp.symbol.KSPropertyDeclaration -import com.google.devtools.ksp.symbol.Origin - -import java.io.DataOutputStream -import java.util.EnumMap - -class LocalizationSymbolProcessorProvider : SymbolProcessorProvider { - override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor = LocalizationSymbolProcessor(environment.codeGenerator) -} - -/** Collects Kotlin declarations and writes one aggregating KSP resource per mod. */ -private class LocalizationSymbolProcessor(private val codeGenerator: CodeGenerator) : SymbolProcessor { - private class ModDeclarations { - val entries = ArrayList() - val files = LinkedHashSet() - } - - private val mods = LinkedHashMap() - - override fun process(resolver: Resolver): List { - collect(resolver, Trans::class.java.name) { annotation, location, group, namespace -> - group.entries.add(entry(namespace, annotation["key"] as String, annotation, "@Trans $location")) - } - collect(resolver, TransVariants::class.java.name) { annotation, location, group, namespace -> - val prefix = annotation["keyPrefix"] as String - for (variant in annotation["value"] as List<*>) { - variant as KSAnnotation - val id = variant["id"] as String - group.entries.add(entry(namespace, LocalizationIndex.variantKey(prefix, id), variant, "@TransVariants $location [$id]")) - } - } - return emptyList() - } - - override fun finish() { - for ((modId, group) in mods) { - val dependencies = Dependencies(aggregating = true, *group.files.toTypedArray()) - val path = LocalizationIndex.path(modId, Frontend.KSP).removeSuffix(".bin") - val resource = codeGenerator.createNewFileByPath(dependencies, path, "bin") - DataOutputStream(resource.buffered()).use { LocalizationIndex.write(it, group.entries) } - } - } - - private inline fun collect(resolver: Resolver, annotationName: String, consume: (KSAnnotation, String, ModDeclarations, String) -> Unit) { - for (symbol in resolver.getSymbolsWithAnnotation(annotationName)) { - if (symbol.origin != Origin.KOTLIN) continue - val declaration = symbol as KSDeclaration - val annotation = declaration.annotations.first { it.annotationType.resolve().declaration.qualifiedName?.asString() == annotationName } - val modId = annotation["modId"] as String - val namespace = (annotation["namespace"] as String).ifEmpty { modId } - val file = declaration.containingFile!! - val group = mods.getOrPut(modId, ::ModDeclarations) - group.files.add(file) - consume(annotation, location(declaration, file), group, namespace) - } - } - - private fun entry(namespace: String, key: String, annotation: KSAnnotation, location: String): Entry { - val translations = annotation["translations"] as List<*> - val texts = if (translations.isEmpty()) { - emptyMap() - } else { - EnumMap(MinecraftLocale::class.java).apply { - for (value in translations) { - value as KSAnnotation - val locale = (value["locale"] as KSClassDeclaration).simpleName.asString() - put(MinecraftLocale.valueOf(locale), value["text"] as String) - } - } - } - return Entry(namespace, key, annotation["source"] as String, location, texts) - } - - private fun location(declaration: KSDeclaration, file: KSFile): String { - val owner = declaration.parentDeclaration - val name = if (declaration is KSPropertyDeclaration && owner != null) { - "${owner.qualifiedName?.asString()}#${declaration.simpleName.asString()}" - } else { - declaration.qualifiedName?.asString() ?: declaration.simpleName.asString() - } - val line = (declaration.location as FileLocation).lineNumber - return "$name (${file.fileName}:$line)" - } - - private operator fun KSAnnotation.get(name: String): Any? = arguments.first { it.name?.asString() == name }.value -} diff --git a/localization-processor/src/main/resources/META-INF/gradle/incremental.annotation.processors b/localization-processor/src/main/resources/META-INF/gradle/incremental.annotation.processors deleted file mode 100644 index 13c2ec4..0000000 --- a/localization-processor/src/main/resources/META-INF/gradle/incremental.annotation.processors +++ /dev/null @@ -1 +0,0 @@ -com.modularmc.registrate.localization.processor.TranslationProcessor,aggregating diff --git a/localization-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider b/localization-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider deleted file mode 100644 index 273c3e1..0000000 --- a/localization-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider +++ /dev/null @@ -1 +0,0 @@ -com.modularmc.registrate.localization.processor.ksp.LocalizationSymbolProcessorProvider diff --git a/localization-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/localization-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor deleted file mode 100644 index 14f4a6f..0000000 --- a/localization-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor +++ /dev/null @@ -1 +0,0 @@ -com.modularmc.registrate.localization.processor.TranslationProcessor diff --git a/settings.gradle b/settings.gradle index 89aae22..4e03807 100644 --- a/settings.gradle +++ b/settings.gradle @@ -23,4 +23,4 @@ dependencyResolutionManagement { } rootProject.name = "${mod_id}" -include 'localization-processor' +include 'test' diff --git a/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt b/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt index 432c134..4a2355e 100644 --- a/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt +++ b/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt @@ -1,4 +1,4 @@ -// KtLint folds forwarding overloads across the configured line limit during formatting. +// 格式化时,KtLint 会根据行宽限制折叠转发用的重载。 @file:Suppress("ktlint:standard:max-line-length") package com.modularmc.registrate @@ -19,6 +19,7 @@ import com.modularmc.registrate.builders.base.AbstractBuilder import com.modularmc.registrate.builders.base.Builder import com.modularmc.registrate.builders.base.BuilderCallback import com.modularmc.registrate.builders.base.NoConfigBuilder +import com.modularmc.registrate.export.RegistrateExportBuilder import com.modularmc.registrate.internal.RegistrationTracker import com.modularmc.registrate.internal.event.OneTimeEventReceiver.Companion.addModListener import com.modularmc.registrate.internal.lifecycle.RegistrateLifecycle @@ -26,14 +27,17 @@ import com.modularmc.registrate.internal.util.DebugMarkers import com.modularmc.registrate.internal.util.RegistrateLogger.core import com.modularmc.registrate.internal.util.RegistrateLogger.datagen import com.modularmc.registrate.internal.util.RegistrateLogger.modMessage +import com.modularmc.registrate.localization.DeclarationDefaults import com.modularmc.registrate.localization.EntryLocalization +import com.modularmc.registrate.localization.ImportedTranslation import com.modularmc.registrate.localization.LocalizationDeclaration import com.modularmc.registrate.localization.LocalizationDeclaration.Companion.sourceText import com.modularmc.registrate.localization.MinecraftLocale import com.modularmc.registrate.localization.TranslationKey import com.modularmc.registrate.localization.TranslationSource +import com.modularmc.registrate.localization.locale.LocaleDerivation import com.modularmc.registrate.localization.resolution.TranslationRegistry -import com.modularmc.registrate.localization.terminology.LocalizationCatalog +import com.modularmc.registrate.localization.terminology.Terminology import com.modularmc.registrate.providers.RegistrateLangProvider.Companion.toEnglishName import com.modularmc.registrate.providers.core.DataProviderInitializer import com.modularmc.registrate.providers.core.GeneratorType @@ -89,9 +93,12 @@ import net.neoforged.neoforge.registries.RegistryBuilder import com.google.common.collect.ArrayListMultimap import com.google.common.collect.HashBasedTable import com.mojang.serialization.Codec +import it.unimi.dsi.fastutil.objects.ObjectArrayList import org.apache.commons.lang3.tuple.Pair import org.apache.logging.log4j.Level +import java.nio.file.Path +import java.util.EnumMap import java.util.Optional import java.util.concurrent.ConcurrentLinkedQueue import java.util.function.BiConsumer @@ -101,30 +108,25 @@ import java.util.function.Function import java.util.function.Supplier /** - * Manages all registrations and data generators for a mod. + * 统一管理一个模组的条目注册和数据生成回调。 * - * Generally *not* thread-safe, as it holds the current name of the object being built statefully, and uses - * non-concurrent collections. - * - * Begin a new object via [object]. This name will be used for all future entries until the next - * invocation of [object]. Alternatively, the methods that accept a name - * parameter (such as [block]) can be used. These do not affect the current name state. - * - * A simple use may look like: + * 通过 [object] 设置当前条目名称。后续省略名称的构建入口会沿用它,直到再次调用 [object]。 + * 也可用 [block] 等带名称的重载直接指定条目名称,当前名称保持原值。 + * 构建过程持有可变状态,由模组初始化线程负责。 * * ```java * public static final Registrate REGISTRATE = Registrate.create("mymod"); - * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * public static final BlockEntry MY_BLOCK = REGISTRATE.object("my_block") * .block(MyBlock::new) - * .defaultItem() + * .simpleItem() * .register(); * ``` * - * For specifics as to building different registry entries, read the documentation on their respective builders. + * 各类条目的默认值及数据生成入口见对应构建器。 */ abstract class AbstractRegistrate> protected constructor( /** - * The mod ID that this [AbstractRegistrate] is creating objects for + * 本实例管理的模组标识。创建注册条目时使用它作为命名空间。 */ val modid: String, ) { @@ -174,11 +176,11 @@ abstract class AbstractRegistrate> protected construct private val dataGeneration = NonNullSupplier.lazy(DatagenModLoader::isRunningDataGen) + /** 返回延迟读取本次启动是否启用数据生成的取值器。首次查询后复用该结果。 */ open fun doDatagen(): NonNullSupplier = dataGeneration /** - * Get the mod event bus that event listeners will be registered to. Useful when Registrate is used in mods that use - * alternative language loaders, such as forgelin. + * 模组的事件总线,用于绑定注册及数据生成监听器。绑定前为空,扩展构建器可在绑定后用它登记监听器。 */ var modEventBus: IEventBus? = null @@ -187,22 +189,18 @@ abstract class AbstractRegistrate> protected construct private var skipErrors = false /** - * Use this in custom implementations to hide unsafe casts to [S] when returning self. + * 把当前实例转换为子类声明的 [S],便于扩展方法返回自身并继续链式调用。 * - * @return This [AbstractRegistrate] object, cast to [S] + * @return 当前实例,类型为 [S] */ @Suppress("UNCHECKED_CAST") protected fun self(): S = this as S /** - * Called during [creation][Registrate.create] to initialize event listeners. Custom implementations - * may add their own event listeners by overriding this. - * - * *Always* call `super` in your override unless you know what you are doing! + * 在 [Registrate.create] 绑定模组事件总线时初始化监听器。子类可以重写此方法添加监听器,需调用父类实现完成基础绑定。 * - * @param bus - * The event bus - * @return This [AbstractRegistrate] object + * @param bus 要绑定的模组事件总线 + * @return 当前实例 */ open fun registerEventListeners(bus: IEventBus): S { lifecycle.register(bus) @@ -210,38 +208,28 @@ abstract class AbstractRegistrate> protected construct } /** - * Called once per registry to gather collected registrations and add entries to the registry. May be overriden in - * custom implementations to perform additional actions upon entry registration, but - * *must* call `super`. + * 每个注册表触发一次,将此前收集的条目提交到对应注册表。重写时须调用父类实现。 * - * @param event - * The [RegisterEvent] being fired, use [RegisterEvent.getRegistryKey] to query the - * registry type + * @param event 当前注册事件,通过 [RegisterEvent.getRegistryKey] 取得注册表键 */ protected open fun onRegister(event: RegisterEvent) { registrationTracker.onRegister(event, skipErrors, isDevEnvironment) } /** - * Called once per registry at the [lowest priority][net.neoforged.bus.api.EventPriority.LOWEST] to perform any actions that must - * happen after all other entries have been registered, including from other mods. May - * be overriden in custom implementations to perform additional actions upon entry registration, but *must* - * call `super`. + * 以[最低优先级][net.neoforged.bus.api.EventPriority.LOWEST] 处理每个注册表的注册事件。 + * 用于执行依赖当前注册表已完成注册的操作,包括依赖其他模组条目的操作。重写时须调用父类实现。 * - * @param event - * The [RegisterEvent] being fired, use [RegisterEvent.getRegistryKey] to query the - * registry type + * @param event 当前注册事件,通过 [RegisterEvent.getRegistryKey] 取得注册表键 */ protected open fun onRegisterLate(event: RegisterEvent) { registrationTracker.onRegisterLate(event) } /** - * Called when a [CreativeModeTab] is being populated to fill in any entries that belong there. Can be - * overriden in custom implementations. + * 填充创造模式物品栏时触发,执行针对当前标签页的修改回调。 * - * @param event - * The event + * @param event 当前标签页的填充事件 */ protected open fun onBuildCreativeModeTabContents(event: BuildCreativeModeTabContentsEvent) { val modifier = CreativeModeTabModifier( @@ -259,10 +247,9 @@ abstract class AbstractRegistrate> protected construct private var provider: RegistrateDataProvider? = null /** - * Called when datagen begins to add our provider to the generator. Can be overriden in custom implementations. + * 数据生成开始时绑定本实例的生成器。扩展实现可重写此方法,为同一轮生成追加数据。 * - * @param event - * The event + * @param event 本轮数据生成事件 */ protected open fun onData(event: GatherDataEvent) { if (event.mods.contains(modid)) { @@ -273,114 +260,83 @@ abstract class AbstractRegistrate> protected construct } /** - * Get the current name (from the last call to [object]), throwing an exception if it is not set. + * 读取最近一次由 [object] 设置的条目名称。 * - * @return The current entry name - + * @return 当前条目名称 + * @throws UninitializedPropertyAccessException 尚未设置当前名称 */ protected open fun currentName(): String = currentName /** - * Allows retrieval of a previously created entry, of the current name (from the last invocation of - * [object]. Useful to retrieve a different entry than the final state of your - * chain may produce, e.g. + * 在指定注册表中查找当前名称对应的条目。可用于取得构建链一并创建的同名条目,例如方块的物品。 * * ```java - * public static final RegistryEntry MY_BLOCK_ITEM = REGISTRATE.object("my_block") + * public static final RegistryEntry MY_BLOCK_ITEM = REGISTRATE.object("my_block") * .block(MyBlock::new) - * .defaultItem() + * .simpleItem() * .lang("My Special Block") * .build() - * .get(Item.class); + * .get(Registries.ITEM); * ``` * - * @param R - * The type of the registry for which to retrieve the entry - * @param T - * The type of the entry to return - * @param type - * A [ResourceKey] for the registry - * @return A [RegistryEntry] which will supply the requested entry, if it exists - * @throws IllegalArgumentException - * if no such registration has been done - * @throws NullPointerException - * if current name has not been set via [object] + * @param R 注册表中的基础类型 + * @param T 所需条目的具体类型 + * @param type 注册表键 + * @return 指定注册表中的 [RegistryEntry],对象在注册绑定后可读 + * @throws IllegalArgumentException 尚未提交对应条目 + * @throws UninitializedPropertyAccessException 尚未通过 [object] 设置当前名称 */ open fun get(type: ResourceKey>) = this.get(currentName(), type) /** - * Allows retrieval of a previously created entry. Useful to retrieve arbitrary entries that may have been created - * as side-effects of earlier registrations. + * 按名称和注册表查找已提交的条目,也可取得构建器一并创建的附属条目。 * * ```java - * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * public static final BlockEntry MY_BLOCK = REGISTRATE.object("my_block") * .block(MyBlock::new) - * .defaultItem() + * .simpleItem() * .register(); - * ... public static final RegistryEntry MY_BLOCK_ITEM = REGISTRATE.get("my_block", Registries.ITEM); + * public static final RegistryEntry MY_BLOCK_ITEM = REGISTRATE.get("my_block", Registries.ITEM); * ``` * - * @param R - * The type of the registry for which to retrieve the entry - * @param T - * The type of the entry to return - * @param name - * The name of the registry entry to request - * @param type - * A [ResourceKey] for the registry - * @return A [RegistryEntry] which will supply the requested entry, if it exists - * @throws IllegalArgumentException - * if no such registration has been done + * @param R 注册表中的基础类型 + * @param T 所需条目的具体类型 + * @param name 本模组命名空间内的条目名称 + * @param type 注册表键 + * @return 指定的 [RegistryEntry],对象在注册绑定后可读 + * @throws IllegalArgumentException 尚未提交对应条目 */ open fun get(name: String, type: ResourceKey>) = registrationTracker.get(name, type) /** - * Allows retrieval of a previously created entry that may or may not exist. Possibly useful in some very specific - * scenarios, internally used during fluid registration. + * 按名称和注册表查找可选条目。流体注册会用此入口查询可能缺省的附属条目。 * - * @param R - * The type of the registry for which to retrieve the entry - * @param T - * The type of the entry to return - * @param name - * The name of the registry entry to request - * @param type - * A class representing the registry type - * @return A [RegistryEntry] which will supply the requested entry, if it exists + * @param R 注册表中的基础类型 + * @param T 所需条目的具体类型 + * @param name 本模组命名空间内的条目名称 + * @param type 注册表键 + * @return 找到时返回包含 [RegistryEntry] 的 [Optional],查不到时返回空值 */ open fun getOptional(name: String, type: ResourceKey>) = registrationTracker.getOptional(name, type) /** - * Gather a collection of all entries registered for a certain registry - * - * Note that this can be called before registration is complete, but the [entries][RegistryEntry] will be empty - * at that time. + * 收集本实例已提交给指定注册表的条目。注册完成前也可查询,条目引用要等各自绑定后才能取得对象。 * - * @param R - * Registry type - * @param type - * A [ResourceKey] for the registry in question - * @return A collection of [RegistryEntry] objects representing all entries in the given registry which are - * known to this [AbstractRegistrate] object. + * @param R 注册表中的基础类型 + * @param type 注册表键 + * @return 该注册表中由本实例提交的 [RegistryEntry] 集合 */ open fun getAll(type: ResourceKey>) = registrationTracker.getAll(type) /** - * Add a callback to be invoked when a certain entry has been registered. This will be invoked *immediately* - * following registration, before further entries are registered. + * 为指定条目添加注册回调。条目写入注册表后立即执行,再继续注册后续条目。 * - * @param R - * Registry type - * @param T - * Entry type - * @param name - * The name of the entry to watch (implicitly within the [modid][modid] of this - * instance - * @param registryType - * A [ResourceKey] for the registry in question - * @param callback - * The callback to invoke, which will be passed the created entry object - * @return This [AbstractRegistrate] instance + * @param R 注册表中的基础类型 + * @param T 条目类型 + * @param name 本实例的 [modid] 命名空间内要监听的条目名称 + * @param registryType 注册表键 + * @param callback 接收已注册对象的回调 + * @return 当前实例 */ open fun addRegisterCallback(name: String, registryType: ResourceKey>, callback: NonNullConsumer): S { registrationTracker.addRegisterCallback(name, registryType, callback) @@ -388,16 +344,12 @@ abstract class AbstractRegistrate> protected construct } /** - * Add a callback to be invoked when a certain registry has fully completed registration, i.e. all objects of that - * type have been registered. + * 在指定注册表完成所有条目的注册后执行回调。 * - * @param R - * The registry type - * @param registryType - * A [ResourceKey] for the registry in question - * @param callback - * The callback to invoke - * @return This [AbstractRegistrate] instance + * @param R 注册表中的基础类型 + * @param registryType 注册表键 + * @param callback 注册表完成时执行的回调 + * @return 当前实例 */ open fun addRegisterCallback(registryType: ResourceKey>, callback: Runnable): S { registrationTracker.addAfterRegisterCallback(registryType, callback) @@ -405,28 +357,21 @@ abstract class AbstractRegistrate> protected construct } /** - * Check if a certain registry has completed registration. + * 查询指定注册表是否完成注册。 * - * @param R - * The registry type - * @param registryType - * A [ResourceKey] for the registry in question - * @return `true` iff the given registry has finished the registration step + * @param R 注册表中的基础类型 + * @param registryType 注册表键 + * @return 已完成注册时返回真 */ open fun isRegistered(registryType: ResourceKey>) = registrationTracker.isRegistered(registryType) /** - * Get the data provider instance for a given [GeneratorType]. Only works within datagen context, not during - * registration or init. + * 在数据生成阶段查询指定类型的提供器。此入口供生成回调使用。 * - * @param P - * The type of the provider - * @param type - * A [GeneratorType] representing the desired provider - * @return An [Optional] holding the provider, or empty if this provider was not registered. This can happen - * if datagen is run only for client or server providers. - * @throws IllegalStateException - * if datagen has not started yet + * @param P 提供器类型 + * @param type 要查询的 [GeneratorType] + * @return 包含提供器的 [Optional]。本轮未启用对应侧的生成任务时可能为空 + * @throws IllegalStateException 数据生成尚未开始 */ open fun

getDataProvider(type: GeneratorType

): Optional

{ val provider = this.provider @@ -437,57 +382,39 @@ abstract class AbstractRegistrate> protected construct } /** - * Mostly internal, sets the data generator for a certain entry/type combination. This will replace an existing data - * gen callback if it exists. + * 为构建器的条目设置指定类型的数据生成回调。重复设置会替换该条目原有的同类型回调。 * - * @param P - * The type of provider - * @param R - * The registry type - * @param builder - * The builder for the entry - * @param type - * The [GeneratorType] to generate data for - * @param cons - * A callback to be invoked during data generation - * @return this [AbstractRegistrate] + * @param P 提供器类型 + * @param R 注册表中的基础类型 + * @param builder 条目的构建器 + * @param type 要生成的 [GeneratorType] + * @param cons 数据生成时执行的回调 + * @return 当前实例 */ open fun

setDataGenerator(builder: Builder, type: GeneratorType, cons: NonNullConsumer) = this.setDataGenerator(builder.name, builder.registryKey, type, cons) /** - * Mostly internal, removes the data generator for a certain entry/type combination if one was previously - * registered. + * 移除构建器的条目此前配置的指定类型数据生成回调。 * - * @param P - * The type of provider - * @param R - * The registry type - * @param builder - * The builder for the entry - * @param type - * The [GeneratorType] to stop generating data for - * @return this [AbstractRegistrate] + * @param P 提供器类型 + * @param R 注册表中的基础类型 + * @param builder 条目的构建器 + * @param type 要移除的 [GeneratorType] + * @return 当前实例 */ open fun

removeDataGenerator(builder: Builder, type: GeneratorType): S = this.removeDataGenerator(builder.name, builder.registryKey, type) /** - * Mostly internal, sets the data generator for a certain entry/type combination. This will replace an existing data - * gen callback if it exists. + * 为指定条目和生成器类型设置回调。重复设置会替换该条目原有的同类型回调。 * - * @param P - * The type of provider - * @param R - * The registry type - * @param entry - * The name of the entry which the provider is for - * @param registryType - * A [Class] representing the registry type of the entry - * @param type - * The [GeneratorType] to generate data for - * @param cons - * A callback to be invoked during data generation - * @return this [AbstractRegistrate] + * @param P 提供器类型 + * @param R 注册表中的基础类型 + * @param entry 条目名称 + * @param registryType 条目所属的注册表键 + * @param type 要生成的 [GeneratorType] + * @param cons 数据生成时执行的回调 + * @return 当前实例 */ open fun

setDataGenerator(entry: String, registryType: ResourceKey>, type: GeneratorType, cons: NonNullConsumer) = setDataGenerator(entry, registryType, EntryMetadata.DataGenerator(type, cons)) @@ -501,20 +428,14 @@ abstract class AbstractRegistrate> protected construct } /** - * Mostly internal, removes the data generator for a certain entry/type combination if one was previously - * registered. + * 移除指定条目此前配置的同类型数据生成回调。 * - * @param P - * The type of provider - * @param R - * The registry type - * @param entry - * The name of the entry which the provider is for - * @param registryType - * The registry type of the entry - * @param type - * The [GeneratorType] to stop generating data for - * @return this [AbstractRegistrate] + * @param P 提供器类型 + * @param R 注册表中的基础类型 + * @param entry 条目名称 + * @param registryType 条目所属的注册表键 + * @param type 要移除的 [GeneratorType] + * @return 当前实例 */ open fun

removeDataGenerator(entry: String, registryType: ResourceKey>, type: GeneratorType): S { val existing = datagensByEntry.remove(Pair.of(entry, registryType), type) @@ -525,18 +446,12 @@ abstract class AbstractRegistrate> protected construct } /** - * Add a data generator callback that is not associated with any entry, which can never replace an existing data - * generator. + * 追加独立于注册条目的数据生成回调,用于生成没有绑定条目的资源。重复调用会累加回调。 * - * This is useful to add data generator callbacks for miscellaneous data not strictly associated with an entry. - * - * @param T - * The type of provider - * @param type - * The [GeneratorType] to generate data for - * @param cons - * A callback to be invoked during data generation - * @return this [AbstractRegistrate] + * @param T 提供器类型 + * @param type 要生成的 [GeneratorType] + * @param cons 数据生成时执行的回调 + * @return 当前实例 */ open fun addDataGenerator(type: GeneratorType, cons: NonNullConsumer): S { if (dataGeneration.get()) { @@ -546,6 +461,15 @@ abstract class AbstractRegistrate> protected construct return self() } + /** 将回调插入指定生成器类型的队首,使它先于同类型的其他回调执行。 */ + open fun addDataGeneratorFirst(type: GeneratorType, cons: NonNullConsumer): S { + if (dataGeneration.get()) { + check(provider == null) { "Cannot add data generator after construction of root generator" } + datagens.get(type).addFirst(cons) + } + return self() + } + open val dataGenInitializer: DataProviderInitializer by lazy(LazyThreadSafetyMode.NONE, ::DataProviderInitializer) @JvmRecord @@ -553,25 +477,68 @@ abstract class AbstractRegistrate> protected construct private val extraLang = ArrayList() private val generatedLang = ConcurrentLinkedQueue() + private val importedTranslations = ObjectArrayList() private var sourceLocale: MinecraftLocale? = null - private val localizationCatalog = LocalizationCatalog() + private var defaultLocalization = DeclarationDefaults.EMPTY + private var localizationExportPath: Path? = null + private val terminology = Terminology() + private val localeDerivations = EnumMap(MinecraftLocale::class.java) - /** Configures the source locale for this mod before data generation. */ + /** 在数据生成开始前配置本模组的源语言,供本地化声明解释源文本。 */ open fun sourceLocale(locale: MinecraftLocale): S { sourceLocale = locale return self() } - /** Returns the source locale after validating this mod's configuration. */ + /** 开始配置本实例随数据生成写出的导出文件。 */ + open fun export(): RegistrateExportBuilder = RegistrateExportBuilder(this) + + internal fun requestLocalizationExport(path: Path) { + localizationExportPath = path + } + + internal fun localizationExportPath(): Path? = localizationExportPath + + /** 设置此后创建的本地化声明使用的默认值。 */ + open fun localizationDefaults(defaults: DeclarationDefaults): S { + defaultLocalization = defaults + return self() + } + + internal fun localizationDefaultValues(): DeclarationDefaults = defaultLocalization + + /** 读取本模组的源语言。数据生成前须显式配置。 */ open fun requireSourceLocale(): MinecraftLocale { val locale = sourceLocale requireNotNull(locale) { "[$modid] Configure sourceLocale before generating languages" } return locale } - open fun localizationCatalog(): LocalizationCatalog = localizationCatalog + /** 返回当前模组的术语表,供初始化时登记领域、术语和单位。 */ + open fun terminology(): Terminology = terminology - open fun collectRawTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { + /** 在模组初始化期间登记外部译文,供后续客户端侧数据生成解析。 */ + open fun importTranslation(translation: ImportedTranslation): S { + importedTranslations.add(translation) + return self() + } + + internal fun collectImportedTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { + val terminology = terminology() + for (translation in importedTranslations) registry.addImported(locale, translation, terminology) + } + + /** 指定数据生成补齐缺失译文的规则。初始化期间可替换同一目标语言的规则。 */ + open fun deriveLocale(derivation: LocaleDerivation): S { + localeDerivations[derivation.output] = derivation + return self() + } + + internal fun configureLocaleDerivations(registry: TranslationRegistry) { + if (localeDerivations.isNotEmpty()) registry.configureDerivations(terminology(), modid, localeDerivations.values) + } + + internal fun collectRawTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { for (translation in extraLang) { collectRawTranslation(registry, locale, translation) } @@ -583,68 +550,53 @@ abstract class AbstractRegistrate> protected construct private fun collectRawTranslation(registry: TranslationRegistry, locale: MinecraftLocale, translation: RawTranslation) { if (translation.source.kind != TranslationSource.Kind.AUTOMATIC || locale == MinecraftLocale.EN_US) { - registry.add(translation.key, locale, translation.declaration, translation.source) + registry.add(translation.key, locale, translation.declaration, translation.source, terminology()) } } /** - * Add a custom translation mapping using the vanilla style of ResourceLocation -> translation key conversion. + * 按原版的命名规则从类型和资源标识生成翻译键,再登记源文本。方块 `mymod:myblock` 的键是 `block.mymod.myblock`。 * - * @param type - * Type of the object, this is used as a prefix (e.g. - * `["block", "mymod:myblock"] -> "block.mymod.myblock"`) - * @param id - * ID of the object, which will be converted to a lang key via - * [Util.makeDescriptionId] - * @param localizedName - * (English) translation value - * @return A [MutableComponent] representing the translated text + * @param type 翻译键的类型前缀 + * @param id 对象的资源标识,由 [Util.makeDescriptionId] 转换 + * @param localizedName 使用本模组源语言书写的名称 + * @return 使用生成键的 [MutableComponent] */ open fun addLang(type: String, id: ResourceLocation, localizedName: String): MutableComponent = addRawLang(Util.makeDescriptionId(type, id), localizedName) /** - * Add a custom translation mapping using the vanilla style of ResourceLocation -> translation key conversion. - * Also - * appends a suffix to the key. + * 按原版规则生成翻译键,并在键末尾以点号连接后缀,再登记源文本。 * - * @param type - * Type of the object, this is used as a prefix (e.g. - * `["block", "mymod:myblock"] -> "block.mymod.myblock"`) - * @param id - * ID of the object, which will be converted to a lang key via - * [Util.makeDescriptionId] - * @param suffix - * A suffix which will be appended to the generated key (separated by a dot) - * @param localizedName - * (English) translation value - * @return A [MutableComponent] representing the translated text + * @param type 翻译键的类型前缀 + * @param id 对象的资源标识,由 [Util.makeDescriptionId] 转换 + * @param suffix 追加到翻译键末尾的片段 + * @param localizedName 使用本模组源语言书写的名称 + * @return 使用生成键的 [MutableComponent] */ open fun addLang(type: String, id: ResourceLocation, suffix: String, localizedName: String): MutableComponent = addRawLang(Util.makeDescriptionId(type, id) + "." + suffix, localizedName) /** - * Add a custom translation mapping directly to the lang provider. + * 使用指定的翻译键直接登记源文本。 * - * @param key - * The translation key - * @param value - * The (English) translation value - * @return A [MutableComponent] representing the translated text + * @param key 原样写入语言资源的翻译键 + * @param value 使用本模组源语言书写的文本 + * @return 使用指定键的 [MutableComponent] */ open fun addRawLang(key: String, value: String): MutableComponent = addRawLang(key, value, TranslationSource.Kind.DECLARED) private fun addRawLang(key: String, value: String, kind: TranslationSource.Kind): MutableComponent { if (dataGeneration.get()) { - addLocalization(TranslationKey(modid, key), sourceText(value), kind) + addLocalization(TranslationKey(modid, key), sourceText(value, defaultLocalization), kind) } return Component.translatable(key) } - /** Declares independent text and returns a component that uses its exact translation key. */ + /** 声明独立于注册条目的本地化文本,并返回使用该翻译键的组件。 */ open fun addLocalization(key: TranslationKey, configure: Consumer): MutableComponent { if (dataGeneration.get()) { val builder = LocalizationDeclaration.Builder() configure.accept(builder) - addLocalization(key, builder.build(), TranslationSource.Kind.DECLARED) + addLocalization(key, builder.build(defaultLocalization), TranslationSource.Kind.DECLARED) } return Component.translatable(key.value) } @@ -662,7 +614,7 @@ abstract class AbstractRegistrate> protected construct } } - open fun collectEntryTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { + internal fun collectEntryTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { registrationTracker.forEachLocalization { entry, localization -> if (localization.kind == TranslationSource.Kind.AUTOMATIC && locale != MinecraftLocale.EN_US) { return@forEachLocalization @@ -672,7 +624,7 @@ abstract class AbstractRegistrate> protected construct localization.kind, "Builder ${entry.id} in ${entry.key!!.registry()}", ) - registry.add(key, locale, localization.declaration.get(), source) + registry.add(key, locale, localization.declaration.get(), source, terminology()) } } @@ -683,7 +635,7 @@ abstract class AbstractRegistrate> protected construct return null } - /** Runs the registered callbacks for the supplied generator. */ + /** 依次执行为指定数据生成器登记的回调。 */ @Suppress("UNCHECKED_CAST") open fun genData(type: GeneratorType, gen: T) { if (!dataGeneration.get()) return @@ -712,14 +664,10 @@ abstract class AbstractRegistrate> protected construct } /** - * Enable skipping of registry entries and data generators that error during registration/generation. + * 开发时可跳过执行失败的注册条目和生成回调,便于继续排查其余条目。该设置仅在开发环境生效。 * - * **Should only be used for debugging!** `skipErrors(true)` will do nothing outside of a dev - * environment. - * - * @param skipErrors - * `true` to skip errors during registration/generation - * @return this [AbstractRegistrate] + * @param skipErrors 是否跳过注册及生成时的错误 + * @return 当前实例 */ open fun skipErrors(skipErrors: Boolean): S { if (skipErrors && !isDevEnvironment) { @@ -734,13 +682,10 @@ abstract class AbstractRegistrate> protected construct } /** - * Begin a new object, this is typically used at the beginning of a builder chain. The given name will be used until - * this method is called again. This makes it simple to create multiple entries - * with the same name, as is often the case with blocks/items, items/entities, and blocks/TEs. + * 为后续构建链设置当前条目名称。同名的方块和方块物品等条目可共用这个名称,下次调用会替换它。 * - * @param name - * The name to use for future entries - * @return this [AbstractRegistrate] + * @param name 后续条目默认采用的名称 + * @return 当前实例 */ open fun `object`(name: String): S { this.currentName = name @@ -748,14 +693,10 @@ abstract class AbstractRegistrate> protected construct } /** - * Set the default CreativeModeTab to be passed onto future builders. - * - * This special case method should be used if your creative tab instance was not created by Registrate, otherwise - * use [defaultCreativeTab]. + * 为之后创建的物品构建器指定默认创造模式标签页。已有标签页时传入其注册键,通过 Registrate 创建新标签页时使用对应重载。 * - * @param creativeModeTab - * The new default CreativeModeTab type - * @return This [AbstractRegistrate] instance + * @param creativeModeTab 默认创造模式标签页的注册键 + * @return 当前实例 */ open fun defaultCreativeTab(creativeModeTab: ResourceKey): S { defaultCreativeModeTab = creativeModeTab @@ -763,17 +704,11 @@ abstract class AbstractRegistrate> protected construct } /** - * Registers a new modifier callback to be used to modify the given CreativeModeTab. - * - * - * Registers a new callback to be invoked during the [BuildCreativeModeTabContentsEvent] event and - * used to modify what items are displayed on the given [CreativeModeTab]. + * 为指定创造模式标签页追加内容修改回调。每次 [BuildCreativeModeTabContentsEvent] 填充该页时,依次执行已登记的回调。 * - * Calling this method multiple times will add additional callbacks. - * - * @param creativeModeTab The [CreativeModeTab] to register this callback for - * @param modifier The modifier callback to be registered - * @return This [AbstractRegistrate] instance + * @param creativeModeTab 要修改的标签页 + * @param modifier 用来修改显示内容的回调 + * @return 当前实例 */ open fun modifyCreativeModeTab(creativeModeTab: ResourceKey, modifier: Consumer): S { creativeModeTabModifiers.put(creativeModeTab, modifier) @@ -781,112 +716,77 @@ abstract class AbstractRegistrate> protected construct } /** - * Apply a transformation to this [AbstractRegistrate]. Useful to apply helper methods within a fluent chain, - * e.g. + * 在链式调用中应用接收当前 [AbstractRegistrate] 实例的扩展函数。 * * ```java - * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") * .transform(Utils::createMyBlock) - * .get(Block.class); + * .get(Registries.BLOCK); * ``` * - * @param func - * The [function][java.util.function.UnaryOperator] to apply - * @return this [AbstractRegistrate] + * @param func 接收并返回当前实例类型的转换函数 + * @return 转换函数的返回值 */ open fun transform(func: NonNullUnaryOperator): S = func.apply(self()) /** - * Apply a transformation to this [AbstractRegistrate]. Similar to [transform], - * but for actions that return a builder in-progress. Useful to apply helper methods - * within a fluent chain, e.g. + * 在链式调用中执行生成构建器的扩展函数。返回的构建器仍可继续配置。 * * ```java - * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") * .transform(Utils::createMyBlock) - * .lang("My Block") // Can modify the builder afterwards + * .lang("My Block") // 继续配置构建器 * .register(); * ``` * - * @param R - * Registry type - * @param T - * Entry type - * @param P - * Parent type - * @param S2 - * Self type - * @param func - * The [function][Function] to apply - * @return the resultant [Builder] + * @param R 注册表中的基础类型 + * @param T 条目类型 + * @param P 父级对象类型 + * @param S2 返回的构建器类型 + * @param func 接收当前实例并创建构建器的函数 + * @return 转换函数创建的 [Builder] */ open fun > transform(func: NonNullFunction): S2 = func.apply(self()) /** - * Create a builder for a new entry. This is typically not needed, unless you are implementing a - * [custom builder type](https://github.com/ModularMCLib/RegistrateLib/wiki/Custom-Builders). - * - * Uses the currently set name (via [object]) as the name for the new entry, and passes it to the - * factory as the first parameter. + * 以当前条目名称创建构建器,供[自定义构建器](https://github.com/ModularMCLib/RegistrateLib/wiki/Custom-Builders)接入。 + * 工厂的首个参数是最近一次由 [object] 设置的名称。 * - * @param R - * Registry type - * @param T - * Entry type - * @param P - * Parent type - * @param S2 - * Self type - * @param factory - * The factory to create the builder - * @return The [Builder] instance + * @param R 注册表中的基础类型 + * @param T 条目类型 + * @param P 父级对象类型 + * @param S2 返回的构建器类型 + * @param factory 接收条目名称和注册回调的工厂 + * @return 工厂创建的 [Builder] */ open fun > entry(factory: NonNullBiFunction) = entry( currentName(), ) { callback: BuilderCallback -> factory.apply(currentName(), callback) } /** - * Create a builder for a new entry. This is typically not needed, unless you are implementing a - * [custom builder type](https://github.com/ModularMCLib/RegistrateLib/wiki/Custom-Builders). + * 调用工厂创建可提交到当前实例的[自定义构建器](https://github.com/ModularMCLib/RegistrateLib/wiki/Custom-Builders)。 * - * @param R - * Registry type - * @param T - * Entry type - * @param P - * Parent type - * @param S2 - * Self type - * @param name - * The name to use for the entry - * @param factory - * The factory to create the builder - * @return The [Builder] instance + * @param R 注册表中的基础类型 + * @param T 条目类型 + * @param P 父级对象类型 + * @param S2 返回的构建器类型 + * @param name 本次创建所用的条目名称 + * @param factory 接收注册回调的构建器工厂 + * @return 工厂创建的 [Builder] */ open fun > entry(name: String, factory: NonNullFunction): S2 = factory.apply(callback) /** - * Factory method to accept a completed builder and add it to the registration queue. - * - * Satisfies the functional interface [BuilderCallback], which is typically given to new builder instances - * when they are constructed. + * 接收配置完成的构建器,并将其条目加入待注册队列。构建器通常在创建时取得指向此入口的 [BuilderCallback]。 * - * @param R - * Registry type - * @param T - * Entry type - * @param name - * Thename of the entry being created - * @param type - * The registry to add the entry to - * @param builder - * The builder instance that was used to create this entry. Not used by default implementation, - * but custom extensions may use it for some purpose - * @param creator - * Constructor for the new entry object - * @param entryFactory - * Optional custom factory to create special [RegistryEntry] types - * @return A [RegistryEntry] that will hold the created entry after registration is complete + * @param R 注册表中的基础类型 + * @param T 条目类型 + * @param name 要创建的条目名称 + * @param type 要向其中登记条目的注册表键 + * @param builder 提供条目声明的构建器 + * @param creator 注册时创建条目对象的工厂 + * @param entryFactory 可选的 [RegistryEntry] 工厂,用于返回专用条目类型 + * @return 注册完成后可取得对象的 [RegistryEntry] */ protected open fun accept( name: String, @@ -918,102 +818,102 @@ abstract class AbstractRegistrate> protected construct } /** - * Returns the declarations for an entry submitted by this Registrate instance. + * 读取本实例为已提交条目保存的声明。 */ open fun getEntryMetadata(key: ResourceKey<*>): EntryMetadata = registrationTracker.getMetadata(key) /** - * Helper to create a new registry for custom objects. The returned [ResourceKey] can be used immediately in - * methods like [simple][simple] or - * [generic][generic]. - * - * Alternatively, a custom [builder][Builder] can be created. - * - * This method will automatically subscribe to the [NewRegistryEvent] and create the registry at the proper - * time. Thus, the new registry will not exist immediately after this is called. + * 为自定义对象创建注册表。返回的 [ResourceKey] 可立即用于 [simple]、[generic] 或自定义 [Builder]。 + * 注册表本身在 [NewRegistryEvent] 触发时创建。 * - * @param R - * The type of object the new registry will contain - * @param name - * The ID of this registry - * @param builder - * A function to create the [RegistryBuilder] that defines the other properties/behaviors of - * the created registry - * @return A [resource key][ResourceKey] referencing the to-be-created registry. + * @param R 新注册表收录的对象类型 + * @param name 注册表标识的路径部分 + * @param builder 接收注册表键并创建 [RegistryBuilder] 的函数 + * @return 待创建注册表的 [ResourceKey] */ open fun makeRegistry(name: String, builder: Function>, RegistryBuilder>): ResourceKey> { val registryId = ResourceKey.createRegistryKey(ResourceLocation.fromNamespaceAndPath(modid, name)) addModListener( this, NewRegistryEvent::class.java, - Consumer { e: NewRegistryEvent -> e.register(builder.apply(registryId).create()) }, + Consumer { e: NewRegistryEvent -> e.register(builder.apply(registryId).create()) }, ) return registryId } /** - * Registers the given registry key as an unsynced datapack registry, which will cause data to be loaded from - * a datapack folder based on the registry's name. The datapack registry is not required to be present - * on clients when connecting to servers with the mod/registry. + * 注册一个仅在服务端加载的数据包注册表,客户端连接时可省略该注册表。 + * 模组命名空间下的注册表从 `data/<数据包命名空间>/<模组标识>/<注册表路径>/` 读取数据。 * - * Data JSONs will be loaded from `data//modid/registryname/`, where `modid` is the - * namespace of the registry key. - * - * @param name The ID of this registry - * @param codec The codec to be used for loading data from datapacks on servers - * @see .makeDatapackRegistry + * @param name 注册表标识的路径部分 + * @param codec 服务端读取数据包条目的编解码器 + * @return 新注册表的 [ResourceKey] + * @see makeDatapackRegistry */ open fun makeDatapackRegistry(name: String, codec: Codec) = makeDatapackRegistry(name, codec, null) /** - * Registers the registry key as a datapack registry, which will cause data to be loaded from - * a datapack folder based on the registry's name. - * - * Data JSONs will be loaded from `data//modid/registryname/`, where `modid` is the - * namespace of the registry key. + * 注册数据包注册表。模组命名空间下的注册表从 `data/<数据包命名空间>/<模组标识>/<注册表路径>/` 读取数据。 + * 提供网络编解码器时,服务器会同步条目,客户端也须拥有该注册表,可通过 [net.minecraft.client.multiplayer.ClientPacketListener.registryAccess] 访问。 + * 网络编解码器为空时由服务端独立加载。 * - * @param name The ID of this registry - * @param codec The codec to be used for loading data from datapacks on servers - * @param networkCodec The codec to be used for syncing loaded data to clients. - * If `networkCodec` is null, data will not be synced, and clients are not required to - * have this - * datapack registry to join a server. - * - * If `networkCodec` is not null, clients must have this datapack registry/mod - * when joining a server that has this datapack registry/mod. - * The data will be synced using the network codec and accessible via - * [net.minecraft.client.multiplayer.ClientPacketListener.registryAccess]. - * @see .makeDatapackRegistry + * @param name 注册表标识的路径部分 + * @param codec 服务端读取数据包条目的编解码器 + * @param networkCodec 同步到客户端时使用的编解码器,可以为空 + * @return 新注册表的 [ResourceKey] */ open fun makeDatapackRegistry(name: String, codec: Codec, networkCodec: Codec?): ResourceKey> { val registryId = ResourceKey.createRegistryKey(ResourceLocation.fromNamespaceAndPath(modid, name)) addModListener( this, NewRegistry::class.java, - Consumer { event: NewRegistry -> event.dataPackRegistry(registryId, codec, networkCodec) }, + Consumer { event: NewRegistry -> event.dataPackRegistry(registryId, codec, networkCodec) }, ) return registryId } - /* === Builder helpers === */ - // Generic + /* === 条目构建入口 === */ + // 通用条目 + + /** 使用当前条目名称提交注册,创建游戏对象时调用 [factory]。 */ open fun simple(registryType: ResourceKey>, factory: NonNullSupplier): RegistryEntry = simple(currentName(), registryType, factory) + /** 以 [name] 提交指定注册表的条目。返回的引用在注册事件绑定后可取得对象。 */ open fun simple(name: String, registryType: ResourceKey>, factory: NonNullSupplier) = simple(this, name, registryType, factory) + /** 使用当前条目名称提交注册,将 [parent] 作为通用构建器的返回目标。 */ open fun simple(parent: P, registryType: ResourceKey>, factory: NonNullSupplier): RegistryEntry = simple(parent, currentName(), registryType, factory) + /** + * 创建通用构建器并立即提交注册。对象由注册事件调用工厂创建。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的条目名称 + * @param registryType 目标注册表的键 + * @param factory 注册时创建条目对象的工厂 + * @return 延迟绑定的条目引用 + */ open fun simple(parent: P, name: String, registryType: ResourceKey>, factory: NonNullSupplier): RegistryEntry = generic(parent, name, registryType, factory).register() + /** 使用当前名称创建通用构建器,可继续附加标签和数据生成配置。 */ open fun generic(registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = generic(self(), registryType, factory) + /** 以 [name] 创建通用构建器。注册时执行 [factory]。 */ open fun generic(name: String, registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = generic(self(), name, registryType, factory) + /** 为当前名称创建通用构建器,调用其 `build` 后返回 [parent]。 */ open fun generic(parent: P, registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = generic(parent, currentName(), registryType, factory) + /** + * 为任意注册表创建通用条目构建器,供没有专用构建器的条目使用。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的条目名称 + * @param registryType 目标注册表的键 + * @param factory 注册时创建条目对象的工厂 + * @return 可继续设置标签、本地化和数据生成回调的构建器 + */ open fun generic(parent: P, name: String, registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = entry>( name, @@ -1028,13 +928,24 @@ abstract class AbstractRegistrate> protected construct ) } - // Items + // 物品 + + /** 使用当前条目名称创建物品构建器,由 [factory] 接收配置完成的物品属性。 */ open fun item(factory: NonNullFunction): ItemBuilder = item(self(), factory) + /** 以 [name] 创建物品构建器,由 [factory] 接收配置完成的物品属性。 */ open fun item(name: String, factory: NonNullFunction): ItemBuilder = item(self(), name, factory) + /** 使用当前条目名称创建物品构建器,调用其 `build` 后返回 [parent]。 */ open fun item(parent: P, factory: NonNullFunction): ItemBuilder = item(parent, currentName(), factory) + /** + * 创建指定名称的物品构建器。构建器应用属性变换后,才将结果传给 [factory]。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的物品名称 + * @param factory 使用最终物品属性创建物品的工厂 + * @return 可继续配置物品属性和数据生成的构建器 + */ open fun item(parent: P, name: String, factory: NonNullFunction): ItemBuilder = entry>( name, ) { callback: BuilderCallback -> @@ -1042,13 +953,24 @@ abstract class AbstractRegistrate> protected construct .tab(defaultCreativeModeTab) } - // Blocks + // 方块 + + /** 使用当前条目名称创建方块构建器,由 [factory] 接收配置完成的方块属性。 */ open fun block(factory: NonNullFunction): BlockBuilder = block(self(), factory) + /** 以 [name] 创建方块构建器,由 [factory] 接收配置完成的方块属性。 */ open fun block(name: String, factory: NonNullFunction): BlockBuilder = block(self(), name, factory) + /** 使用当前条目名称创建方块构建器,调用其 `build` 后返回 [parent]。 */ open fun block(parent: P, factory: NonNullFunction): BlockBuilder = block(parent, currentName(), factory) + /** + * 创建指定名称的方块构建器。构建器应用属性变换后,才将结果传给 [factory]。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的方块名称 + * @param factory 使用最终方块属性创建方块的工厂 + * @return 可继续配置方块属性、附属物品和数据生成的构建器 + */ open fun block(parent: P, name: String, factory: NonNullFunction): BlockBuilder = entry>( name, ) { callback: BuilderCallback -> @@ -1061,13 +983,25 @@ abstract class AbstractRegistrate> protected construct ) } - // Entities + // 实体 + + /** 使用当前条目名称创建实体类型构建器,以 [classification] 设置原版实体分类。 */ open fun entity(factory: EntityFactory, classification: MobCategory): EntityBuilder = entity(self(), factory, classification) + /** 以 [name] 创建实体类型构建器,以 [classification] 设置原版实体分类。 */ open fun entity(name: String, factory: EntityFactory, classification: MobCategory): EntityBuilder = entity(self(), name, factory, classification) + /** 使用当前条目名称创建实体类型构建器,调用其 `build` 后返回 [parent]。 */ open fun entity(parent: P, factory: EntityFactory, classification: MobCategory): EntityBuilder = entity(parent, currentName(), factory, classification) + /** + * 创建指定名称的实体类型构建器。游戏创建实体实例时调用 [factory]。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的实体类型名称 + * @param factory 由实体类型和所在世界创建实体实例的工厂 + * @param classification 原版使用的实体分类 + * @return 可继续配置实体类型、渲染器和生成数据的构建器 + */ open fun entity(parent: P, name: String, factory: EntityFactory, classification: MobCategory): EntityBuilder = entry, EntityType, P, EntityBuilder>( name, @@ -1082,13 +1016,24 @@ abstract class AbstractRegistrate> protected construct ) } - // Block Entities + // 方块实体 + + /** 使用当前条目名称创建方块实体类型构建器,可接着指定适用方块。 */ open fun blockEntity(factory: BlockEntityFactory): BlockEntityBuilder = blockEntity(self(), factory) + /** 以 [name] 创建方块实体类型构建器,可接着指定适用方块。 */ open fun blockEntity(name: String, factory: BlockEntityFactory): BlockEntityBuilder = blockEntity(self(), name, factory) + /** 使用当前条目名称创建方块实体类型构建器,调用其 `build` 后返回 [parent]。 */ open fun blockEntity(parent: P, factory: BlockEntityFactory): BlockEntityBuilder = blockEntity(parent, currentName(), factory) + /** + * 创建指定名称的方块实体类型构建器,由 [factory] 为指定位置创建方块实体实例。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的方块实体类型名称 + * @param factory 使用类型、位置和方块状态创建实例的工厂 + * @return 可继续指定适用方块和渲染器的构建器 + */ open fun blockEntity(parent: P, name: String, factory: BlockEntityFactory): BlockEntityBuilder = entry, BlockEntityType, P, BlockEntityBuilder>( name, @@ -1102,46 +1047,64 @@ abstract class AbstractRegistrate> protected construct ) } - // Fluids + // 流体 + + /** 为当前名称创建流体构建器,使用默认纹理、默认流体类型和默认的流动流体实现。 */ open fun fluid(): FluidBuilder = fluid(self()) + /** 为当前名称创建流体构建器,使用默认纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。 */ open fun fluid(typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), typeFactory) + /** 为当前名称创建流体构建器,使用默认纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。 */ open fun fluid(fluidType: NonNullSupplier): FluidBuilder = fluid(self(), fluidType) + /** 为当前名称创建流体构建器,使用指定的源流体纹理和流动纹理,并使用默认流体类型和默认的流动流体实现。 */ open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation): FluidBuilder = fluid(self(), stillTexture, flowingTexture) + /** 为当前名称创建流体构建器,使用指定纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。 */ open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation, typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), stillTexture, flowingTexture, typeFactory) + /** 为当前名称创建流体构建器,使用指定纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。 */ open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidType: NonNullSupplier): FluidBuilder = fluid(self(), stillTexture, flowingTexture, fluidType) + /** 为当前名称创建流体构建器,使用指定纹理和默认流体类型,并由 [fluidFactory] 创建流动流体。 */ open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidFactory: FluidFactory): FluidBuilder = fluid(self(), stillTexture, flowingTexture, fluidFactory) + /** 为当前名称创建流体构建器,使用指定纹理,并分别由 [typeFactory] 和 [fluidFactory] 创建流体类型和流动流体。 */ open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation, typeFactory: FluidTypeFactory, fluidFactory: FluidFactory): FluidBuilder = fluid(self(), stillTexture, flowingTexture, typeFactory, fluidFactory) + /** 为当前名称创建流体构建器,使用指定纹理和 [fluidType] 提供的流体类型,并由 [fluidFactory] 创建流动流体。 */ open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidType: NonNullSupplier, fluidFactory: FluidFactory): FluidBuilder = fluid(self(), stillTexture, flowingTexture, fluidType, fluidFactory) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理、默认流体类型和默认的流动流体实现。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun fluid(name: String): FluidBuilder = fluid(self(), name) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun fluid(name: String, typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), name, typeFactory) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun fluid(name: String, fluidType: NonNullSupplier): FluidBuilder = fluid(self(), name, fluidType) + /** 以 [name] 为注册名创建流体构建器,使用指定的源流体纹理和流动纹理,并使用默认流体类型和默认的流动流体实现。 */ open fun fluid(name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。 */ open fun fluid(name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, typeFactory) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。 */ open fun fluid(name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidType: NonNullSupplier): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, fluidType) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认流体类型,并由 [fluidFactory] 创建流动流体。 */ open fun fluid(name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidFactory: FluidFactory): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, fluidFactory) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理,并分别由 [typeFactory] 和 [fluidFactory] 创建流体类型和流动流体。 */ open fun fluid( name: String, stillTexture: ResourceLocation, @@ -1150,6 +1113,7 @@ abstract class AbstractRegistrate> protected construct fluidFactory: FluidFactory, ): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, typeFactory, fluidFactory) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和 [fluidType] 提供的流体类型,并由 [fluidFactory] 创建流动流体。 */ open fun fluid( name: String, stillTexture: ResourceLocation, @@ -1158,23 +1122,31 @@ abstract class AbstractRegistrate> protected construct fluidFactory: FluidFactory, ): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, fluidType, fluidFactory) + /** 为当前名称创建流体构建器,使用默认纹理、默认流体类型和默认的流动流体实现。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P): FluidBuilder = fluid(parent, currentName()) + /** 为当前名称创建流体构建器,使用默认纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, typeFactory: FluidTypeFactory): FluidBuilder = fluid(parent, currentName(), typeFactory) + /** 为当前名称创建流体构建器,使用默认纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, fluidType: NonNullSupplier): FluidBuilder = fluid(parent, currentName(), fluidType) + /** 为当前名称创建流体构建器,使用指定的源流体纹理和流动纹理,并使用默认流体类型和默认的流动流体实现。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, stillTexture: ResourceLocation, flowingTexture: ResourceLocation): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture) + /** 为当前名称创建流体构建器,使用指定纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, typeFactory: FluidTypeFactory): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory) + /** 为当前名称创建流体构建器,使用指定纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidType: NonNullSupplier): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, fluidType) + /** 为当前名称创建流体构建器,使用指定纹理和默认流体类型,并由 [fluidFactory] 创建流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid(parent: P, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidFactory: FluidFactory): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, fluidFactory) + /** 为当前名称创建流体构建器,使用指定纹理,并分别由 [typeFactory] 和 [fluidFactory] 创建流体类型和流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid( parent: P, stillTexture: ResourceLocation, @@ -1183,6 +1155,7 @@ abstract class AbstractRegistrate> protected construct fluidFactory: FluidFactory, ): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory, fluidFactory) + /** 为当前名称创建流体构建器,使用指定纹理和 [fluidType] 提供的流体类型,并由 [fluidFactory] 创建流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid( parent: P, stillTexture: ResourceLocation, @@ -1191,16 +1164,20 @@ abstract class AbstractRegistrate> protected construct fluidFactory: FluidFactory, ): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, fluidType, fluidFactory) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理、默认流体类型和默认的流动流体实现。调用构建器的 `build` 后返回 [parent]。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun

fluid(parent: P, name: String): FluidBuilder = fluid(parent, name, defaultStillTexture(), defaultFlowingTexture()) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。调用构建器的 `build` 后返回 [parent]。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun

fluid(parent: P, name: String, typeFactory: FluidTypeFactory): FluidBuilder = fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), typeFactory) + /** 以 [name] 为注册名创建流体构建器,使用默认纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。调用构建器的 `build` 后返回 [parent]。默认纹理路径仍以当前名称为基础,须先调用 [object]。 */ open fun

fluid(parent: P, name: String, fluidType: NonNullSupplier): FluidBuilder = fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), fluidType) private fun defaultStillTexture(): ResourceLocation = ResourceLocation.fromNamespaceAndPath(modid, "block/" + currentName() + "_still") private fun defaultFlowingTexture(): ResourceLocation = ResourceLocation.fromNamespaceAndPath(modid, "block/" + currentName() + "_flow") + /** 以 [name] 为注册名创建流体构建器,使用指定的源流体纹理和流动纹理,并使用默认流体类型和默认的流动流体实现。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation): FluidBuilder = entry>( name, ) { callback: BuilderCallback -> @@ -1213,6 +1190,7 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认的流动流体实现,并由 [typeFactory] 创建流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, typeFactory: FluidTypeFactory): FluidBuilder = entry>( name, @@ -1226,6 +1204,7 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认的流动流体实现,并复用 [fluidType] 提供的流体类型。调用构建器的 `build` 后返回 [parent]。 */ open fun

fluid(parent: P, name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidType: NonNullSupplier): FluidBuilder = entry>( name, @@ -1239,6 +1218,7 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和默认流体类型,并由 [fluidFactory] 创建流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid(parent: P, name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidFactory: FluidFactory): FluidBuilder = entry>( name, @@ -1252,6 +1232,7 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理,并分别由 [typeFactory] 和 [fluidFactory] 创建流体类型和流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid( parent: P, name: String, @@ -1272,6 +1253,7 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) + /** 以 [name] 为注册名创建流体构建器,使用指定纹理和 [fluidType] 提供的流体类型,并由 [fluidFactory] 创建流动流体。调用构建器的 `build` 后返回 [parent]。 */ open fun fluid( parent: P, name: String, @@ -1292,16 +1274,28 @@ abstract class AbstractRegistrate> protected construct ) }.model(stillTexture, flowingTexture) - // Menu + // 菜单 + + /** 使用当前条目名称创建普通菜单构建器。界面工厂仅在客户端取得。 */ open fun menu(factory: MenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(currentName(), factory, screenFactory) + /** 以 [name] 创建普通菜单构建器。界面工厂仅在客户端取得。 */ open fun menu(name: String, factory: MenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(self(), name, factory, screenFactory) + /** 使用当前条目名称创建普通菜单构建器,调用其 `build` 后返回 [parent]。 */ open fun menu(parent: P, factory: MenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(parent, currentName(), factory, screenFactory) + /** + * 创建普通菜单构建器。菜单工厂接收菜单类型、窗口标识和玩家物品栏。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的菜单类型名称 + * @param factory 菜单实例工厂 + * @param screenFactory 客户端的界面工厂取值器 + * @return 尚可配置注册回调的菜单构建器 + */ open fun menu( parent: P, name: String, @@ -1320,15 +1314,26 @@ abstract class AbstractRegistrate> protected construct ) } + /** 使用当前条目名称创建支持读取网络数据的菜单构建器。 */ open fun menu(factory: ForgeMenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(currentName(), factory, screenFactory) + /** 以 [name] 创建支持读取网络数据的菜单构建器。 */ open fun menu(name: String, factory: ForgeMenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(self(), name, factory, screenFactory) + /** 使用当前条目名称创建支持读取网络数据的菜单构建器,调用其 `build` 后返回 [parent]。 */ open fun menu(parent: P, factory: ForgeMenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = menu(parent, currentName(), factory, screenFactory) + /** + * 创建支持读取网络数据的菜单构建器。打开菜单时,工厂可读取服务端发送的附加数据。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的菜单类型名称 + * @param factory 可读取打开数据的菜单实例工厂 + * @param screenFactory 客户端的界面工厂取值器 + * @return 尚可配置注册回调的菜单构建器 + */ open fun menu( parent: P, name: String, @@ -1347,39 +1352,54 @@ abstract class AbstractRegistrate> protected construct ) } - // Creative Tab + // 创造模式标签页 + + /** 使用当前条目名称创建创造模式标签页构建器,并将该标签页设为本实例的默认页。 */ open fun defaultCreativeTab(): NoConfigBuilder = defaultCreativeTab(self()) + /** 以 [name] 创建创造模式标签页构建器,并将该标签页设为本实例的默认页。 */ open fun defaultCreativeTab(name: String): NoConfigBuilder = defaultCreativeTab(self(), name) + /** 使用当前名称创建默认标签页,调用构建器的 `build` 后返回 [parent]。 */ open fun

defaultCreativeTab(parent: P): NoConfigBuilder = defaultCreativeTab(parent, currentName()) + /** 以 [name] 创建默认标签页,调用构建器的 `build` 后返回 [parent]。 */ open fun

defaultCreativeTab(parent: P, name: String): NoConfigBuilder = defaultCreativeTab( parent, name, ) { tab: CreativeModeTab.Builder -> } + /** 为当前名称构建默认标签页,由 [config] 调整原版标签页构建器。 */ open fun defaultCreativeTab(config: Consumer): NoConfigBuilder = defaultCreativeTab(self(), config) + /** 以 [name] 构建默认标签页,由 [config] 调整原版标签页构建器。 */ open fun defaultCreativeTab(name: String, config: Consumer): NoConfigBuilder = defaultCreativeTab(self(), name, config) + /** 为当前名称构建默认标签页,由 [config] 调整原版构建器,完成后返回 [parent]。 */ open fun

defaultCreativeTab(parent: P, config: Consumer): NoConfigBuilder = defaultCreativeTab(parent, currentName(), config) + /** + * 创建标签页构建器并立即更新本实例的默认标签页指向。实际注册时先设置默认标题和图标,再执行 [config]。 + * @param parent 构建链返回的上一级对象 + * @param name 当前模组命名空间下的标签页名称 + * @param config 用于调整标题、图标或展示内容的回调 + * @return 可追加注册回调的标签页构建器 + */ open fun

defaultCreativeTab(parent: P, name: String, config: Consumer): NoConfigBuilder { this.defaultCreativeModeTab = ResourceKey.create( Registries.CREATIVE_MODE_TAB, ResourceLocation.fromNamespaceAndPath(this.modid, name), ) - return this.generic( + return this.generic( parent, name, Registries.CREATIVE_MODE_TAB, ) { val builder = CreativeModeTab.builder() .icon { - getAll(Registries.ITEM).firstOrNull()?.get()?.let(::ItemStack) ?: ItemStack.EMPTY + getAll(Registries.ITEM).firstOrNull()?.get()?.let(::ItemStack) ?: ItemStack.EMPTY } .title( addRawLang( @@ -1397,7 +1417,7 @@ abstract class AbstractRegistrate> protected construct private val LOGGER = core() private val DATAGEN_LOGGER = datagen() - /** Enables development diagnostics when NeoForge is running outside production. */ + /** NeoForge 在开发环境中运行时启用开发诊断。 */ @get:JvmStatic val isDevEnvironment: Boolean get() = !FMLEnvironment.production diff --git a/src/main/java/com/modularmc/registrate/Registrate.kt b/src/main/java/com/modularmc/registrate/Registrate.kt index 8b098b0..7799b37 100644 --- a/src/main/java/com/modularmc/registrate/Registrate.kt +++ b/src/main/java/com/modularmc/registrate/Registrate.kt @@ -4,11 +4,12 @@ import com.modularmc.registrate.internal.util.RegistrateLogger import net.neoforged.fml.ModList +/** 一个模组的默认注册入口。在初始化阶段通过 [create] 创建并绑定到模组事件总线。 */ open class Registrate protected constructor(modid: String) : AbstractRegistrate(modid) { companion object { private val LOGGER = RegistrateLogger.core() - /** Creates a Registrate and attaches its listeners to the owning mod's event bus. */ + /** 创建一个 Registrate 实例,并将监听器绑定到所属模组的事件总线。 */ @JvmStatic fun create(modid: String): Registrate { val registrate = Registrate(modid) diff --git a/src/main/java/com/modularmc/registrate/RegistrateLib.java b/src/main/java/com/modularmc/registrate/RegistrateLib.java index f992d5f..cb6908b 100644 --- a/src/main/java/com/modularmc/registrate/RegistrateLib.java +++ b/src/main/java/com/modularmc/registrate/RegistrateLib.java @@ -7,13 +7,11 @@ import org.apache.logging.log4j.Logger; /** - * Runtime entrypoint for the ModularMCLib variant of Registrate. + * ModularMCLib 维护的 Registrate 运行时入口。 * *

- * This library is intended to load as its own NeoForge mod so downstream - * mods can depend on it as a prerequisite during development. Integration - * scenarios, sample registrations, and visual validation belong in the test - * harness under {@code src/test}. + * 下游模组可将此库作为独立的 NeoForge 模组依赖。集成用例、注册示例和视觉检查入口位于 {@code test/src/main}。 + *

*/ @Mod(RegistrateLib.MOD_ID) public final class RegistrateLib { @@ -23,5 +21,10 @@ public final class RegistrateLib { public static final Logger LOGGER = LogManager.getLogger(MOD_NAME); + /** + * 供 NeoForge 加载运行时库时实例化。各下游模组自行创建其所属的 {@link Registrate}。 + * + * @param modEventBus NeoForge 注入的本库模组事件总线 + */ public RegistrateLib(IEventBus modEventBus) {} } diff --git a/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt index d276606..da37c9a 100644 --- a/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt @@ -37,13 +37,10 @@ import java.util.function.Function import java.util.function.Supplier /** - * A builder for blocks, allows for customization of the [Block.Properties], creation of block items, and - * configuration of data associated with blocks (loot tables, recipes, etc.). + * 构建和注册方块,可配置方块属性、创建方块物品,并生成模型、配方和战利品表。 * - * @param T - * The type of block being built - * @param P - * Parent object type + * @param T 要构建的方块类型 + * @param P 父级对象类型 */ open class BlockBuilder protected constructor( owner: AbstractRegistrate<*>, @@ -59,16 +56,10 @@ open class BlockBuilder protected constructor( private var colorHandler: NonNullSupplier>? = null /** - * Modify the properties of the block. Modifications are done lazily, but the passed function is composed with the - * current one, and as such this method can be called multiple times to perform - * different operations. + * 登记方块属性变换,构建方块时按登记顺序应用。变换返回另一份属性对象时,后续变换从新对象开始。 * - * - * If a different properties instance is returned, it will replace the existing one entirely. - * - * @param func - * The action to perform on the properties - * @return this [BlockBuilder] + * @param func 要应用的属性变换 + * @return 当前构建器 */ open fun properties(func: NonNullUnaryOperator): BlockBuilder { propertiesCallback = propertiesCallback.andThen(func) @@ -76,13 +67,10 @@ open class BlockBuilder protected constructor( } /** - * Replace the initial state of the block properties, without replacing or removing any modifications done via - * [properties]. + * 以另一方块的完整属性副本作为起点,保留已通过 [properties] 登记的变换。 * - * @param block - * The block to create the initial properties from (via - * [Block.Properties.ofFullCopy]) - * @return this [BlockBuilder] + * @param block 用于读取初始属性的方块供应器 + * @return 当前构建器 */ open fun initialProperties(block: NonNullSupplier): BlockBuilder { initialProperties = NonNullSupplier { BlockBehaviour.Properties.ofFullCopy(block.get()) } @@ -90,25 +78,17 @@ open class BlockBuilder protected constructor( } /** - * Create a standard [BlockItem] for this block, building it immediately, and not allowing for further - * configuration. + * 用默认配置提交此方块的 [BlockItem]。物品沿用方块的翻译键。 * - * - * The item will have no lang entry (since it would duplicate the block's) - * - * @return this [BlockBuilder] - * @see .item + * @return 当前构建器 + * @see item */ open fun simpleItem(): BlockBuilder = item().build() /** - * Create a standard [BlockItem] for this block, and return the builder for it so that further customization - * can be done. - * + * 创建标准 [BlockItem] 的构建器,便于继续配置物品。默认使用方块的翻译键。 * - * The item will have no lang entry (since it would duplicate the block's) - * - * @return the [ItemBuilder] for the [BlockItem] + * @return 方块物品的 [ItemBuilder] */ open fun item() = item( NonNullBiFunction { block: T, properties: Item.Properties -> @@ -120,18 +100,11 @@ open class BlockBuilder protected constructor( ) /** - * Create a [BlockItem] for this block, which is created by the given factory, and return the builder for it - * so that further customization can be done. - * + * 使用指定工厂创建方块物品构建器。默认使用简单的方块物品模型,并沿用方块的翻译键。 * - * By default, the item will have no lang entry (since it would duplicate the block's) and a simple block item - * model. - * - * @param I - * The type of the item - * @param factory - * A factory for the item, which accepts the block object and properties and returns a new item - * @return the [ItemBuilder] for the [BlockItem] + * @param I 物品类型 + * @param factory 接收方块和物品属性并创建物品的工厂 + * @return 方块物品的 [ItemBuilder] */ open fun item(factory: NonNullBiFunction): ItemBuilder> { return owner.item( @@ -160,30 +133,21 @@ open class BlockBuilder protected constructor( } /** - * Create a [BlockEntity] for this block, which is created by the given factory, and assigned this block as - * its one and only valid block. + * 创建并提交方块实体类型,初始有效方块为当前方块。 * - * @param BE - * The type of the block entity - * @param factory - * A factory for the block entity - * @return this [BlockBuilder] - */ + * @param BE 方块实体类型 + * @param factory 创建方块实体的工厂 + * @return 当前构建器 + */ open fun simpleBlockEntity(factory: BlockEntityBuilder.BlockEntityFactory) = blockEntity(factory).build() /** - * Create a [BlockEntity] for this block, which is created by the given factory, and assigned this block as - * its one and only valid block. - * + * 创建方块实体构建器,初始有效方块为当前方块。可在返回的构建器上继续添加有效方块及其他配置。 * - * The created [BlockEntityBuilder] is returned for further configuration. - * - * @param BE - * The type of the block entity - * @param factory - * A factory for the block entity - * @return the [BlockEntityBuilder] - */ + * @param BE 方块实体类型 + * @param factory 创建方块实体的工厂 + * @return 方块实体的 [BlockEntityBuilder] + */ open fun blockEntity(factory: BlockEntityBuilder.BlockEntityFactory) = owner.blockEntity(this, name, factory).validBlock(asSupplier()) /** @@ -214,12 +178,10 @@ open class BlockBuilder protected constructor( } /** - * Assign the default blockstate, which maps all states to a single model file (via - * [RegistrateBlockModelGenerator.createTrivialCube]). This is the default, so it is generally not - * necessary - * to call, unless for undoing previous changes. + * 使用 [RegistrateBlockModelGenerator.createTrivialCube] 生成默认方块状态,所有状态共用一个立方体模型。 + * 可再次调用以替换之前设置的生成方式。 * - * @return this [BlockBuilder] + * @return 当前构建器 */ open fun defaultBlockstate(): BlockBuilder = blockstate { NonNullBiConsumer { ctx: DataGenContext, prov: RegistrateBlockModelGenerator -> @@ -230,12 +192,11 @@ open class BlockBuilder protected constructor( } /** - * Configure the blockstate/models for this block. + * 设置此方块的方块状态和模型生成回调。 * - * @param cons - * The callback which will be invoked during data generation. - * @return this [BlockBuilder] - * @see .setData + * @param cons 提供数据生成回调的供应器 + * @return 当前构建器 + * @see setData */ open fun blockstate(cons: NonNullSupplier, RegistrateBlockModelGenerator>>): BlockBuilder { val blockstate: NonNullSupplier, RegistrateBlockModelGenerator>> = @@ -248,48 +209,36 @@ open class BlockBuilder protected constructor( } /** - * Assign the default translation, as specified by - * [RegistrateLangProvider.getAutomaticName]. This is - * the default, so it is generally - * not necessary to call, unless for undoing previous changes. + * 用 [RegistrateLangProvider.getAutomaticName] 从注册名称推导默认翻译,可用于恢复默认生成方式。 * - * @return this [BlockBuilder] + * @return 当前构建器 */ open fun defaultLang(): BlockBuilder = lang { obj: T -> obj.descriptionId } - /** Configures the source text and translations of this entry. */ + /** 使用方块的描述键声明源文本及显式译文。 */ open fun localization(configure: Consumer): BlockBuilder = localization({ obj: T -> obj.descriptionId }, configure) /** - * Set the translation for this block. + * 为此方块指定源语言名称。 * - * @param name - * A localized English name - * @return this [BlockBuilder] + * @param name 使用模组源语言书写的方块名称 + * @return 当前构建器 */ open fun lang(name: String): BlockBuilder = lang({ obj: T -> obj.descriptionId }, name) /** - * Assign the default loot table, as specified by [RegistrateBlockLootTables.dropSelf]. This is the - * default, so it is generally not necessary to call, unless for - * undoing previous changes. + * 恢复默认战利品表。方块被破坏时按 [RegistrateBlockLootTables.dropSelf] 的规则掉落自身。 * - * @return this [BlockBuilder] + * @return 当前构建器 */ open fun defaultLoot(): BlockBuilder = loot { obj: RegistrateBlockLootTables, block: T -> obj.dropSelf(block) } /** - * Configure the loot table for this block. This is different than most data gen callbacks as the callback does not - * accept a [DataGenContext], but instead a - * [RegistrateBlockLootTables], for creating specifically block loot tables. - * + * 配置方块战利品表。回调接收专用的 [RegistrateBlockLootTables] 和方块对象。 + * 方块通过 [Block.Properties.noLootTable] 禁用战利品表时,跳过该回调。 * - * If the block does not have a loot table (i.e. [Block.Properties.noLootTable] is called) this action will - * be *skipped*. - * - * @param cons - * The callback which will be invoked during block loot table creation. - * @return this [BlockBuilder] + * @param cons 生成方块战利品表时执行的回调 + * @return 当前构建器 */ open fun loot(cons: NonNullBiConsumer) = setData( ProviderType.LOOT, @@ -304,24 +253,21 @@ open class BlockBuilder protected constructor( } /** - * Configure the recipe(s) for this block. + * 设置此方块的配方生成回调。 * - * @param cons - * The callback which will be invoked during data generation. - * @return this [BlockBuilder] - * @see .setData + * @param cons 数据生成时执行的回调 + * @return 当前构建器 + * @see setData */ open fun recipe(cons: NonNullBiConsumer, RegistrateRecipeProvider>) = setData(ProviderType.RECIPE, cons) private var clientExtension: NonNullSupplier>? = null /** - * Register a client extension for this block. - * The [IClientBlockExtensions] instance can be shared across many items. + * 登记方块客户端扩展。同一个 [IClientBlockExtensions] 实例可供多个方块共用。 * - * @param clientExtension - * The client extension to register for this block - * @return this [BlockBuilder] + * @param clientExtension 外层供应器须可在服务端安全创建,内层供应器在客户端取得扩展 + * @return 当前构建器 */ open fun clientExtension(clientExtension: NonNullSupplier>): BlockBuilder { if (this.clientExtension == null) { @@ -345,55 +291,41 @@ open class BlockBuilder protected constructor( } /** - * Assign [TagKey]`s` to this block. Multiple calls will add additional tags. + * 向此方块添加标签。多次调用会累加标签。 * - * @param tags - * The tags to assign - * @return this [BlockBuilder] + * @param tags 要添加的标签键 + * @return 当前构建器 */ @SafeVarargs fun tag(vararg tags: TagKey) = tag(ProviderType.BLOCK_TAGS, *tags) + /** 应用已登记的属性变换,写入注册键,再由工厂创建方块。 */ override fun createEntry(): T { var properties = this.initialProperties.get() properties = propertiesCallback.apply(properties) return factory.apply(properties) } + /** 用方块专用引用包装延迟绑定的条目,便于获取关联方块物品。 */ override fun createEntryWrapper(delegate: DeferredHolder) = BlockEntry(owner, delegate) + /** 提交方块注册,返回可保存到静态字段的方块引用。 */ override fun register(): BlockEntry = super.register() as BlockEntry companion object { /** - * Create a new [BlockBuilder] and configure data. Used in lieu of adding side-effects to constructor, so that - * alternate initialization strategies can be done in subclasses. - * - * - * The block will be assigned the following data: - * - * * A default blockstate file mapping all states to one model (via [.defaultBlockstate]) - * * A simple cube_all model (used in the blockstate) with one texture (via [.defaultBlockstate]) - * * A self-dropping loot table (via [.defaultLoot]) - * * The default translation (via [.defaultLang]) - * + * 创建带默认数据配置的 [BlockBuilder],集中设置可由子类替换的生成规则。 + * 默认让所有方块状态共用单纹理立方体模型,生成掉落自身的战利品表和默认名称。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the block - * @return A new [BlockBuilder] with reasonable default data generators. -

*/ + * @param T 方块类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param factory 接收属性并创建方块的工厂 + * @return 配置好默认数据生成规则的构建器 + */ @JvmStatic fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: NonNullFunction) = BlockBuilder( owner, diff --git a/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt index 1036f95..a80185f 100644 --- a/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt @@ -20,7 +20,6 @@ import net.minecraft.world.level.block.entity.BlockEntityType import net.minecraft.world.level.block.state.BlockState import net.neoforged.api.distmarker.Dist import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent -import net.neoforged.neoforge.capabilities.Capabilities import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent import net.neoforged.neoforge.registries.DeferredHolder @@ -29,12 +28,10 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet import java.util.function.Consumer /** - * A builder for block entities, allows for customization of the valid blocks. + * 构建和注册方块实体类型,登记可承载此类型的方块。 * - * @param T - * The type of block entity being built - * @param P - * Parent object type + * @param T 方块实体类型 + * @param P 父级对象类型 */ open class BlockEntityBuilder protected constructor( owner: AbstractRegistrate<*>, @@ -49,7 +46,15 @@ open class BlockEntityBuilder protected constructor( callback, Registries.BLOCK_ENTITY_TYPE, ) { + /** 由模组实现,用于游戏在指定位置创建方块实体实例。回调运行在发起创建的线程上。 */ fun interface BlockEntityFactory { + /** + * 创建与当前位置和方块状态对应的方块实体。 + * @param type 已注册的方块实体类型 + * @param pos 方块在世界中的位置 + * @param state 创建时的方块状态 + * @return 新的方块实体实例 + */ fun create(type: BlockEntityType, pos: BlockPos, state: BlockState): T } @@ -58,11 +63,10 @@ open class BlockEntityBuilder protected constructor( null /** - * Add a valid block for this block entity. + * 添加一个可承载此方块实体的方块。 * - * @param block - * A supplier for the block to add at registration time - * @return this [BlockEntityBuilder] + * @param block 注册时取得方块的供应器 + * @return 当前构建器 */ open fun validBlock(block: NonNullSupplier): BlockEntityBuilder { validBlocks.add(block) @@ -70,11 +74,10 @@ open class BlockEntityBuilder protected constructor( } /** - * Add valid blocks for this block entity. + * 添加多个可承载此方块实体的方块。 * - * @param blocks - * An array of suppliers for the block to add at registration time - * @return this [BlockEntityBuilder] + * @param blocks 注册时取得各个方块的供应器 + * @return 当前构建器 */ @SafeVarargs fun validBlocks(vararg blocks: NonNullSupplier): BlockEntityBuilder { @@ -83,17 +86,10 @@ open class BlockEntityBuilder protected constructor( } /** - * Register an [BlockEntityRenderer] for this block entity. - * - * + * 为此方块实体类型登记客户端渲染器。 * - * @apiNote This requires the [Class] of the block entity object, which can only be gotten by inspecting an - * instance of it. Thus, the entity will be constructed to register the renderer. - * - * @param renderer - * A (server safe) supplier to an [Function] that will provide this block entity's renderer - * given the renderer dispatcher - * @return this [BlockEntityBuilder] + * @param renderer 外层供应器须可在服务端安全创建,内层工厂在客户端接收渲染上下文并创建渲染器 + * @return 当前构建器 */ open fun renderer(renderer: NonNullSupplier>>): BlockEntityBuilder { if (this.renderer == null) { // First call only @@ -122,10 +118,10 @@ open class BlockEntityBuilder protected constructor( } /** - * Register [Capabilities] for this block entity. + * 在能力注册事件中为此方块实体登记能力。 * - * @param registerCapabilitiesEvent A consumer for the register capabilities event - * @return this [BlockEntityBuilder] + * @param registerCapabilitiesEvent 接收能力注册事件的回调 + * @return 当前构建器 */ open fun registerCapability(registerCapabilitiesEvent: Consumer): BlockEntityBuilder { addModListener( @@ -136,6 +132,7 @@ open class BlockEntityBuilder protected constructor( return this } + /** 在注册时收集有效方块,并将实例工厂与新类型绑定。 */ override fun createEntry(): BlockEntityType { val factory: BlockEntityFactory = this.factory val supplier: NonNullSupplier> = asSupplier() @@ -144,34 +141,25 @@ open class BlockEntityBuilder protected constructor( return BlockEntityType.Builder.of({ pos, state -> factory.create(supplier.get(), pos, state) }, *valid).build(null) } + /** 用方块实体类型的专用引用包装延迟绑定的条目。 */ override fun createEntryWrapper(delegate: DeferredHolder, BlockEntityType>) = BlockEntityEntry(owner, delegate) + /** 提交方块实体类型注册,返回用于创建或查询实例的类型引用。 */ override fun register(): BlockEntityEntry = super.register() as BlockEntityEntry companion object { /** - * Create a new [BlockEntityBuilder] and configure data. Used in lieu of adding side-effects to constructor, - * so that alternate initialization strategies can be done in subclasses. - * - * - * The block entity will be assigned the following data: + * 创建 [BlockEntityBuilder],供子类在此入口附加初始化配置。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the block entity - * @return A new [BlockEntityBuilder] with reasonable default data generators. -

*/ + * @param T 方块实体类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param factory 创建方块实体的工厂 + * @return 新的方块实体构建器 + */ @JvmStatic fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: BlockEntityFactory) = BlockEntityBuilder(owner, parent, name, callback, factory) diff --git a/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt index 5406e27..e71c800 100644 --- a/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt @@ -1,4 +1,4 @@ -// Keep the Java overload signatures while formatting the Kotlin declarations. +// 格式化 Kotlin 声明时保留与 Java 调用方对应的重载签名。 @file:Suppress("ktlint:standard:max-line-length") package com.modularmc.registrate.builders @@ -42,13 +42,10 @@ import java.util.function.Consumer import java.util.function.Supplier /** - * A builder for entities, allows for customization of the [EntityType.Builder], easy creation of spawn egg items, - * and configuration of data associated with entities (loot tables, etc.). + * 构建和注册实体类型,可配置原版实体属性、刷怪蛋和实体战利品等数据。 * - * @param T - * The type of entity being built - * @param P - * Parent object type + * @param T 实体类型 + * @param P 父级对象类型 */ open class EntityBuilder protected constructor( owner: AbstractRegistrate<*>, @@ -76,13 +73,10 @@ open class EntityBuilder protected constructor( private var spawnConfigured = false /** - * Modify the properties of the entity. Modifications are done lazily, but the passed function is composed with the - * current one, and as such this method can be called multiple times to perform - * different operations. + * 登记实体类型属性变换。创建实体类型时按登记顺序应用各次变换。 * - * @param cons - * The action to perform on the properties - * @return this [EntityBuilder] + * @param cons 配置原版实体类型构建器的回调 + * @return 当前构建器 */ open fun properties(cons: NonNullConsumer>): EntityBuilder { builderCallback = builderCallback.andThen(cons) @@ -90,14 +84,10 @@ open class EntityBuilder protected constructor( } /** - * Register an [EntityRenderer] for this entity. + * 登记此类型的实体渲染器,供客户端渲染事件调用。 * - * - * - * @param renderer - * A (server safe) supplier to an [EntityRendererProvider] that will provide this entity's - * renderer - * @return this [EntityBuilder] + * @param renderer 外层供应器须可在服务端安全创建,内层工厂在客户端接收渲染上下文并创建渲染器 + * @return 当前构建器 */ open fun renderer(renderer: NonNullSupplier>>): EntityBuilder { if (this.renderer == null) { @@ -127,17 +117,11 @@ open class EntityBuilder protected constructor( } /** - * Register a attributes for this entity. The entity must extend [LivingEntity]. - * + * 为 [LivingEntity] 类型登记属性。每个构建器只能设置一次。 * - * Cannot be called more than once per builder. - * - * @param attributes - * A supplier to the attributes for this entity, usually of the form - * `EntityClass::createAttributes` - * @return this [EntityBuilder] - * @throws IllegalStateException - * When called more than once + * @param attributes 用于创建属性的供应器,通常为实体类的静态方法引用 + * @return 当前构建器 + * @throws IllegalStateException 已登记过实体属性 */ open fun attributes(attributes: Supplier): EntityBuilder { check(!attributesConfigured) { "Cannot configure attributes more than once" } @@ -156,21 +140,13 @@ open class EntityBuilder protected constructor( } /** - * Register a spawn placement for this entity. The entity must extend [Mob] and allow construction with a - * `null` [net.minecraft.world.level.Level]. - * - * - * Cannot be called more than once per builder. + * 为 [Mob] 类型登记生成位置规则。每个构建器只能设置一次。 * - * @param type - * The type of placement to use - * @param heightmap - * Which heightmap to use to choose placement locations - * @param predicate - * A predicate to check spawn locations for validity - * @return this [EntityBuilder] - * @throws IllegalStateException - * When called more than once + * @param type 生成位置类型 + * @param heightmap 用于查询候选生成位置的高度图 + * @param predicate 判断候选位置能否生成该实体的条件 + * @return 当前构建器 + * @throws IllegalStateException 已登记过生成位置规则 */ open fun spawnPlacement( type: SpawnPlacementType, @@ -194,7 +170,7 @@ open class EntityBuilder protected constructor( return this } - /** Registers a spawn egg using the given customization callback and standard model. */ + /** 为此实体登记刷怪蛋,可通过回调继续配置其物品构建器。 */ @JvmOverloads open fun spawnEgg(consumer: NonNullConsumer>> = NonNullConsumer.noop()): EntityBuilder = spawnEgg(0xFFFFFF, 0xFFFFFF, consumer) @@ -231,35 +207,26 @@ open class EntityBuilder protected constructor( } /** - * Assign the default translation, as specified by - * [com.modularmc.registrate.providers.RegistrateLangProvider.getAutomaticName]. This is - * the default, so it is generally - * not necessary to call, unless for undoing previous changes. - * - * @return this [EntityBuilder] + * 从注册名称推导默认实体名称。可再次调用以恢复默认翻译。 */ open fun defaultLang(): EntityBuilder = lang { obj: EntityType -> obj.descriptionId } - /** Configures the source text and translations of this entry. */ + /** 使用实体类型的描述键声明源文本及显式译文。 */ open fun localization(configure: Consumer): EntityBuilder = localization({ obj: EntityType -> obj.descriptionId }, configure) /** - * Set the translation for this entity. + * 为此实体指定源语言名称。 * - * @param name - * A localized English name - * @return this [EntityBuilder] + * @param name 使用模组源语言书写的实体名称 + * @return 当前构建器 */ open fun lang(name: String): EntityBuilder = lang({ obj: EntityType -> obj.descriptionId }, name) /** - * Configure the loot table for this entity. This is different than most data gen callbacks as the callback does not - * accept a [DataGenContext], but instead a - * [RegistrateEntityLootTables], for creating specifically entity loot tables. + * 设置实体战利品表。回调接收 [RegistrateEntityLootTables] 和实体类型。 * - * @param cons - * The callback which will be invoked during entity loot table creation. - * @return this [EntityBuilder] + * @param cons 生成实体战利品表时执行的回调 + * @return 当前构建器 */ open fun loot(cons: NonNullBiConsumer>) = setData( ProviderType.LOOT, @@ -270,54 +237,41 @@ open class EntityBuilder protected constructor( } /** - * Assign [TagKey]`s` to this entity. Multiple calls will add additional tags. + * 向此实体类型添加标签。多次调用会累加标签。 * - * @param tags - * The tags to assign - * @return this [EntityBuilder] + * @param tags 要添加的标签键 + * @return 当前构建器 */ @SafeVarargs fun tag(vararg tags: TagKey>) = tag(ProviderType.ENTITY_TAGS, *tags) + /** 将构建回调应用到原版构建器,再使用当前注册键创建实体类型。 */ override fun createEntry(): EntityType { val builder: EntityType.Builder = this.builder.get() builderCallback.accept(builder) return builder.build(resourceKey.location().toString()) } + /** 用实体类型专用引用包装延迟绑定的条目。 */ override fun createEntryWrapper(delegate: DeferredHolder, EntityType>) = EntityEntry(owner, delegate) + /** 提交实体类型注册,返回供后续生成和查询实体使用的引用。 */ override fun register(): EntityEntry = super.register() as EntityEntry companion object { /** - * Create a new [EntityBuilder] and configure data. Used in lieu of adding side-effects to constructor, so - * that alternate initialization strategies can be done in subclasses. - * - * - * The entity will be assigned the following data: - * - * * The default translation (via [.defaultLang]) - * + * 创建 [EntityBuilder] 并配置默认翻译。子类可在此入口扩展初始化。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the entity - * @param classification - * The [MobCategory] of the entity - * @return A new [EntityBuilder] with reasonable default data generators. -

*/ + * @param T 实体类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param factory 创建实体的工厂 + * @param classification 实体的 [MobCategory] + * @return 配置好默认翻译的实体构建器 + */ @JvmStatic fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: EntityFactory, classification: MobCategory) = EntityBuilder(owner, parent, name, callback, factory, classification) diff --git a/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt index 6c85eed..77f5387 100644 --- a/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt @@ -1,4 +1,4 @@ -@file:Suppress("ktlint:standard:max-line-length") // Spotless reports a line-length violation at the file header during formatting. +@file:Suppress("ktlint:standard:max-line-length") // Spotless 格式化时会在文件头报告行宽超限。 package com.modularmc.registrate.builders @@ -49,12 +49,17 @@ import java.util.function.Consumer import java.util.function.Supplier import java.util.function.ToIntFunction +/** 配置流体类型、源流体和流动流体的注册,并可附带方块、桶及客户端模型。 */ open class FluidBuilder : AbstractBuilder> { + /** 由模组提供,用于在注册阶段按配置创建一个新的 NeoForge 流体类型。 */ fun interface FluidTypeFactory { + /** 以配置完成的 [properties] 创建流体类型,返回供源流体与流动流体共享的实例。 */ fun create(properties: FluidType.Properties): FluidType } + /** 由模组提供,用于在流体注册阶段创建具体的流动流体。 */ fun interface FluidFactory { + /** 用已配置的 [properties] 创建流动流体。属性中引用的附属条目由注册流程延迟取得。 */ fun create(properties: BaseFlowingFluid.Properties): T } @@ -67,8 +72,8 @@ open class FluidBuilder : AbstractBuilder>): FluidBuilder { if (this.clientExtension == null && !(registerType && textures != null)) { @@ -133,6 +138,7 @@ open class FluidBuilder : AbstractBuilder private val tags = ObjectOpenHashSet>() + /** 创建会同时注册新流体类型的流体构建器。实际类型由 [typeFactory] 延迟创建。 */ constructor( owner: AbstractRegistrate<*>, parent: P, @@ -148,6 +154,7 @@ open class FluidBuilder : AbstractBuilder, parent: P, @@ -160,17 +167,14 @@ open class FluidBuilder : AbstractBuilder): FluidBuilder { typeProperties = typeProperties.andThen(cons) @@ -178,13 +182,10 @@ open class FluidBuilder : AbstractBuilder): FluidBuilder { fluidProperties = fluidProperties.andThen(cons) @@ -200,26 +201,23 @@ open class FluidBuilder : AbstractBuilder = defaultLang({ f: T -> f.fluidType.descriptionId }, sourceName) - /** Configures the source text and translations of this entry. */ + /** 使用流体类型的描述键声明源文本及显式译文。 */ open fun localization(configure: Consumer): FluidBuilder = localization({ fluid: T -> fluid.fluidType.descriptionId }, configure) /** - * Set the translation for this fluid. + * 为此流体指定源语言名称。 * - * @param name - * A localized English name - * @return this [FluidBuilder] + * @param name 使用模组源语言书写的流体名称 + * @return 当前构建器 */ open fun lang(name: String): FluidBuilder = lang({ f: T -> f.fluidType.descriptionId }, name) /** - * Create a standard [BaseFlowingFluid.Source] for this fluid which will be built and registered along with - * this fluid. + * 为此流体配置标准 [BaseFlowingFluid.Source],随流动流体一起构建和登记。 * - * @return this [FluidBuilder] - * @see .source - * @throws IllegalStateException - * If [source] has been called before this method + * @return 当前构建器 + * @see source + * @throws IllegalStateException 已配置过源流体 */ open fun defaultSource(): FluidBuilder { check(this.defaultSource == null) { "Cannot set a default source after a custom source has been created" } @@ -228,12 +226,10 @@ open class FluidBuilder : AbstractBuilder): FluidBuilder { this.defaultSource = false @@ -242,14 +238,10 @@ open class FluidBuilder : AbstractBuilder { check(this.defaultBlock == null) { "Cannot set a default block after a custom block has been created" } @@ -258,10 +250,9 @@ open class FluidBuilder : AbstractBuilder @@ -273,14 +264,11 @@ open class FluidBuilder : AbstractBuilder block(factory: NonNullBiFunction): BlockBuilder> { check(this.defaultBlock != false) { "Only one call to block/noBlock per builder allowed" } @@ -312,6 +300,7 @@ open class FluidBuilder : AbstractBuilder { check(this.defaultBlock != false) { "Only one call to block/noBlock per builder allowed" } @@ -320,14 +309,10 @@ open class FluidBuilder : AbstractBuilder { check(this.defaultBucket == null) { "Cannot set a default bucket after a custom bucket has been created" } @@ -336,10 +321,9 @@ open class FluidBuilder : AbstractBuilder @@ -351,15 +335,11 @@ open class FluidBuilder : AbstractBuilder bucket(factory: NonNullBiFunction): ItemBuilder> { check(this.defaultBucket != false) { "Only one call to bucket/noBucket per builder allowed" } @@ -383,6 +363,7 @@ open class FluidBuilder : AbstractBuilder { check(this.defaultBucket != false) { "Only one call to bucket/noBucket per builder allowed" } @@ -391,11 +372,10 @@ open class FluidBuilder : AbstractBuilder): FluidBuilder { @@ -417,11 +397,10 @@ open class FluidBuilder : AbstractBuilder): FluidBuilder { @@ -442,7 +421,7 @@ open class FluidBuilder : AbstractBuilder(sourceName, Registries.BLOCK) this.typeProperties.accept(properties) - // Use the sibling block's description ID for the default FluidType when it is already registered. + // 关联方块已注册时,默认流体类型沿用该方块的描述键。 if (block.isPresent && block.get().isBound) { properties.descriptionId(block.get().get().descriptionId) } else { @@ -457,13 +436,11 @@ open class FluidBuilder : AbstractBuilder { if (registerType) { @@ -485,26 +462,20 @@ open class FluidBuilder : AbstractBuilder } + /** 将流动流体包装为流体专用引用,供查询同组的源流体、方块和桶。 */ override fun createEntryWrapper(delegate: DeferredHolder): RegistryEntry = FluidEntry(owner, delegate) companion object { /** - * Create a new [FluidBuilder] and configure data. The created builder will use a default ([FluidType]) - * and fluid class ([BaseFlowingFluid.Flowing]). + * 创建使用默认 [FluidType] 和 [BaseFlowingFluid.Flowing] 的构建器。 * - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @return A new [FluidBuilder] with reasonable default data generators. - * @see .create -

*/ + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun

create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback) = create( owner, @@ -516,108 +487,65 @@ open class FluidBuilder : AbstractBuilder - * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param typeFactory - * A factory that creates the fluid type - * @return A new [FluidBuilder] with reasonable default data generators. - * @see .create -

*/ + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param typeFactory 创建流体类型的工厂 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun

create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, typeFactory: FluidTypeFactory): FluidBuilder = create(owner, parent, name, callback, typeFactory, ::Flowing) /** - * Create a new [FluidBuilder] and configure data. The created builder will use a default fluid class - * ([BaseFlowingFluid.Flowing]). + * 复用已注册的流体类型,流动流体采用 [BaseFlowingFluid.Flowing]。 * - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param fluidType - * An existing and registered fluid type. - * @return A new [FluidBuilder] with reasonable default data generators. - * @see .create -

*/ + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param fluidType 已注册的流体类型 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun

create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, fluidType: NonNullSupplier): FluidBuilder = create(owner, parent, name, callback, FluidTypeFactory { fluidType.get() }, ::Flowing) /** - * Create a new [FluidBuilder] and configure data. The created builder will use a default ([FluidType]) - * and fluid class ([BaseFlowingFluid.Flowing]). + * 使用默认 [FluidType],由调用方提供流动流体的工厂。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param fluidFactory - * A factory that creates the flowing fluid - * @return A new [FluidBuilder] with reasonable default data generators. -

*/ + * @param T 流体类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param fluidFactory 创建流动流体的工厂 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, fluidFactory: FluidFactory): FluidBuilder = create(owner, parent, name, callback, ::FluidType, fluidFactory) /** - * Create a new [FluidBuilder] and configure data. Used in lieu of adding side-effects to constructor, so that - * alternate initialization strategies can be done in subclasses. - * - * - * The fluid will be assigned the following data: - * - * * The default translation (via [.defaultLang]) - * * A default [source fluid][BaseFlowingFluid.Source] (via [.defaultSource]) - * * A default block for the fluid, with its own default blockstate and model that configure the particle texture - * (via [.defaultBlock]) - * * A default bucket item, that uses a simple generated item model with a texture of the same name as this fluid - * (via [.defaultBucket]) - * + * 创建 [FluidBuilder] 并安装默认配置,便于子类自定义初始化过程。 + * 默认生成源流体及其名称、带粒子纹理的液体方块模型,以及使用同名纹理的桶物品模型。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param typeFactory - * A factory that creates the fluid type - * @param fluidFactory - * A factory that creates the flowing fluid - * @return A new [FluidBuilder] with reasonable default data generators. -

*/ + * @param T 流体类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param typeFactory 创建流体类型的工厂 + * @param fluidFactory 创建流动流体的工厂 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun create( owner: AbstractRegistrate<*>, @@ -634,38 +562,19 @@ open class FluidBuilder : AbstractBuilder - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param fluidType - * An existing and registered fluid type - * @param fluidFactory - * A factory that creates the flowing fluid - * @return A new [FluidBuilder] with reasonable default data generators. -

*/ + * @param T 流体类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param fluidType 已注册并由当前流体复用的类型 + * @param fluidFactory 创建流动流体的工厂 + * @return 已配置默认数据的 [FluidBuilder] + */ @JvmStatic fun create( owner: AbstractRegistrate<*>, diff --git a/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt index 52488e9..88b0c8b 100644 --- a/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt @@ -37,13 +37,10 @@ import java.util.function.Consumer import java.util.function.Supplier /** - * A builder for items, allows for customization of the [Item.Properties] and configuration of data associated - * with items (models, recipes, etc.). + * 构建和注册物品,可配置物品属性、模型和配方等数据。 * - * @param T - * The type of item being built - * @param P - * Parent object type + * @param T 物品类型 + * @param P 父级对象类型 */ open class ItemBuilder protected constructor( owner: AbstractRegistrate<*>, @@ -60,16 +57,10 @@ open class ItemBuilder protected constructor( Maps.newLinkedHashMap, NonNullBiConsumer, CreativeModeTabModifier>>() /** - * Modify the properties of the item. Modifications are done lazily, but the passed function is composed with the - * current one, and as such this method can be called multiple times to perform - * different operations. + * 登记物品属性变换,构建物品时按登记顺序应用。变换返回另一份属性对象时,后续变换从新对象开始。 * - * - * If a different properties instance is returned, it will replace the existing one entirely. - * - * @param func - * The action to perform on the properties - * @return this [ItemBuilder] + * @param func 要应用的属性变换 + * @return 当前构建器 */ open fun properties(func: NonNullUnaryOperator): ItemBuilder { propertiesCallback = propertiesCallback.andThen(func) @@ -77,19 +68,17 @@ open class ItemBuilder protected constructor( } /** - * Replace the initial state of the item properties, without replacing or removing any modifications done via - * [properties]. + * 设置物品属性的起点,保留已通过 [properties] 登记的变换。 * - * @param properties - * A supplier to to create the initial properties - * @return this [ItemBuilder] + * @param properties 创建初始属性的供应器 + * @return 当前构建器 */ open fun initialProperties(properties: NonNullSupplier): ItemBuilder { initialProperties = properties return this } - /** Adds this item to a tab, with an optional callback to customize its display. */ + /** 将物品加入指定创造模式标签页。可选的回调控制该物品在标签页中的呈现。 */ @JvmOverloads open fun tab( tab: ResourceKey, @@ -97,17 +86,17 @@ open class ItemBuilder protected constructor( modifier.accept(item) }, ): ItemBuilder { - creativeModeTabs[tab] = modifier // Should we get the current value in the map [if one exists] and - // .andThen() the 2 together? right now we replace any consumer that - // currently exists + creativeModeTabs[tab] = modifier // 同一个标签页只保存一个回调。 + // 重复登记会替换之前的回调。 + // 如果需要组合回调,由调用方组合后登记。 return this } /** - * Removes the modifier from this builder from the given [CreativeModeTab]. + * 移除该物品对此创造模式标签页登记的回调。 * - * @param tab A [ResourceKey] representing the [CreativeModeTab] to remove the modifier from - * @return This builder + * @param tab 要移除回调的标签页键 + * @return 当前构建器 */ open fun removeTab(tab: ResourceKey): ItemBuilder { creativeModeTabs.remove(tab) @@ -115,9 +104,9 @@ open class ItemBuilder protected constructor( } /** - * Assign the default model to this item, which is simply a generated model with a single texture of the same name. + * 使用与注册名称同名的单张纹理生成默认物品模型。 * - * @return this [ItemBuilder] + * @return 当前构建器 */ open fun defaultModel(): ItemBuilder = model { NonNullBiConsumer { ctx: DataGenContext, prov: RegistrateItemModelGenerator -> @@ -156,12 +145,11 @@ open class ItemBuilder protected constructor( } /** - * Configure the model for this item. + * 设置此物品的模型生成回调。 * - * @param cons - * The callback which will be invoked during data creation - * @return this [ItemBuilder] - * @see .setData + * @param cons 提供数据生成回调的供应器 + * @return 当前构建器 + * @see setData */ open fun model(cons: NonNullSupplier, RegistrateItemModelGenerator>>): ItemBuilder { val model: NonNullSupplier, RegistrateItemModelGenerator>> = @@ -174,48 +162,43 @@ open class ItemBuilder protected constructor( } /** - * Assign the default translation, as specified by - * [RegistrateLangProvider.getAutomaticName]. This is - * the default, so it is generally - * not necessary to call, unless for undoing previous changes. + * 用 [RegistrateLangProvider.getAutomaticName] 从注册名称推导默认翻译,可用于恢复默认生成方式。 * - * @return this [ItemBuilder] + * @return 当前构建器 */ open fun defaultLang(): ItemBuilder = lang { obj: T -> obj.descriptionId } - /** Configures the source text and translations of this entry. */ + /** 使用物品的描述键声明源文本及显式译文。 */ open fun localization(configure: Consumer): ItemBuilder = localization({ obj: T -> obj.descriptionId }, configure) /** - * Set the translation for this item. + * 为此物品指定源语言名称。 * - * @param name - * A localized English name - * @return this [ItemBuilder] + * @param name 使用模组源语言书写的物品名称 + * @return 当前构建器 */ open fun lang(name: String): ItemBuilder = lang({ obj: T -> obj.descriptionId }, name) /** - * Configure the recipe(s) for this item. + * 设置此物品的配方生成回调。 * - * @param cons - * The callback which will be invoked during data generation. - * @return this [ItemBuilder] - * @see .setData + * @param cons 数据生成时执行的回调 + * @return 当前构建器 + * @see setData */ open fun recipe(cons: NonNullBiConsumer, RegistrateRecipeProvider>) = setData(ProviderType.RECIPE, cons) /** - * Add burn time for the item + * 将物品登记为熔炉燃料。 * - * @param tick time in ticks for this item to burn in furnace. + * @param tick 该物品在熔炉中燃烧的游戏刻数 */ open fun burnTime(tick: Int): ItemBuilder = dataMap(NeoForgeDataMaps.FURNACE_FUELS, FurnaceFuel(tick)) /** - * Add compost chance for the item + * 登记物品的堆肥成功概率。 * - * @param chance chance for composter to increase one level when composting this item. + * @param chance 投入一个该物品时堆肥桶增加一层的概率 */ open fun compostable(chance: Float): ItemBuilder = dataMap(NeoForgeDataMaps.COMPOSTABLES, Compostable(chance)) @@ -234,18 +217,16 @@ open class ItemBuilder protected constructor( ) } } - creativeModeTabs.clear() // this registration should only fire once, to doubly ensure this, clear the map + creativeModeTabs.clear() // 这个注册回调只需执行一次,用完即清空待处理的扩展。 }, ) } /** - * Register a client extension for this item. The [IClientItemExtensions] instance can be shared across many - * items. + * 登记物品客户端扩展。同一个 [IClientItemExtensions] 实例可供多个物品共用。 * - * @param clientExtension - * The client extension to register for this item - * @return this [ItemBuilder] + * @param clientExtension 外层供应器须可在服务端安全创建,内层供应器在客户端取得扩展 + * @return 当前构建器 */ open fun clientExtension(clientExtension: NonNullSupplier>): ItemBuilder { if (this.clientExtension == null) { @@ -269,53 +250,40 @@ open class ItemBuilder protected constructor( } /** - * Assign [TagKey]`s` to this item. Multiple calls will add additional tags. + * 向物品添加标签。多次调用会累加标签。 * - * @param tags - * The tag to assign - * @return this [ItemBuilder] + * @param tags 要添加的物品标签 + * @return 当前构建器 */ @SafeVarargs fun tag(vararg tags: TagKey) = tag(ProviderType.ITEM_TAGS, *tags) + /** 应用物品属性变换,写入注册键,再由工厂创建物品。 */ override fun createEntry(): T { var properties = this.initialProperties.get() properties = propertiesCallback.apply(properties) return factory.apply(properties) } + /** 用物品专用引用包装延迟绑定的条目。 */ override fun createEntryWrapper(delegate: DeferredHolder): RegistryEntry = ItemEntry(owner, delegate) + /** 提交物品注册,返回可用于构造物品堆叠的物品引用。 */ override fun register(): ItemEntry = super.register() as ItemEntry companion object { /** - * Create a new [ItemBuilder] and configure data. Used in lieu of adding side-effects to constructor, so that - * alternate initialization strategies can be done in subclasses. - * - * - * The item will be assigned the following data: - * - * * A simple generated model with one texture (via [.defaultModel]) - * * The default translation (via [.defaultLang]) - * + * 创建 [ItemBuilder],并配置使用单张纹理的默认物品模型及默认翻译。子类可在此入口扩展初始化。 * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning [AbstractRegistrate] object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the item - * @return A new [ItemBuilder] with reasonable default data generators. -

*/ + * @param T 物品类型 + * @param P 父级对象类型 + * @param owner 所属的 [AbstractRegistrate] 实例 + * @param parent 构建完成后返回的父级对象 + * @param name 条目名称 + * @param callback 将条目提交给所属实例的回调 + * @param factory 接收属性并创建物品的工厂 + * @return 配置好默认模型和翻译的物品构建器 + */ @JvmStatic fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: NonNullFunction) = ItemBuilder(owner, parent, name, callback, factory) diff --git a/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt b/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt index 6ff81c2..443ac20 100644 --- a/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt @@ -22,6 +22,7 @@ import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent import net.neoforged.neoforge.common.extensions.IMenuTypeExtension import net.neoforged.neoforge.registries.DeferredHolder +/** 注册菜单类型,并在客户端为该类型绑定界面。菜单实例由打开菜单的游戏流程创建。 */ open class MenuBuilder( owner: AbstractRegistrate<*>, parent: P, @@ -36,18 +37,44 @@ open class MenuBuilder( callback, Registries.MENU, ) where S : Screen, S : MenuAccess { + /** 由模组提供,适用于只用菜单类型、窗口标识和物品栏即可创建的菜单。 */ fun interface MenuFactory { + /** + * 创建本次打开操作对应的菜单。 + * @param type 已注册的菜单类型 + * @param windowId 本次打开操作分配的窗口标识 + * @param inv 打开菜单的玩家物品栏 + * @return 新的菜单实例 + */ fun create(type: MenuType, windowId: Int, inv: Inventory): T } + /** 由模组提供,在普通菜单参数之外还可读取服务端发来的打开数据。 */ fun interface ForgeMenuFactory { + /** + * 使用当前窗口和玩家物品栏创建菜单。 + * @param type 已注册的菜单类型 + * @param windowId 本次打开操作分配的窗口标识 + * @param inv 打开菜单的玩家物品栏 + * @param buffer 可用时读取服务端附加数据,未附带数据时可为 `null` + * @return 新的菜单实例 + */ fun create(type: MenuType, windowId: Int, inv: Inventory, buffer: RegistryFriendlyByteBuf?): T } + /** 在客户端打开菜单时创建对应界面,界面可以通过 [MenuAccess] 访问该菜单。 */ fun interface ScreenFactory where T : Screen, T : MenuAccess { + /** + * 为已经创建的菜单实例构造客户端界面。 + * @param menu 当前打开的菜单 + * @param inv 当前玩家的物品栏 + * @param displayName 打开菜单时提供的标题组件 + * @return 要显示的界面 + */ fun create(menu: M, inv: Inventory, displayName: Component): T } + /** 使用只接收普通菜单参数的工厂构建菜单类型。界面工厂延迟到客户端注册时获取。 */ constructor( owner: AbstractRegistrate<*>, parent: P, @@ -64,6 +91,7 @@ open class MenuBuilder( screenFactory, ) + /** 创建菜单类型。客户端还会在界面注册事件中绑定对应的界面工厂。 */ override fun createEntry(): MenuType { val supplier = asSupplier() val menu = IMenuTypeExtension.create { id, inventory, buffer -> @@ -80,7 +108,9 @@ open class MenuBuilder( return menu } + /** 用菜单专用引用包装延迟绑定的条目。 */ override fun createEntryWrapper(delegate: DeferredHolder, MenuType>): RegistryEntry, MenuType> = MenuEntry(owner, delegate) + /** 提交菜单类型注册,返回供后续打开菜单使用的引用。 */ override fun register(): MenuEntry = super.register() as MenuEntry } diff --git a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt index 905b0de..66b3307 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt @@ -30,6 +30,7 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet import java.util.function.Consumer +/** 保存条目提交前的标签、本地化及数据生成配置,供具体条目构建器复用。构建器由模组初始化线程配置。 */ abstract class AbstractBuilder>( override val owner: AbstractRegistrate<*>, override val parent: P, @@ -44,9 +45,10 @@ abstract class AbstractBuilder { val entry = callback.accept(name, registryKey, this, ::createEntry, ::createEntryWrapper) submitted = true @@ -54,10 +56,13 @@ abstract class AbstractBuilder> = dataGenerators.values + /** 返回当前构建器的本地化声明。没有声明时返回 `null`。 */ fun localization(): EntryLocalization? = localization + /** 设置或替换指定类型的生成回调。提交前暂存在构建器中,提交后更新所属 Registrate 的回调。 */ override fun setData(type: GeneratorType, cons: NonNullBiConsumer, D>): S { if (submitted) return super.setData(type, cons) if (type === ProviderType.LANG) localization = null @@ -65,6 +70,7 @@ abstract class AbstractBuilder removeData(type: GeneratorType): S { if (submitted) return super.removeData(type) if (type === ProviderType.LANG) localization = null @@ -74,8 +80,10 @@ abstract class AbstractBuilder): RegistryEntry = RegistryEntry(owner, delegate) + /** 返回可提前保存的条目取值器。调用它取值时,条目须已注册并绑定。 */ override fun asSupplier(): NonNullSupplier = safeSupplier + /** 为当前条目追加标签。生成时由 [type] 对应的提供器写入,重复的标签键会合并。 */ fun tag(type: ProviderType, vararg tags: TagKey): S where TP : TagsProvider, TP : RegistrateTagsProvider { val keys = tagsByType.getOrPut(type) { val registered = ObjectOpenHashSet>() @@ -89,6 +97,7 @@ abstract class AbstractBuilder removeTag(type: ProviderType, vararg tags: TagKey): S where TP : TagsProvider, TP : RegistrateTagsProvider { val keys = tagsByType[type] ?: return self() for (key in tags) keys.remove(key) return self() } + /** 用条目名称生成默认源文,由 [langKeyProvider] 从已绑定对象取得翻译键。 */ open fun lang(langKeyProvider: NonNullFunction): S = defaultLang(langKeyProvider, name) - open fun lang(langKeyProvider: NonNullFunction, name: String): S = localization(langKeyProvider, { LocalizationDeclaration.sourceText(name) }, Kind.DECLARED) + /** 为翻译键登记显式源文。键在生成阶段从已绑定对象读取,声明采用所属模组的默认元数据。 */ + open fun lang(langKeyProvider: NonNullFunction, name: String): S = localization( + langKeyProvider, + { LocalizationDeclaration.sourceText(name, owner.localizationDefaultValues()) }, + Kind.DECLARED, + ) protected open fun defaultLang(key: NonNullFunction, path: String): S = - localization(key, { LocalizationDeclaration.sourceText(RegistrateLangProvider.toEnglishName(path)) }, Kind.AUTOMATIC) + localization(key, { LocalizationDeclaration.sourceText(RegistrateLangProvider.toEnglishName(path), owner.localizationDefaultValues()) }, Kind.AUTOMATIC) - /** Declares text whose translation key is read from the registered object during DataGen. */ + /** 登记本地化声明。数据生成时从已绑定的注册对象解析翻译键。 */ open fun localization(key: NonNullFunction, configure: Consumer): S { - val declaration = LocalizationDeclaration.Builder().also(configure::accept).build() + val declaration = LocalizationDeclaration.Builder().also(configure::accept).build(owner.localizationDefaultValues()) return localization(key, { declaration }, Kind.DECLARED) } diff --git a/src/main/java/com/modularmc/registrate/builders/base/Builder.kt b/src/main/java/com/modularmc/registrate/builders/base/Builder.kt index fab48e6..2a3baf9 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/Builder.kt +++ b/src/main/java/com/modularmc/registrate/builders/base/Builder.kt @@ -16,50 +16,71 @@ import net.minecraft.core.Registry import net.minecraft.resources.ResourceKey import net.neoforged.neoforge.registries.datamaps.DataMapType -/** Collects entry declarations during mod setup and submits them to the owning Registrate. */ +/** + * 在模组初始化期间收集条目配置,并将其提交给所属 Registrate。 + * 提交前可继续链式配置,条目对象在延迟引用绑定后可读。 + * + * @param R 注册表中的基础类型 + * @param T 条目的具体类型 + * @param P 构建链的父级类型 + * @param S 当前构建器类型 + */ interface Builder> : NonNullSupplier> { val owner: AbstractRegistrate<*> val parent: P val name: String val registryKey: ResourceKey> - /** Submits the entry and returns its deferred holder. Each ID can be submitted once per registry. */ + /** 提交条目并返回延迟引用。同一注册表内每个资源标识只能提交一次。 */ fun register(): RegistryEntry + /** 返回已经提交给 Registrate 的条目引用。条目尚未提交时抛出 [IllegalArgumentException]。 */ override fun get(): RegistryEntry = owner.get(name, registryKey) - /** The registered object, available after its holder binds. */ + /** 读取已注册的对象。调用前须等该条目的延迟引用完成绑定。 */ val entry: T get() = get().get() + /** 返回延迟取得实际游戏对象的取值器。可在注册前保存取值器,实际取值须等待条目绑定。 */ fun asSupplier(): NonNullSupplier + /** 为当前条目设置指定类型的生成回调。重复设置会替换此前为该条目配置的同类型回调。 */ @Suppress("UNCHECKED_CAST") fun setData(type: GeneratorType, cons: NonNullBiConsumer, D>): S { owner.setDataGenerator(this, type) { cons.accept(DataGenContext.from(this), it) } return this as S } + /** 移除当前条目指定类型的生成回调。 */ @Suppress("UNCHECKED_CAST") fun removeData(type: GeneratorType): S { owner.removeDataGenerator(this, type) return this as S } + /** 为当前模组追加独立的生成回调,回调只接收匹配类型的生成器。 */ @Suppress("UNCHECKED_CAST") fun addMiscData(type: GeneratorType, cons: NonNullConsumer): S { owner.addDataGenerator(type, cons) return this as S } + /** 为当前条目的数据映射设置固定值,由数据生成阶段写出。 */ fun dataMap(type: DataMapType, value: D): S = dataMap(type) { value } + /** 在数据生成期间根据当前条目的上下文计算数据映射值。 */ fun dataMap(type: DataMapType, factory: NonNullFunction, D>): S = dataMap(type) { context, _ -> factory.apply( context, ) } + /** + * 在数据生成期间用条目信息和本轮注册表查询计算数据映射值。 + * @param type 要写入的数据映射类型 + * @param factory 接收条目上下文和注册表查询的工厂 + * @return 当前构建器 + */ @Suppress("UNCHECKED_CAST") fun dataMap(type: DataMapType, factory: NonNullBiFunction, HolderLookup.Provider, D>): S { owner.addDataGenerator(ProviderType.DATA_MAP) { provider -> @@ -69,14 +90,14 @@ interface Builder> : NonNullSup return this as S } - /** Adds a callback that runs after the object is inserted into its registry. */ + /** 添加在对象写入所属注册表后执行的回调。 */ @Suppress("UNCHECKED_CAST") fun onRegister(callback: NonNullConsumer): S { owner.addRegisterCallback(name, registryKey, callback) return this as S } - /** Runs the callback after this entry binds and the dependency registry is complete. */ + /** 当本条目已绑定且依赖的注册表完成注册后执行回调。 */ fun onRegisterAfter(dependencyType: ResourceKey>, callback: NonNullConsumer): S = onRegister { value -> if (owner.isRegistered(dependencyType)) { callback.accept(value) @@ -85,10 +106,11 @@ interface Builder> : NonNullSup } } + /** 将当前构建器交给 [func] 转换为另一个类型的构建器,并继续调用其构建链。 */ @Suppress("UNCHECKED_CAST") fun > transform(func: NonNullFunction): S2 = func.apply(this as S) - /** Registers the entry and returns the parent so the enclosing chain can continue. */ + /** 提交条目并返回父级对象,以便继续外层构建链。 */ fun build(): P { register() return parent diff --git a/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt b/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt index 74a4b44..915e82e 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt +++ b/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt @@ -8,9 +8,12 @@ import net.minecraft.core.Registry import net.minecraft.resources.ResourceKey import net.neoforged.neoforge.registries.DeferredHolder -/** Submits a completed builder to its owner during mod setup. The creator runs at registry time. */ +/** + * 接收构建完成的条目,将对象创建推迟到 NeoForge 注册阶段。 + * 所属 Registrate 在模组初始化时将此回调交给构建器。构建器配置完成后调用一次。 + */ interface BuilderCallback { - /** Queues an entry with its holder factory and returns the resulting deferred holder. */ + /** 将条目、对象工厂和引用工厂提交到待注册队列,返回该条目的延迟引用。 */ fun accept( name: String, type: ResourceKey>, @@ -19,7 +22,7 @@ interface BuilderCallback { entryFactory: NonNullFunction, out RegistryEntry>, ): RegistryEntry - /** Queues an entry using the default holder wrapper for its registry. */ + /** 用目标注册表的默认引用类型提交条目。 */ fun accept(name: String, type: ResourceKey>, builder: Builder, factory: NonNullSupplier): RegistryEntry = accept(name, type, builder, factory) { RegistryEntry(builder.owner, it) } } diff --git a/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt b/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt index 234e49c..cfed634 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt @@ -6,6 +6,7 @@ import com.modularmc.registrate.util.nullness.NonNullSupplier import net.minecraft.core.Registry import net.minecraft.resources.ResourceKey +/** 供没有专用构建器的条目使用。在通用注册、标签和数据生成配置之外,由工厂负责创建对象。 */ open class NoConfigBuilder( owner: AbstractRegistrate<*>, parent: P, @@ -14,5 +15,6 @@ open class NoConfigBuilder( registryType: ResourceKey>, private val factory: NonNullSupplier, ) : AbstractBuilder>(owner, parent, name, callback, registryType) { + /** 在注册时调用传入的条目工厂。 */ override fun createEntry(): T = factory.get() } diff --git a/src/main/java/com/modularmc/registrate/builders/base/package-info.java b/src/main/java/com/modularmc/registrate/builders/base/package-info.java index 3240767..bca52e2 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/package-info.java +++ b/src/main/java/com/modularmc/registrate/builders/base/package-info.java @@ -1,5 +1,5 @@ /** - * Base builder contracts and shared builder implementation scaffolding. + * 声明构建器的公共契约,以及各类构建器共用的基础逻辑。 */ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.builders.base; diff --git a/src/main/java/com/modularmc/registrate/builders/package-info.java b/src/main/java/com/modularmc/registrate/builders/package-info.java index fde0603..3cb4b69 100644 --- a/src/main/java/com/modularmc/registrate/builders/package-info.java +++ b/src/main/java/com/modularmc/registrate/builders/package-info.java @@ -1,10 +1,9 @@ /** - * Fluent concrete builder APIs for registering content. + * 提供物品、方块、实体等具体类型的链式注册入口。 * *

- * These classes form the primary downstream-facing DSL. Shared builder - * contracts and scaffolding live in {@code com.modularmc.registrate.builders.base}, - * while this package focuses on content-specific registration behavior. + * 这些构建器负责各类条目的注册规则和默认配置。共用契约与基础逻辑位于 {@code com.modularmc.registrate.builders.base}。 + *

*/ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.builders; diff --git a/src/main/java/com/modularmc/registrate/difficulty/DifficultyLevel.java b/src/main/java/com/modularmc/registrate/difficulty/DifficultyLevel.java new file mode 100644 index 0000000..d7f67d9 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/difficulty/DifficultyLevel.java @@ -0,0 +1,22 @@ +package com.modularmc.registrate.difficulty; + +import net.minecraft.util.StringRepresentable; + +import org.jspecify.annotations.NullMarked; + +/** + * 由模组的难度枚举实现,供配置按稳定标识选择档位。 + * 调用方保存 {@link #getSerializedName()} 返回的标识,枚举常量改名或调整顺序后仍可沿用已有配置。 + * 同一枚举中的档位标识必须唯一,枚举常量初始化后可从任意线程读取。 + */ +@NullMarked +public interface DifficultyLevel extends StringRepresentable { + + /** + * 返回当前档位在配置中使用的标识。 + * + * @return 非空白且在枚举常量初始化后保持固定的标识 + */ + @Override + String getSerializedName(); +} diff --git a/src/main/java/com/modularmc/registrate/difficulty/DifficultyValues.java b/src/main/java/com/modularmc/registrate/difficulty/DifficultyValues.java new file mode 100644 index 0000000..b16f5b1 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/difficulty/DifficultyValues.java @@ -0,0 +1,71 @@ +package com.modularmc.registrate.difficulty; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import org.jspecify.annotations.NullMarked; + +import java.util.EnumMap; +import java.util.Map; + +/** + * 将配置里的档位标识解析为枚举常量,再按该常量取出业务参数。 + * 建表后可供多线程查询。表中保存参数对象的引用,可变对象的线程安全由调用方负责。 + * + * @param 模组声明的难度枚举 + * @param 各档共用的参数类型 + */ +@NullMarked +public final class DifficultyValues & DifficultyLevel, V> { + + private final Object2ObjectLinkedOpenHashMap levelsById; + private final EnumMap valuesByLevel; + + /** + * 复制档位与取值的映射。多个档位可以引用同一份值。 + * + * @param levels 至少两个档位,通常由枚举的 {@code values()} 提供 + * @param values 每个已声明档位对应的非空值 + * @throws IllegalArgumentException 档位不足两个、标识为空白或重复, + * 或缺少某个档位的值 + */ + public DifficultyValues(D[] levels, Map values) { + if (levels.length < 2) throw new IllegalArgumentException("At least two difficulty levels are required"); + + levelsById = new Object2ObjectLinkedOpenHashMap<>(levels.length); + valuesByLevel = new EnumMap<>(levels[0].getDeclaringClass()); + for (D level : levels) { + String id = level.getSerializedName(); + if (id.isBlank()) throw new IllegalArgumentException("A difficulty ID is required for " + level.name()); + if (levelsById.putIfAbsent(id, level) != null) throw new IllegalArgumentException("Duplicate difficulty ID '" + id + "'"); + + V value = values.get(level); + if (value == null) throw new IllegalArgumentException("Missing value for difficulty '" + id + "'"); + valuesByLevel.put(level, value); + } + } + + /** + * 按配置中的标识查找档位,区分大小写。 + * + * @param id 从配置读取的档位标识 + * @return 与标识对应的枚举常量 + * @throws IllegalArgumentException 标识未声明,异常信息按声明顺序列出可用标识 + */ + public D level(String id) { + D level = levelsById.get(id); + if (level == null) throw new IllegalArgumentException("Unknown difficulty '" + id + "'. Available IDs " + levelsById.keySet()); + return level; + } + + /** + * 取得所选档位的值,供机器初始化或提示文本使用。 + * + * @param level 选中的难度档位 + * @return 建表时为该档位提供的值 + * @throws IllegalArgumentException 建表时未声明该档位 + */ + public V value(D level) { + V value = valuesByLevel.get(level); + if (value == null) throw new IllegalArgumentException("Undeclared difficulty '" + level.getSerializedName() + "'"); + return value; + } +} diff --git a/src/main/java/com/modularmc/registrate/export/RegistrateExportBuilder.kt b/src/main/java/com/modularmc/registrate/export/RegistrateExportBuilder.kt new file mode 100644 index 0000000..a00e635 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/export/RegistrateExportBuilder.kt @@ -0,0 +1,10 @@ +package com.modularmc.registrate.export + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.localization.export.LocalizationExportBuilder + +/** 提供当前 Registrate 实例的数据导出入口。 */ +class RegistrateExportBuilder internal constructor(private val registrate: AbstractRegistrate<*>) { + /** 配置所属模组的本地化交换文件。 */ + fun localization(): LocalizationExportBuilder = LocalizationExportBuilder(registrate) +} diff --git a/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt index baff357..bb0982c 100644 --- a/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt +++ b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt @@ -22,6 +22,7 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet import java.util.Optional import java.util.function.BiConsumer +/** 在同一模组内按注册表暂存条目,管理绑定阶段、条目元数据和注册回调。 */ class RegistrationTracker(private val modId: String) { private enum class Stage(val description: String) { CREATION("creation"), @@ -70,6 +71,12 @@ class RegistrationTracker(private val modId: String) { private val afterRegisterCallbacks = HashMultimap.create>, Runnable>() private val completedRegistrations = ObjectOpenHashSet>>() + /** + * 在普通优先级处理当前注册表,按提交顺序创建、写入并绑定条目。 + * @param event 当前注册表的注册事件 + * @param skipErrors 条目注册失败时是否记录异常后继续处理下一项 + * @param devEnvironment 开发环境下发现未使用的条目回调时立即抛出异常 + */ fun onRegister(event: RegisterEvent, skipErrors: Boolean, devEnvironment: Boolean) { val registry = event.registryKey if (!pendingEntryCallbacks.isEmpty) { @@ -99,12 +106,23 @@ class RegistrationTracker(private val modId: String) { } } + /** 在最低优先级标记注册表完成,并执行等待此注册表的回调。 */ fun onRegisterLate(event: RegisterEvent) { val registry = event.registryKey completedRegistrations.add(registry) for (callback in afterRegisterCallbacks.removeAll(registry)) callback.run() } + /** + * 暂存同名条目的对象工厂、引用和元数据。返回的引用要等注册事件触发后才绑定。 + * @param name 当前模组命名空间下的条目名称 + * @param registry 目标注册表 + * @param creator 写入注册表时调用的对象工厂 + * @param entryFactory 用延迟引用构造条目包装对象的工厂 + * @param metadata 随条目保存的数据生成回调和本地化声明 + * @return 尚未绑定的条目引用 + * @throws IllegalArgumentException 同一注册表已存在同名条目 + */ fun track( name: String, registry: ResourceKey>, @@ -127,8 +145,10 @@ class RegistrationTracker(private val modId: String) { return registration.delegate } + /** 查询指定注册键的元数据,未提交该条目时抛出 [IllegalArgumentException]。 */ fun getMetadata(key: ResourceKey<*>): EntryMetadata = registration(key.location().path, key.registryKey()).metadata + /** 在调用线程上逐一处理已声明本地化的条目,向回调传入条目引用和声明。 */ fun forEachLocalization(action: BiConsumer, EntryLocalization>) { for (row in registrations.values) { for (registration in row.values) { @@ -138,6 +158,7 @@ class RegistrationTracker(private val modId: String) { } } + /** 添加在条目注册时执行的回调。条目尚未提交时先按注册表和名称暂存。 */ fun addRegisterCallback(name: String, registry: ResourceKey>, callback: NonNullConsumer) { val entry = findRegistration(name, registry) if (entry == null) { @@ -147,17 +168,22 @@ class RegistrationTracker(private val modId: String) { } } + /** 暂存注册表完成后运行的回调。应在该注册表的注册完成事件之前调用。 */ fun addAfterRegisterCallback(registry: ResourceKey>, callback: Runnable) { afterRegisterCallbacks.put(registry, callback) } + /** 判断指定注册表是否已进入注册完成阶段。 */ fun isRegistered(registry: ResourceKey>): Boolean = registry in completedRegistrations + /** 按注册表和名称查找已提交条目的引用。缺少该条目时抛出 [IllegalArgumentException]。 */ @Suppress("UNCHECKED_CAST") fun get(name: String, registry: ResourceKey>): RegistryEntry = registration(name, registry).delegate as RegistryEntry + /** 按注册表和名称查找条目引用,没有对应条目时返回空值。 */ fun getOptional(name: String, registry: ResourceKey>): Optional> = Optional.ofNullable(findRegistration(name, registry)?.delegate) + /** 收集当前模组提交到指定注册表的引用,保留提交顺序。 */ @Suppress("UNCHECKED_CAST") fun getAll(registry: ResourceKey>): Collection> = registrations[registry]?.values?.map { it.delegate as RegistryEntry } ?: emptyList() diff --git a/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt b/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt index f740dc8..bd67208 100644 --- a/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt +++ b/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt @@ -14,9 +14,11 @@ import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Consumer +/** 将模组事件监听器限制为一次执行,并将注销安排到允许修改监听器的阶段。 */ class OneTimeEventReceiver(private val bus: IEventBus, private val listener: Consumer) : Consumer { private val consumed = AtomicBoolean() + /** 首次收到事件时调用监听器,成功返回后将自身加入注销队列。 */ override fun accept(event: T) { if (consumed.compareAndSet(false, true)) { listener.accept(event) @@ -29,11 +31,19 @@ class OneTimeEventReceiver(private val bus: IEventBus, private val li private val waitingModListeners = Reference2ObjectOpenHashMap, MutableList>>() private val toUnregister = ArrayList() + /** 以普通优先级订阅单次模组事件。实例尚未绑定事件总线时暂存监听器。 */ @JvmStatic fun addModListener(owner: AbstractRegistrate<*>, eventClass: Class, listener: Consumer) where T : Event, T : IModBusEvent { addModListener(owner, EventPriority.NORMAL, eventClass, listener) } + /** + * 以指定优先级订阅单次模组事件。已暂存的监听器在首次使用所属实例的总线时一起挂接。 + * @param owner 事件监听器所属的 Registrate 实例 + * @param priority 监听器执行优先级 + * @param eventClass 接收的模组事件类型 + * @param listener 首次收到事件时执行的回调 + */ @JvmStatic fun addModListener(owner: AbstractRegistrate<*>, priority: EventPriority, eventClass: Class, listener: Consumer) where T : Event, T : IModBusEvent { val bus = owner.modEventBus @@ -49,6 +59,7 @@ class OneTimeEventReceiver(private val bus: IEventBus, private val li addListener(bus, priority, eventClass, listener) } + /** 在模组加载完成时注销监听器。所属实例需已绑定事件总线,[event] 为保留的事件类型参数。 */ @JvmStatic @Suppress("UNUSED_PARAMETER") fun unregister(owner: AbstractRegistrate<*>, listener: Any, event: Class) { diff --git a/src/main/java/com/modularmc/registrate/internal/event/package-info.java b/src/main/java/com/modularmc/registrate/internal/event/package-info.java index be778bf..ea56a0f 100644 --- a/src/main/java/com/modularmc/registrate/internal/event/package-info.java +++ b/src/main/java/com/modularmc/registrate/internal/event/package-info.java @@ -1,6 +1,5 @@ /** - * Event-bus plumbing that supports one-shot registration hooks for the public - * Registrate DSL. + * 为 Registrate 注册接口提供一次性事件监听。 */ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.internal.event; diff --git a/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt index 005bfe4..2340929 100644 --- a/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt +++ b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt @@ -12,25 +12,33 @@ import net.neoforged.neoforge.registries.RegisterEvent import java.util.function.Consumer -/** Attaches the registration and DataGen listeners for one Registrate. */ +/** 把单个 Registrate 实例的注册和数据生成回调接入模组事件总线。 */ class RegistrateLifecycle(private val owner: AbstractRegistrate<*>, private val hooks: Hooks) { - /** Callbacks bound to their owning Registrate before NeoForge posts lifecycle events. */ + /** 定义注册、创造模式物品栏和数据生成回调。NeoForge 派发事件前,所属 Registrate 会把这些回调接入模组事件总线。 */ interface Hooks { + /** 返回绑定的模组事件总线,尚未绑定时返回 `null`。 */ fun modEventBus(): IEventBus? + /** 保存注册期间使用的模组事件总线。 */ fun setModEventBus(bus: IEventBus) + /** 返回当前启动是否正在运行数据生成,用于决定是否订阅收集数据事件。 */ fun doDatagen(): Boolean + /** 在普通优先级接收注册事件,处理当前注册表的条目。 */ fun onRegister(event: RegisterEvent) + /** 在最低优先级接收注册事件,执行等待当前注册表写入结束的操作。 */ fun onRegisterLate(event: RegisterEvent) + /** 接收创造模式标签页填充事件,为对应的标签页追加内容。 */ fun onBuildCreativeModeTabContents(event: BuildCreativeModeTabContentsEvent) + /** 接收数据收集事件,为本轮生成登记所需的提供器。 */ fun onData(event: GatherDataEvent) } + /** 在模组初始化期间挂接注册、创造模式标签页和数据生成所需的监听器。注册监听器会在公共初始化阶段排队移除。 */ fun register(bus: IEventBus) { if (hooks.modEventBus() == null) { hooks.setModEventBus(bus) diff --git a/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java b/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java index 6a752dd..db7b95b 100644 --- a/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java +++ b/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java @@ -1,6 +1,5 @@ /** - * Per-instance lifecycle bridges that attach Registrate owners to the NeoForge - * mod bus. + * 将各个 Registrate 实例接入 NeoForge 模组事件总线。 */ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.internal.lifecycle; diff --git a/src/main/java/com/modularmc/registrate/internal/package-info.java b/src/main/java/com/modularmc/registrate/internal/package-info.java index 97ad00b..40be79b 100644 --- a/src/main/java/com/modularmc/registrate/internal/package-info.java +++ b/src/main/java/com/modularmc/registrate/internal/package-info.java @@ -1,9 +1,8 @@ /** - * Internal implementation details that back the public Registrate API. + * 存放 Registrate 公共接口使用的内部实现。 * *

- * Types in this package are free to change during development and should not - * be treated as stable extension points for downstream mods. + * 此处的类型会随库的实现调整,下游模组应通过公共接口接入。 */ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.internal; diff --git a/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt b/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt index c40146b..b3ee010 100644 --- a/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt +++ b/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt @@ -3,6 +3,7 @@ package com.modularmc.registrate.internal.util import org.apache.logging.log4j.Marker import org.apache.logging.log4j.MarkerManager +/** 提供注册和数据生成日志的分类标记,便于在开发环境中按阶段筛选。 */ object DebugMarkers { private const val PREFIX = "REGISTRATE." diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt index 0d14148..d3e990b 100644 --- a/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt +++ b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt @@ -5,7 +5,9 @@ import net.neoforged.fml.loading.FMLEnvironment import java.util.function.Supplier +/** 根据 NeoForge 的物理侧执行延迟任务,供客户端类的初始化入口使用。 */ object RegistrateDistExecutor { + /** 当前物理侧与 [dist] 匹配时,才获取 [toRun] 并在调用线程执行。客户端任务的类引用应放在取值器内部。 */ @JvmStatic fun unsafeRunWhenOn(dist: Dist, toRun: Supplier) { if (dist == FMLEnvironment.dist) { diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt b/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt index 940e512..9f60231 100644 --- a/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt +++ b/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt @@ -5,24 +5,30 @@ import com.modularmc.registrate.RegistrateLib import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger +/** 集中提供 Registrate 各阶段的日志器和带模组标识的消息格式。 */ object RegistrateLogger { private val ROOT = RegistrateLib.LOGGER private val CORE = child("Core") private val DATAGEN = child("Datagen") private val REGISTRATION = child("Registration") + /** 返回本库使用的根日志器。 */ @JvmStatic fun root(): Logger = ROOT + /** 返回用于记录 Registrate 初始化和公共流程的日志器。 */ @JvmStatic fun core(): Logger = CORE + /** 返回用于记录数据生成及本地化解析的日志器。 */ @JvmStatic fun datagen(): Logger = DATAGEN + /** 返回用于记录注册提交、绑定及回调的日志器。 */ @JvmStatic fun registration(): Logger = REGISTRATION + /** 为日志消息加上模组标识占位符。调用记录方法时须将模组标识作为第一个格式化参数。 */ @JvmStatic fun modMessage(message: String): String = "[{}] $message" diff --git a/src/main/java/com/modularmc/registrate/internal/util/package-info.java b/src/main/java/com/modularmc/registrate/internal/util/package-info.java index 9def3cb..b895615 100644 --- a/src/main/java/com/modularmc/registrate/internal/util/package-info.java +++ b/src/main/java/com/modularmc/registrate/internal/util/package-info.java @@ -1,5 +1,5 @@ /** - * Small implementation-only helpers used by runtime internals. + * 存放注册流程在运行时使用的内部工具。 */ @org.jspecify.annotations.NullMarked package com.modularmc.registrate.internal.util; diff --git a/src/main/java/com/modularmc/registrate/localization/ComponentTemplate.kt b/src/main/java/com/modularmc/registrate/localization/ComponentTemplate.kt new file mode 100644 index 0000000..1a965d5 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/ComponentTemplate.kt @@ -0,0 +1,39 @@ +package com.modularmc.registrate.localization + +import net.minecraft.network.chat.Component +import net.minecraft.network.chat.Style + +import it.unimi.dsi.fastutil.objects.ObjectArrayList + +/** + * 把翻译键和样式组成可复用的文本模板,供提示框等多行文本使用。 + * 模组初始化时通过 `addLocalization` 为每行的键声明译文,显示时通过 [build] 传入实际参数。 + * + * @param lines 按显示顺序排列的文本行 + */ +class ComponentTemplate(vararg lines: Line) { + /** + * 模板中的一行,正文和说明都可以使用。 + * + * @param key 该行使用的翻译键 + * @param style 应用在该行组件上的样式 + */ + @JvmRecord + data class Line(val key: TranslationKey, val style: Style) + + private val lines = lines.copyOf() + + /** + * 为一次显示创建新的组件列表。每行可以用 `%1$s`、`%2$s` 等占位符引用同一组参数。 + * + * @param args 传给各行翻译组件的参数 + * @return 按声明顺序排列的组件列表 + */ + fun build(vararg args: Any): List { + val components = ObjectArrayList(lines.size) + for (line in lines) { + components.add(Component.translatable(line.key.value, *args).setStyle(line.style)) + } + return components + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt b/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt new file mode 100644 index 0000000..5afd6ce --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt @@ -0,0 +1,72 @@ +package com.modularmc.registrate.localization + +import com.modularmc.registrate.localization.terminology.Domain +import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTerm + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap +import it.unimi.dsi.fastutil.objects.ObjectArrayList +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet + +/** 供本地化声明复用的默认领域、文本类型、术语和单位。 */ +@JvmRecord +data class DeclarationDefaults @JvmOverloads constructor( + val domains: List, + val type: TextType?, + val glossary: List, + val glossaryIds: List = emptyList(), + val unitIds: List = emptyList(), +) { + /** + * 按字段合并默认值。显式引入的条目优先,其次使用继承值,最后使用基础默认值。 + * 多个引入项的文本类型或同标识术语发生冲突时,构建会抛出异常。 + */ + class Builder { + private var defaults = EMPTY + private var parent = EMPTY + private val included = ObjectArrayList() + + /** 设置基础默认值。仅在引入项和继承项未提供某字段时使用。 */ + fun defaults(defaults: DeclarationDefaults) = apply { this.defaults = defaults } + + /** 设置继承来源。字段没有被引入项提供时,先使用继承值再回退到基础默认值。 */ + fun inherits(parent: DeclarationDefaults) = apply { this.parent = parent } + + /** 引入一组优先级较高的默认值。多次调用会累加引入项。 */ + fun include(vararg defaults: DeclarationDefaults) = apply { included.addAll(defaults.asList()) } + + /** 合并当前配置的默认值。同标识术语或引入的文本类型发生冲突时抛出 [IllegalArgumentException]。 */ + fun build(): DeclarationDefaults { + val domains = ObjectLinkedOpenHashSet() + val glossary = Object2ObjectLinkedOpenHashMap() + val glossaryIds = ObjectLinkedOpenHashSet() + val units = ObjectLinkedOpenHashSet() + var type: TextType? = null + for (defaults in included) { + domains.addAll(defaults.domains) + glossaryIds.addAll(defaults.glossaryIds) + units.addAll(defaults.unitIds) + for (term in defaults.glossary) { + val existing = glossary.putIfAbsent(term.id, term) + require(existing == null || existing == term) { "Included defaults disagree on glossary term '${term.id}'" } + } + defaults.type?.let { candidate -> + require(type == null || type == candidate) { "Included defaults disagree on text type: ${type?.id} and ${candidate.id}" } + type = candidate + } + } + val glossaryParent = if (parent.glossary.isEmpty() && parent.glossaryIds.isEmpty()) defaults else parent + val useIncludedGlossary = glossary.isNotEmpty() || glossaryIds.isNotEmpty() + return DeclarationDefaults( + if (domains.isEmpty()) parent.domains.ifEmpty { defaults.domains } else ObjectArrayList(domains), + type ?: parent.type ?: defaults.type, + if (useIncludedGlossary) ObjectArrayList(glossary.values) else glossaryParent.glossary, + if (useIncludedGlossary) ObjectArrayList(glossaryIds) else glossaryParent.glossaryIds, + if (units.isEmpty()) parent.unitIds.ifEmpty { defaults.unitIds } else ObjectArrayList(units), + ) + } + } + + companion object { + internal val EMPTY = DeclarationDefaults(emptyList(), null, emptyList()) + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt b/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt index e73537e..49b8f99 100644 --- a/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt +++ b/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt @@ -3,6 +3,6 @@ package com.modularmc.registrate.localization import com.modularmc.registrate.localization.TranslationSource.Kind import com.modularmc.registrate.util.nullness.NonNullSupplier -/** A builder declaration whose key is obtained from the bound Minecraft object during DataGen. */ +/** 构建器保存的本地化声明。数据生成时从已绑定的游戏对象读取翻译键。 */ @JvmRecord data class EntryLocalization(val key: NonNullSupplier, val declaration: NonNullSupplier, val kind: Kind) diff --git a/src/main/java/com/modularmc/registrate/localization/ImportedTranslation.kt b/src/main/java/com/modularmc/registrate/localization/ImportedTranslation.kt new file mode 100644 index 0000000..b0e364b --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/ImportedTranslation.kt @@ -0,0 +1,43 @@ +package com.modularmc.registrate.localization + +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.util.HexFormat + +/** 标识译文审校时对应的源文版本,用于判断源文是否已变更。 */ +@JvmRecord +data class SourceRevision(val value: String) { + companion object { + private val digest = ThreadLocal.withInitial { MessageDigest.getInstance("SHA-256") } + private val hex = HexFormat.of() + + /** 按 UTF-8 编码计算源文的 SHA-256 摘要。 */ + @JvmStatic + fun of(source: String): SourceRevision = SourceRevision(hex.formatHex(digest.get().digest(source.toByteArray(StandardCharsets.UTF_8)))) + } +} + +/** 记录外部译文的审校状态,供数据生成时比较导入译文的优先级。 */ +enum class TranslationStatus(private val priority: Int) { + STALE(0), + DRAFT(1), + IN_REVIEW(2), + APPROVED(3), + ; + + internal fun priority(locked: Boolean): Int = priority + if (locked) entries.size else 0 +} + +/** 从外部导入的译文。[location] 记录来源,供数据生成时定位问题。 */ +@JvmRecord +data class ImportedTranslation( + val key: TranslationKey, + val locale: MinecraftLocale, + val text: String, + val sourceRevision: SourceRevision, + val status: TranslationStatus, + val locked: Boolean, + val location: String, +) { + internal fun forRevision(revision: SourceRevision): ImportedTranslation = if (sourceRevision == revision || status == TranslationStatus.STALE) this else copy(status = TranslationStatus.STALE) +} diff --git a/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt b/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt index 53dee17..777f318 100644 --- a/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt +++ b/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt @@ -1,47 +1,91 @@ package com.modularmc.registrate.localization import com.modularmc.registrate.localization.terminology.Domain -import com.modularmc.registrate.localization.terminology.LocalizationCatalog.GlossaryTerm +import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTerm import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap -/** A source declaration and its explicit translations, resolved against the owning mod's source locale. */ +/** 声明源文及显式提供的译文。数据生成时以所属模组的源语言解释源文。 */ @JvmRecord -data class LocalizationDeclaration(val source: String, val translations: Map, val domains: List, val type: TextType?, val glossary: List) { +data class LocalizationDeclaration @JvmOverloads constructor( + val source: String, + val translations: Map, + val domains: List, + val type: TextType?, + val glossary: List, + val glossaryIds: List = emptyList(), + val unitIds: List = emptyList(), +) { + /** 为单条本地化声明收集源文、译文及可选的术语信息。构建前须设置源文。 */ class Builder { private lateinit var source: String private var translations: Object2ObjectOpenHashMap? = null private var domains: List? = null private var type: TextType? = null private var glossary: List? = null - private var profile = LocalizationProfile.EMPTY + private var glossaryIds: List? = null + private var unitIds: List? = null + private var defaults = DeclarationDefaults.EMPTY + /** 设置源语言文本,其中的占位符应和各译文对应。 */ fun source(source: String) = apply { this.source = source } + /** 设置声明专用文本类型。传入 `null` 时沿用构建时可用的默认类型。 */ fun type(type: TextType?) = apply { this.type = type } - fun profile(profile: LocalizationProfile) = apply { this.profile = profile } + /** 设置声明级默认值。显式字段优先,缺失字段可以回退到模组默认值。 */ + fun defaults(defaults: DeclarationDefaults) = apply { this.defaults = defaults } + /** 设置指定语言的显式译文。同一语言重复设置时采用最后一次的内容。 */ fun translation(locale: MinecraftLocale, text: String) = apply { val texts = translations ?: Object2ObjectOpenHashMap(2).also { translations = it } texts[locale] = text } + /** 设置声明的领域列表。传入零个领域会清除继承的领域。 */ fun domain(vararg domains: Domain) = apply { this.domains = domains.toList() } - fun glossary(vararg terms: GlossaryTerm) = apply { glossary = terms.toList() } + /** 直接指定声明使用的术语,并替换此前指定的术语标识。 */ + fun glossary(vararg terms: GlossaryTerm) = apply { + glossary = terms.asList() + glossaryIds = emptyList() + } + + /** 按稳定标识引用已登记的术语,替换此前直接指定的术语。 */ + fun glossaryIds(vararg ids: String) = apply { + glossary = emptyList() + glossaryIds = ids.asList() + } + + /** 指定声明使用的单位标识。派生译文时可以保留这些单位的符号。 */ + fun units(vararg ids: String) = apply { unitIds = ids.asList() } - fun build() = LocalizationDeclaration( - source, - translations?.toMap() ?: emptyMap(), - domains ?: profile.domains, - type ?: profile.type, - glossary ?: profile.glossary, - ) + /** 仅使用此构建器的配置和默认值创建声明。尚未调用 [source] 时抛出 [UninitializedPropertyAccessException]。 */ + fun build(): LocalizationDeclaration = build(DeclarationDefaults.EMPTY) + + /** 创建声明,并按显式设置、声明默认值、模组默认值的顺序取各字段。尚未设置源文时抛出 [UninitializedPropertyAccessException]。 */ + fun build(moduleDefaults: DeclarationDefaults): LocalizationDeclaration { + val entryGlossary = if (defaults.glossary.isEmpty() && defaults.glossaryIds.isEmpty()) moduleDefaults else defaults + return LocalizationDeclaration( + source, + translations?.toMap() ?: emptyMap(), + domains ?: defaults.domains.ifEmpty { moduleDefaults.domains }, + type ?: defaults.type ?: moduleDefaults.type, + glossary ?: entryGlossary.glossary, + glossaryIds ?: entryGlossary.glossaryIds, + unitIds ?: defaults.unitIds.ifEmpty { moduleDefaults.unitIds }, + ) + } } companion object { + /** 创建仅含源文的声明,供没有单独配置译文、术语或单位的条目使用。 */ @JvmStatic fun sourceText(source: String) = LocalizationDeclaration(source, emptyMap(), emptyList(), null, emptyList()) + + /** 用源文和指定的默认元数据创建声明。目标语言可在数据生成期间由导入或派生规则提供。 */ + @JvmStatic + fun sourceText(source: String, defaults: DeclarationDefaults) = + LocalizationDeclaration(source, emptyMap(), defaults.domains, defaults.type, defaults.glossary, defaults.glossaryIds, defaults.unitIds) } } diff --git a/src/main/java/com/modularmc/registrate/localization/LocalizationProfile.kt b/src/main/java/com/modularmc/registrate/localization/LocalizationProfile.kt deleted file mode 100644 index c594239..0000000 --- a/src/main/java/com/modularmc/registrate/localization/LocalizationProfile.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.modularmc.registrate.localization - -import com.modularmc.registrate.localization.terminology.Domain -import com.modularmc.registrate.localization.terminology.LocalizationCatalog.GlossaryTerm - -/** Reusable domain, text type and glossary defaults for a localization declaration. */ -@JvmRecord -data class LocalizationProfile(val domains: List, val type: TextType?, val glossary: List) { - companion object { - internal val EMPTY = LocalizationProfile(emptyList(), null, emptyList()) - } -} diff --git a/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt b/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt index d3c18ef..0f75396 100644 --- a/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt +++ b/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization -/** Languages shipped with Minecraft 1.21.1. */ +/** Minecraft 提供的语言选项。 */ enum class MinecraftLocale { AF_ZA, AR_SA, @@ -143,5 +143,6 @@ enum class MinecraftLocale { private val code = name.lowercase() + /** 返回形如 `zh_cn` 的语言文件代码。 */ fun code(): String = code } diff --git a/src/main/java/com/modularmc/registrate/localization/TextType.kt b/src/main/java/com/modularmc/registrate/localization/TextType.kt index 9568003..0a1b57b 100644 --- a/src/main/java/com/modularmc/registrate/localization/TextType.kt +++ b/src/main/java/com/modularmc/registrate/localization/TextType.kt @@ -1,19 +1,35 @@ package com.modularmc.registrate.localization -/** The role of a piece of text in the mod. */ -enum class TextType { - ITEM, - BLOCK, - MACHINE, - MATERIAL, - PROCESS, - REACTION, - PHENOMENON, - ASTRONOMICAL_OBJECT, - BIOME, - RESEARCH, - STATISTIC, - DESCRIPTION, - TOOLTIP, - GUI_LABEL, +/** 标识文本在模组中的用途,模组可以定义自己的类型。 */ +@JvmRecord +data class TextType(val id: String) { + companion object { + @JvmField val ITEM = TextType("item") + + @JvmField val BLOCK = TextType("block") + + @JvmField val MACHINE = TextType("machine") + + @JvmField val MATERIAL = TextType("material") + + @JvmField val PROCESS = TextType("process") + + @JvmField val REACTION = TextType("reaction") + + @JvmField val PHENOMENON = TextType("phenomenon") + + @JvmField val ASTRONOMICAL_OBJECT = TextType("astronomical_object") + + @JvmField val BIOME = TextType("biome") + + @JvmField val RESEARCH = TextType("research") + + @JvmField val STATISTIC = TextType("statistic") + + @JvmField val DESCRIPTION = TextType("description") + + @JvmField val TOOLTIP = TextType("tooltip") + + @JvmField val GUI_LABEL = TextType("gui_label") + } } diff --git a/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt b/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt index 4b5ab9d..9c95490 100644 --- a/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt +++ b/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt @@ -1,5 +1,5 @@ package com.modularmc.registrate.localization -/** The literal Minecraft translation key and the namespace of the language file that owns it. */ +/** 由 Minecraft 使用的原始翻译键和负责输出它的语言文件命名空间组成。 */ @JvmRecord data class TranslationKey(val namespace: String, val value: String) diff --git a/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt b/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt index c062c7c..7f7ee43 100644 --- a/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt +++ b/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt @@ -1,10 +1,15 @@ package com.modularmc.registrate.localization -/** Identifies a translation's priority and the declaration that supplied it. */ +/** 记录译文的来源声明及其优先级,供数据生成时选择译文。 */ @JvmRecord data class TranslationSource(val kind: Kind, val location: String) { - enum class Kind { - AUTOMATIC, - DECLARED, + /** 区分译文来源。数据生成时将来源优先级用于比较同一个键和语言的候选文本。 */ + enum class Kind(internal val priority: Int) { + FALLBACK(0), + VARIANT(1), + AUTOMATIC(2), + GLOSSARY(3), + IMPORTED(4), + DECLARED(5), } } diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/AnnotatedTranslations.kt b/src/main/java/com/modularmc/registrate/localization/annotation/AnnotatedTranslations.kt new file mode 100644 index 0000000..ef64b95 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/annotation/AnnotatedTranslations.kt @@ -0,0 +1,88 @@ +package com.modularmc.registrate.localization.annotation + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource +import com.modularmc.registrate.localization.TranslationSource.Kind.DECLARED +import com.modularmc.registrate.localization.resolution.TranslationRegistry + +import net.neoforged.fml.ModList +import net.neoforged.fml.loading.modscan.ModAnnotation.EnumHolder +import net.neoforged.neoforgespi.language.ModFileScanData.AnnotationData + +import org.objectweb.asm.Type + +import java.lang.annotation.ElementType +import java.util.EnumMap + +/** 数据生成时从所属模组文件的 NeoForge 扫描结果中读取本地化声明。 */ +internal object AnnotatedTranslations { + private val trans = Type.getType(Trans::class.java) + private val transVariants = Type.getType(TransVariants::class.java) + + fun collect(owner: AbstractRegistrate<*>, locale: MinecraftLocale, registry: TranslationRegistry) { + val modId = owner.modid + val defaults = owner.localizationDefaultValues() + val terminology = owner.terminology() + val modFile = ModList.get().getModFileById(modId) + val singleModFile = modFile.mods.size == 1 + + fun add(namespace: String, key: String, values: Map<*, *>, location: String) { + val declaration = LocalizationDeclaration( + values["source"] as String, + translations(values), + defaults.domains, + defaults.type, + defaults.glossary, + defaults.glossaryIds, + defaults.unitIds, + ) + registry.add(TranslationKey(namespace, key), locale, declaration, TranslationSource(DECLARED, location), terminology) + } + + for (annotation in modFile.file.scanResult.annotations) { + val type = annotation.annotationType() + if (type != trans && type != transVariants) continue + val values = annotation.annotationData() + val declaredModId = values["modId"] as String? + if (declaredModId.isNullOrEmpty()) { + check(singleModFile) { "${annotation.location()} must declare modId because its file contains multiple mods" } + } else if (declaredModId != modId) { + continue + } + + val namespace = (values["namespace"] as String?).orEmpty().ifEmpty { modId } + val location = annotation.location() + if (type == trans) { + add(namespace, values["key"] as String, values, "@Trans $location") + } else { + val keyPrefix = values["keyPrefix"] as String + val prefix = if (keyPrefix.endsWith('.')) keyPrefix else "$keyPrefix." + for (variant in values["value"] as List<*>) { + variant as Map<*, *> + val id = variant["id"] as String + add(namespace, "$prefix$id", variant, "@TransVariants $location [$id]") + } + } + } + } + + private fun AnnotationData.location(): String { + val className = clazz().className + return if (targetType() == ElementType.FIELD) "$className#${memberName()}" else className + } + + private fun translations(values: Map<*, *>): Map { + val translations = values["translations"] as List<*>? + if (translations.isNullOrEmpty()) return emptyMap() + val texts = EnumMap(MinecraftLocale::class.java) + for (translation in translations) { + translation as Map<*, *> + val locale = MinecraftLocale.valueOf((translation["locale"] as EnumHolder).value()) + texts[locale] = translation["text"] as String + } + return texts + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt b/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt index ed42984..50d84cb 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization.annotation -/** Adds one translation key to the named mod's language declarations. */ +/** 声明一个翻译键。模组文件只声明一个模组时,可以省略 [modId]。 */ @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS, AnnotationTarget.FIELD) -annotation class Trans(val modId: String, val key: String, val source: String, val namespace: String = "", val translations: Array = []) +annotation class Trans(val modId: String = "", val key: String, val source: String, val namespace: String = "", val translations: Array = []) diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt b/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt index 1be3f31..821a104 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization.annotation -/** Adds a translation for each variant under the given key prefix. */ +/** 为每个变体声明翻译键。模组文件只声明一个模组时,可以省略 [modId]。 */ @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS, AnnotationTarget.FIELD) -annotation class TransVariants(val modId: String, val keyPrefix: String, val value: Array, val namespace: String = "") +annotation class TransVariants(val modId: String = "", val keyPrefix: String, val value: Array, val namespace: String = "") diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt b/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt index 6ac0d1f..c77aff9 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt @@ -2,7 +2,7 @@ package com.modularmc.registrate.localization.annotation import com.modularmc.registrate.localization.MinecraftLocale -/** Explicit target text supplied by an annotated declaration. */ +/** 为注解声明提供指定语言的译文。 */ @Retention(AnnotationRetention.BINARY) @Target() annotation class Translation(val locale: MinecraftLocale, val text: String) diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt b/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt index 38fa23e..9dff07e 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization.annotation -/** One entry of a variant group, appended to the group's key prefix. */ +/** 变体组中的一条声明。该变体的键后缀接到组的公共前缀后。 */ @Retention(AnnotationRetention.BINARY) @Target() annotation class Variant(val id: String, val source: String, val translations: Array = []) diff --git a/src/main/java/com/modularmc/registrate/localization/export/LocalizationDocument.kt b/src/main/java/com/modularmc/registrate/localization/export/LocalizationDocument.kt new file mode 100644 index 0000000..c102ff3 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/export/LocalizationDocument.kt @@ -0,0 +1,24 @@ +package com.modularmc.registrate.localization.export + +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource + +import it.unimi.dsi.fastutil.ints.Int2IntMap +import it.unimi.dsi.fastutil.objects.ObjectArrayList + +internal class LocalizationDocument(val modId: String, val sourceLocale: MinecraftLocale, val entries: ObjectArrayList) { + internal class Entry( + val key: TranslationKey, + val sourceText: String, + val sourceRevision: String, + val domains: ObjectArrayList, + val type: String?, + val glossaryIds: ObjectArrayList, + val unitIds: ObjectArrayList, + val placeholderSignature: Int2IntMap, + val translations: ObjectArrayList, + ) + + internal class Translation(val locale: MinecraftLocale, val text: String, val source: TranslationSource, val sourceRevision: String, val status: String?, val locked: Boolean) +} diff --git a/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportBuilder.kt b/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportBuilder.kt new file mode 100644 index 0000000..347b0a5 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportBuilder.kt @@ -0,0 +1,25 @@ +package com.modularmc.registrate.localization.export + +import com.modularmc.registrate.AbstractRegistrate + +import java.nio.file.Path + +/** 为所属模组配置数据生成时导出的本地化交换文件。 */ +class LocalizationExportBuilder internal constructor(private val registrate: AbstractRegistrate<*>) { + private var outputPath: Path? = null + + /** 设置导出 JSON 的完整文件路径。相对路径以当前进程的工作目录为基准。 */ + fun path(path: Path): LocalizationExportBuilder { + outputPath = path.toAbsolutePath().normalize() + return this + } + + /** + * 登记本地化导出任务,由数据生成流程在收集所属模组的语言声明后写出文件。 + * + * @throws IllegalArgumentException 尚未设置输出路径 + */ + fun build() { + registrate.requestLocalizationExport(requireNotNull(outputPath) { "Set the localization export path before build" }) + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportOutput.kt b/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportOutput.kt new file mode 100644 index 0000000..a5e8bef --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportOutput.kt @@ -0,0 +1,82 @@ +package com.modularmc.registrate.localization.export + +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.TranslationSource + +import net.minecraft.data.CachedOutput +import net.minecraft.data.DataProvider + +import com.google.gson.JsonArray +import com.google.gson.JsonNull +import com.google.gson.JsonObject +import it.unimi.dsi.fastutil.ints.Int2IntMaps + +import java.nio.file.Path +import java.util.Locale +import java.util.concurrent.CompletableFuture + +internal object LocalizationExportOutput { + fun write(cache: CachedOutput, path: Path, document: LocalizationDocument): CompletableFuture<*> = DataProvider.saveStable(cache, toJson(document), path) + + private fun toJson(document: LocalizationDocument): JsonObject { + val json = JsonObject() + json.addProperty("formatVersion", 1) + json.addProperty("modId", document.modId) + json.addProperty("sourceLocale", document.sourceLocale.code()) + val entries = JsonArray() + for (entry in document.entries) entries.add(entry(entry, document.sourceLocale)) + json.add("entries", entries) + return json + } + + private fun entry(value: LocalizationDocument.Entry, sourceLocale: MinecraftLocale): JsonObject { + val json = JsonObject() + json.addProperty("namespace", value.key.namespace) + json.addProperty("key", value.key.value) + val source = JsonObject() + source.addProperty("locale", sourceLocale.code()) + source.addProperty("text", value.sourceText) + source.addProperty("revision", value.sourceRevision) + json.add("source", source) + val context = JsonObject() + context.add("domains", strings(value.domains)) + if (value.type == null) context.add("type", JsonNull.INSTANCE) else context.addProperty("type", value.type) + context.add("glossaryIds", strings(value.glossaryIds)) + context.add("unitIds", strings(value.unitIds)) + val placeholders = JsonObject() + val indexes = IntArray(value.placeholderSignature.size) + val iterator = Int2IntMaps.fastIterator(value.placeholderSignature) + var index = 0 + while (iterator.hasNext()) indexes[index++] = iterator.next().intKey + indexes.sort() + for (argument in indexes) placeholders.addProperty(argument.toString(), value.placeholderSignature.get(argument)) + context.add("placeholderSignature", placeholders) + json.add("context", context) + val translations = JsonArray() + for (translation in value.translations) translations.add(translation(translation)) + json.add("translations", translations) + return json + } + + private fun translation(value: LocalizationDocument.Translation): JsonObject { + val json = JsonObject() + json.addProperty("locale", value.locale.code()) + json.addProperty("text", value.text) + val source = JsonObject() + source.addProperty("kind", sourceKind(value.source.kind)) + source.addProperty("location", value.source.location) + json.add("source", source) + json.addProperty("sourceRevision", value.sourceRevision) + if (value.status == null) json.add("status", JsonNull.INSTANCE) else json.addProperty("status", value.status) + json.addProperty("locked", value.locked) + return json + } + + private fun strings(values: Iterable): JsonArray { + val array = JsonArray() + for (value in values) array.add(value) + return array + } + + private fun sourceKind(kind: TranslationSource.Kind): String = kind.name.lowercase(Locale.ROOT) +} diff --git a/src/main/java/com/modularmc/registrate/localization/index/IndexedTranslations.kt b/src/main/java/com/modularmc/registrate/localization/index/IndexedTranslations.kt deleted file mode 100644 index 873f493..0000000 --- a/src/main/java/com/modularmc/registrate/localization/index/IndexedTranslations.kt +++ /dev/null @@ -1,41 +0,0 @@ -package com.modularmc.registrate.localization.index - -import com.modularmc.registrate.localization.LocalizationDeclaration -import com.modularmc.registrate.localization.MinecraftLocale -import com.modularmc.registrate.localization.TranslationKey -import com.modularmc.registrate.localization.TranslationSource -import com.modularmc.registrate.localization.resolution.TranslationRegistry - -import net.neoforged.fml.ModList - -import java.io.DataInputStream -import java.io.IOException -import java.io.UncheckedIOException -import java.nio.file.Files - -/** Loads the declarations compiled into a mod's own resources during DataGen. */ -object IndexedTranslations { - @JvmStatic - fun collect(modId: String, locale: MinecraftLocale, registry: TranslationRegistry) { - val modFile = ModList.get().getModFileById(modId).file - for (frontend in LocalizationIndex.Frontend.entries) { - val index = modFile.findResource(LocalizationIndex.path(modId, frontend)) - if (Files.notExists(index)) continue - - try { - DataInputStream(Files.newInputStream(index).buffered()).use { input -> - LocalizationIndex.read(input) { entry -> - registry.add( - TranslationKey(entry.namespace, entry.key), - locale, - LocalizationDeclaration(entry.source, entry.translations, emptyList(), null, emptyList()), - TranslationSource(TranslationSource.Kind.DECLARED, entry.location), - ) - } - } - } catch (error: IOException) { - throw UncheckedIOException("[$modId] Reading localization index $index", error) - } - } - } -} diff --git a/src/main/java/com/modularmc/registrate/localization/index/LocalizationIndex.kt b/src/main/java/com/modularmc/registrate/localization/index/LocalizationIndex.kt deleted file mode 100644 index ed1ff17..0000000 --- a/src/main/java/com/modularmc/registrate/localization/index/LocalizationIndex.kt +++ /dev/null @@ -1,90 +0,0 @@ -package com.modularmc.registrate.localization.index - -import com.modularmc.registrate.localization.MinecraftLocale - -import java.io.DataInputStream -import java.io.DataOutputStream -import java.io.IOException -import java.util.EnumMap -import java.util.function.Consumer - -/** The declaration protocol used by compiler frontends and the DataGen reader. */ -object LocalizationIndex { - private const val MAGIC = -0x524c494e - private const val VERSION = 1 - - private val entryOrder = compareBy(Entry::namespace, Entry::key, Entry::location) - - enum class Frontend(val suffix: String) { - JAVAC(""), - KSP(".ksp"), - } - - @JvmRecord - data class Entry(val namespace: String, val key: String, val source: String, val location: String, val translations: Map) - - @JvmStatic - @JvmOverloads - fun path(modId: String, frontend: Frontend = Frontend.JAVAC): String = "META-INF/registratelib/localization/$modId${frontend.suffix}.bin" - - @JvmStatic - fun variantKey(prefix: String, id: String): String = if (prefix.endsWith('.')) "$prefix$id" else "$prefix.$id" - - @JvmStatic - @Throws(IOException::class) - fun write(output: DataOutputStream, entries: Collection) { - output.writeInt(MAGIC) - output.writeInt(VERSION) - output.writeInt(entries.size) - for ((namespace, key, source, location, translations) in entries.sortedWith(entryOrder)) { - output.writeUTF(namespace) - output.writeUTF(key) - output.writeUTF(source) - output.writeUTF(location) - output.writeInt(translations.size) - for ((locale, text) in translations) { - output.writeUTF(locale.name) - output.writeUTF(text) - } - } - } - - @JvmStatic - @Throws(IOException::class) - fun read(input: DataInputStream, consumer: Consumer) { - val leading = input.readInt() - val count = if (leading == MAGIC) { - val version = input.readInt() - if (version != VERSION) { - throw IOException("Unsupported localization index version $version") - } - input.readInt() - } else { - leading // Version 0 began with the entry count. - } - - if (count < 0) { - throw IOException("Invalid localization index entry count $count") - } - repeat(count) { - val namespace = input.readUTF() - val key = input.readUTF() - val source = input.readUTF() - val location = input.readUTF() - val targetCount = input.readInt() - if (targetCount < 0) { - throw IOException("Invalid translation count $targetCount for $namespace/$key") - } - val translations = if (targetCount == 0) { - emptyMap() - } else { - EnumMap(MinecraftLocale::class.java).apply { - repeat(targetCount) { - put(MinecraftLocale.valueOf(input.readUTF()), input.readUTF()) - } - } - } - consumer.accept(Entry(namespace, key, source, location, translations)) - } - } -} diff --git a/src/main/java/com/modularmc/registrate/localization/locale/BritishEnglish.kt b/src/main/java/com/modularmc/registrate/localization/locale/BritishEnglish.kt new file mode 100644 index 0000000..ad19c91 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/locale/BritishEnglish.kt @@ -0,0 +1,75 @@ +package com.modularmc.registrate.localization.locale + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap + +import java.util.regex.Pattern + +internal object BritishEnglish { + private val words = Object2ObjectOpenHashMap(42).apply { + put("color", "colour") + put("colors", "colours") + put("colored", "coloured") + put("coloring", "colouring") + put("colorize", "colourise") + put("colorized", "colourised") + put("colorizes", "colourises") + put("colorizing", "colourising") + put("favor", "favour") + put("favors", "favours") + put("favorite", "favourite") + put("favorites", "favourites") + put("honor", "honour") + put("honors", "honours") + put("honored", "honoured") + put("honoring", "honouring") + put("labor", "labour") + put("neighbor", "neighbour") + put("neighbors", "neighbours") + put("rumor", "rumour") + put("center", "centre") + put("centers", "centres") + put("centered", "centred") + put("centering", "centring") + put("meter", "metre") + put("meters", "metres") + put("liter", "litre") + put("liters", "litres") + put("theater", "theatre") + put("theaters", "theatres") + put("gray", "grey") + put("grays", "greys") + put("defense", "defence") + put("offense", "offence") + put("organize", "organise") + put("organizes", "organises") + put("organized", "organised") + put("organizing", "organising") + put("analyze", "analyse") + put("analyzes", "analyses") + put("analyzed", "analysed") + put("analyzing", "analysing") + } + private val wordsPattern = Pattern.compile("[A-Za-z]+") + + fun convert(text: String): String { + val matcher = wordsPattern.matcher(text) + var converted: StringBuilder? = null + var copiedUntil = 0 + while (matcher.find()) { + val word = matcher.group() + val replacement = words[word.lowercase()] ?: continue + val output = converted ?: StringBuilder(text.length).also { converted = it } + output.append(text, copiedUntil, matcher.start()) + output.append(caseLike(word, replacement)) + copiedUntil = matcher.end() + } + val output = converted ?: return text + return output.append(text, copiedUntil, text.length).toString() + } + + private fun caseLike(word: String, replacement: String): String = when { + word.all(Char::isUpperCase) -> replacement.uppercase() + word.first().isUpperCase() -> replacement.replaceFirstChar(Char::uppercase) + else -> replacement + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/locale/LocaleConverter.kt b/src/main/java/com/modularmc/registrate/localization/locale/LocaleConverter.kt new file mode 100644 index 0000000..3e9af41 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/locale/LocaleConverter.kt @@ -0,0 +1,24 @@ +package com.modularmc.registrate.localization.locale + +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.TranslationKey + +/** + * 供数据生成流程在派生目标语言时转换纯文本片段。 + * 同一条译文可能分多次调用转换器,结果应只取决于输入和转换上下文。 + */ +fun interface LocaleConverter { + /** + * 转换一个纯文本片段。 + * + * @param text 待转换的文本片段 + * @param context 包含源语言、目标语言和声明信息的上下文 + * @return 转换后的文本片段 + */ + fun convert(text: String, context: Context): String + + /** 传给转换器的声明上下文,包含翻译键、输入和输出语言以及完整的本地化声明。 */ + @JvmRecord + data class Context(val key: TranslationKey, val input: MinecraftLocale, val output: MinecraftLocale, val declaration: LocalizationDeclaration) +} diff --git a/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt b/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt new file mode 100644 index 0000000..d54f7b2 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt @@ -0,0 +1,43 @@ +package com.modularmc.registrate.localization.locale + +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.MinecraftLocale.EN_GB +import com.modularmc.registrate.localization.MinecraftLocale.EN_UD +import com.modularmc.registrate.localization.MinecraftLocale.EN_US +import com.modularmc.registrate.localization.MinecraftLocale.ZH_CN +import com.modularmc.registrate.localization.MinecraftLocale.ZH_TW +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource.Kind +import com.modularmc.registrate.localization.resolution.MinecraftTextFormat + +/** 定义目标语言缺少译文时的派生规则。数据生成流程以输入语言已解析的文本为基础。 */ +class LocaleDerivation private constructor( + val input: MinecraftLocale, + val output: MinecraftLocale, + internal val kind: Kind, + private val transform: (String, Collection, TranslationKey, LocalizationDeclaration) -> String, +) { + /** 创建纯文本转换规则。转换器会逐段执行,格式控制、占位符和单位符号由本地化流程保留。 */ + constructor(input: MinecraftLocale, output: MinecraftLocale, converter: LocaleConverter) : this( + input, + output, + Kind.VARIANT, + { text, symbols, key, declaration -> + val context = LocaleConverter.Context(key, input, output, declaration) + MinecraftTextFormat.convert(text, symbols) { converter.convert(it, context) } + }, + ) + + internal fun derive(text: String, symbols: Collection, key: TranslationKey, declaration: LocalizationDeclaration): String = transform(text, symbols, key, declaration) + + companion object { + internal val UPSIDE_DOWN = LocaleDerivation(EN_US, EN_UD, Kind.VARIANT) { text, symbols, _, _ -> MinecraftTextFormat.upsideDown(text, symbols) } + internal val BRITISH_ENGLISH = LocaleDerivation(EN_US, EN_GB) { text, _ -> BritishEnglish.convert(text) } + internal val TRADITIONAL_CHINESE = LocaleDerivation(ZH_CN, ZH_TW) { text, _ -> TraditionalChinese.convert(text) } + + /** 为目标语言配置显示回退规则。缺少译文时直接使用输入语言已解析的文本。 */ + @JvmStatic + fun fallback(input: MinecraftLocale, output: MinecraftLocale): LocaleDerivation = LocaleDerivation(input, output, Kind.FALLBACK) { text, _, _, _ -> text } + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivationGraph.kt b/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivationGraph.kt new file mode 100644 index 0000000..904cd0f --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivationGraph.kt @@ -0,0 +1,50 @@ +package com.modularmc.registrate.localization.locale + +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.MinecraftLocale.EN_GB +import com.modularmc.registrate.localization.MinecraftLocale.EN_UD +import com.modularmc.registrate.localization.MinecraftLocale.ZH_TW + +import it.unimi.dsi.fastutil.objects.ObjectArrayList + +import java.util.EnumMap +import java.util.EnumSet + +internal class LocaleDerivationGraph(modId: String, derivations: Collection) { + private val outgoing = EnumMap>(MinecraftLocale::class.java) + + init { + val byTarget = EnumMap(MinecraftLocale::class.java) + byTarget[EN_UD] = LocaleDerivation.UPSIDE_DOWN + byTarget[EN_GB] = LocaleDerivation.BRITISH_ENGLISH + byTarget[ZH_TW] = LocaleDerivation.TRADITIONAL_CHINESE + for (derivation in derivations) byTarget[derivation.output] = derivation + + val done = EnumSet.noneOf(MinecraftLocale::class.java) + val path = ObjectArrayList() + val visiting = EnumSet.noneOf(MinecraftLocale::class.java) + for (target in byTarget.keys) { + var locale = target + while (locale !in done) { + val rule = byTarget[locale] ?: break + require(visiting.add(locale)) { + val cycleStart = path.indexOf(locale) + val cycle = path.subList(cycleStart, path.size).joinToString(" -> ", transform = MinecraftLocale::code) + "[$modId] Locale derivation cycle: $cycle -> ${locale.code()}" + } + path.add(locale) + locale = rule.input + } + done.addAll(visiting) + visiting.clear() + path.clear() + } + for (derivation in byTarget.values) outgoing.computeIfAbsent(derivation.input) { ObjectArrayList(1) }.add(derivation) + } + + fun from(locale: MinecraftLocale): List = outgoing[locale].orEmpty() + + companion object { + val DEFAULT = LocaleDerivationGraph("registratelib", emptyList()) + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/locale/TraditionalChinese.kt b/src/main/java/com/modularmc/registrate/localization/locale/TraditionalChinese.kt new file mode 100644 index 0000000..82b49a2 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/locale/TraditionalChinese.kt @@ -0,0 +1,9 @@ +package com.modularmc.registrate.localization.locale + +import com.ibm.icu.text.Transliterator + +internal object TraditionalChinese { + private val transliterator = ThreadLocal.withInitial { Transliterator.getInstance("Simplified-Traditional") } + + fun convert(text: String): String = transliterator.get().transliterate(text) +} diff --git a/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt b/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt index 0ec1387..d5f190a 100644 --- a/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt +++ b/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt @@ -7,7 +7,10 @@ import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap import java.util.regex.Pattern internal object MinecraftTextFormat { - private val tokenPattern = Pattern.compile("%(?:(\\d+)\\$)?s|%%") + private const val ARGUMENT = "%(?:(\\d+)\\$)?s|%%" + private const val PROTECTED = "$ARGUMENT|(§[^\\r\\n]|\\R)|https?://[^\\s<>§]+" + private val argumentPattern = Pattern.compile(ARGUMENT) + private val protectedPattern = Pattern.compile(PROTECTED) private const val NORMAL = "abcdefghijklmn\u00F1opqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789()[]{}<>\u25C1\u25B7_,;.?!/\\'" private const val INVERTED = "\u0250q\u0254p\u01DD\u025Fb\u0265\u0131\u0638\u029E\u05DF\u026Fuuodb\u0279s\u0287n\u028C\u028Dx\u028Ez" + @@ -22,61 +25,105 @@ internal object MinecraftTextFormat { private data class Token(val start: Int, val end: Int, val argument: Int) - private val plainTextSignature: Int2IntMap = Int2IntMaps.EMPTY_MAP - private val plainText = Parsed(plainTextSignature, null) - - class Parsed(val signature: Int2IntMap, val variant: String?) - - fun parse(text: String, invert: Boolean): Parsed { + /** 统计可识别的格式占位符及其次数,用于比较源文和译文引用的参数是否一致。 */ + fun signature(text: String): Int2IntMap { val firstPercent = text.indexOf('%') - if (firstPercent < 0) { - return parsePlain(text, invert) - } + if (firstPercent < 0) return Int2IntMaps.EMPTY_MAP - val matcher = tokenPattern.matcher(text) - if (!matcher.find(firstPercent)) { - return parsePlain(text, invert) - } + val matcher = argumentPattern.matcher(text) + if (!matcher.find(firstPercent)) return Int2IntMaps.EMPTY_MAP - val tokens = if (invert) ArrayList(2) else null val signature = Int2IntOpenHashMap(2) var nextArgument = 1 do { - val indexStart = matcher.start(1) - val argument = when { - text[matcher.start() + 1] == '%' -> 0 + val index = matcher.start(1) + val argument = if (index >= 0) { + argumentIndex(text, index, matcher.end(1)) + } else if (text[matcher.start() + 1] == '%') { + 0 + } else { + nextArgument++ + } + signature.addTo(argument, 1) + } while (matcher.find()) + return signature + } + + /** 逐段转换纯文本,保留 Minecraft 格式码、占位符及 [symbols] 指定的单位符号。 */ + fun convert(text: String, symbols: Collection, convertRun: (String) -> String): String { + val matcher = tokenPattern(symbols).matcher(text) + if (!matcher.find()) return convertRun(text) - indexStart < 0 -> nextArgument++ + val result = StringBuilder(text.length) + var cursor = 0 + do { + if (cursor < matcher.start()) result.append(convertRun(text.substring(cursor, matcher.start()))) + result.append(text, matcher.start(), matcher.end()) + cursor = matcher.end() + } while (matcher.find()) + if (cursor < text.length) result.append(convertRun(text.substring(cursor))) + return result.toString() + } - else -> { - val position = Integer.parseInt(text, indexStart, matcher.end(1), 10) - require(position >= 1) { "Minecraft argument indices start at 1" } - position + /** 将可见文字变为倒置文本,同时尽量保持样式边界和不可拆分的格式标记。 */ + fun upsideDown(text: String, symbols: Collection): String { + val result = StringBuilder(text.length) + val matcher = tokenPattern(symbols).matcher(text) + if (!matcher.find()) { + appendUpsideDown(text, 0, text.length, result) + return result.toString() + } + + val tokens = ArrayList(2) + var start = 0 + var nextArgument = 1 + do { + if (matcher.start(2) >= 0) { + // 换行和样式切换会断开文本片段,反转时让样式留在原来的文本上。 + reverseRun(text, start, matcher.start(), tokens, result) + result.append(text, matcher.start(), matcher.end()) + tokens.clear() + start = matcher.end() + } else { + val index = matcher.start(1) + val argument = when { + index >= 0 -> argumentIndex(text, index, matcher.end(1)) + text[matcher.start()] != '%' -> -1 + text[matcher.start() + 1] == '%' -> 0 + else -> nextArgument++ } + tokens.add(Token(matcher.start(), matcher.end(), argument)) } - signature.addTo(argument, 1) - tokens?.add(Token(matcher.start(), matcher.end(), argument)) } while (matcher.find()) - return Parsed(signature, tokens?.let { upsideDown(text, it) }) + reverseRun(text, start, text.length, tokens, result) + return result.toString() } - private fun parsePlain(text: String, invert: Boolean): Parsed = if (invert) Parsed(plainTextSignature, upsideDown(text, emptyList())) else plainText + private fun argumentIndex(text: String, start: Int, end: Int): Int { + val index = Integer.parseInt(text, start, end, 10) + require(index >= 1) { "Minecraft argument indices start at 1" } + return index + } - private fun upsideDown(text: String, tokens: List): String { - val result = StringBuilder(text.length) - var cursor = text.length + private fun tokenPattern(symbols: Collection): Pattern { + if (symbols.isEmpty()) return protectedPattern + val units = symbols.sortedByDescending(String::length).joinToString("|", transform = Pattern::quote) + return Pattern.compile("$PROTECTED|(?, result: StringBuilder) { + var cursor = end for (index in tokens.indices.reversed()) { val token = tokens[index] appendUpsideDown(text, token.end, cursor, result) - if (token.argument == 0) { - result.append("%%") - } else { + if (token.argument > 0) { result.append('%').append(token.argument).append($$"$s") + } else { + result.append(text, token.start, token.end) } cursor = token.start } - appendUpsideDown(text, 0, cursor, result) - return result.toString() + appendUpsideDown(text, start, cursor, result) } private fun appendUpsideDown(text: String, start: Int, end: Int, result: StringBuilder) { diff --git a/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt b/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt index 0ffe1b0..e206fd7 100644 --- a/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt +++ b/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt @@ -1,20 +1,39 @@ package com.modularmc.registrate.localization.resolution +import com.modularmc.registrate.internal.util.RegistrateLogger.datagen +import com.modularmc.registrate.localization.ImportedTranslation import com.modularmc.registrate.localization.LocalizationDeclaration import com.modularmc.registrate.localization.MinecraftLocale -import com.modularmc.registrate.localization.MinecraftLocale.EN_UD -import com.modularmc.registrate.localization.MinecraftLocale.EN_US +import com.modularmc.registrate.localization.SourceRevision import com.modularmc.registrate.localization.TranslationKey import com.modularmc.registrate.localization.TranslationSource +import com.modularmc.registrate.localization.TranslationSource.Kind +import com.modularmc.registrate.localization.TranslationStatus.STALE +import com.modularmc.registrate.localization.export.LocalizationDocument +import com.modularmc.registrate.localization.locale.LocaleDerivation +import com.modularmc.registrate.localization.locale.LocaleDerivationGraph +import com.modularmc.registrate.localization.terminology.Terminology +import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTerm import it.unimi.dsi.fastutil.ints.Int2IntMap import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap +import it.unimi.dsi.fastutil.objects.Object2ObjectMap +import it.unimi.dsi.fastutil.objects.Object2ObjectMaps +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap +import it.unimi.dsi.fastutil.objects.ObjectArrayList +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap import java.util.TreeMap +import java.util.function.Consumer -/** Resolves the declarations for one DataGen output before the language provider writes any files. */ -class TranslationRegistry { +/** 在语言文件写出前,为同一份数据生成输出解析本地化声明。 */ +internal class TranslationRegistry(private val parent: TranslationRegistry? = null) { private val selections = Object2ObjectLinkedOpenHashMap() + private val imports = ObjectArrayList() + private val declarations = Reference2ObjectOpenHashMap>() + private val importRevisions = Reference2ObjectOpenHashMap() + private val derivations = Reference2ObjectOpenHashMap() @JvmRecord data class LanguageFile(val namespace: String, val locale: MinecraftLocale) @@ -23,24 +42,47 @@ class TranslationRegistry { override fun toString(): String = "${key.namespace}/${key.value} (${locale.code()})" } - private class Candidate(val text: String, val source: TranslationSource, val original: Selection?) + private class Declaration(val localization: LocalizationDeclaration, val terminology: Terminology) - private class Selection(var winner: Candidate) { - private var ties: MutableList? = null - lateinit var signature: Int2IntMap + private class PendingImport(val sourceLocale: MinecraftLocale, val translation: ImportedTranslation, val terminology: Terminology) + + private class Candidate(val text: String, val source: TranslationSource, val declaration: Declaration, val original: Selection? = null, val importPriority: Int = 0) { + fun comparePriority(other: Candidate): Int { + val sourcePriority = source.kind.priority.compareTo(other.source.kind.priority) + return if (sourcePriority != 0) sourcePriority else importPriority.compareTo(other.importPriority) + } + } + + private class Resolved( + val imported: Object2ObjectMap, + val glossary: Object2ObjectLinkedOpenHashMap, + val glossaryTerms: MutableMap, + val variants: Object2ObjectLinkedOpenHashMap, + val files: Map>, + ) + + private class ExportEntry(val candidate: Candidate) { + val sourceRevision = SourceRevision.of(candidate.declaration.localization.source).value + val translations = ObjectArrayList() + } + + private class Selection(private val key: EntryKey, var winner: Candidate) { + private var ties: ObjectArrayList? = null + private var signature: Int2IntMap? = null fun add(candidate: Candidate) { - val precedence = candidate.source.kind.compareTo(winner.source.kind) + val precedence = candidate.comparePriority(winner) if (precedence > 0) { winner = candidate ties = null + signature = null } else if (precedence == 0) { - val candidates = ties ?: ArrayList(1).also { ties = it } + val candidates = ties ?: ObjectArrayList(1).also { ties = it } candidates.add(candidate) } } - fun verifyText(key: EntryKey) { + fun verifyText() { ties?.forEach { candidate -> require(candidate.text == winner.text) { "Conflicting translations for $key from ${winner.source.location} and ${candidate.source.location}" @@ -48,64 +90,312 @@ class TranslationRegistry { } } - fun verifyPlaceholders(key: EntryKey) { - verifyPlaceholders(key, winner) - ties?.forEach { verifyPlaceholders(key, it) } + fun forEachWinner(action: (Candidate) -> Unit) { + action(winner) + ties?.forEach(action) } - private fun verifyPlaceholders(key: EntryKey, candidate: Candidate) { - candidate.original?.let { original -> - require(original.signature == signature) { "Minecraft placeholder mismatch for $key at ${candidate.source.location}" } + fun verifyPlaceholders() { + val expected = placeholderSignature() + forEachWinner { candidate -> + val original = candidate.original ?: return@forEachWinner + require(original.placeholderSignature() == expected) { "Minecraft placeholder mismatch for $key at ${candidate.source.location}" } + } + } + + private fun placeholderSignature(): Int2IntMap { + signature?.let { return it } + return try { + MinecraftTextFormat.signature(winner.text).also { signature = it } + } catch (error: IllegalArgumentException) { + throw IllegalArgumentException("Invalid Minecraft placeholder for $key at ${winner.source.location}", error) } } } - fun add(key: TranslationKey, locale: MinecraftLocale, declaration: LocalizationDeclaration, source: TranslationSource) { - val original = add(EntryKey(key, locale), Candidate(declaration.source, source, null)) + @JvmOverloads + fun add(key: TranslationKey, locale: MinecraftLocale, declaration: LocalizationDeclaration, source: TranslationSource, terminology: Terminology = Terminology.EMPTY) { + val context = Declaration(declaration, terminology) + val sourceKey = EntryKey(key, locale) + val sourceCandidate = Candidate(declaration.source, source, context) + val original = selections.add(sourceKey, sourceCandidate) + val ownedDeclarations = declarations.computeIfAbsent(terminology) { Object2ObjectOpenHashMap() } + val ownedDeclaration = ownedDeclarations[sourceKey] + if (ownedDeclaration == null || sourceCandidate.comparePriority(ownedDeclaration) > 0) ownedDeclarations[sourceKey] = sourceCandidate for ((target, text) in declaration.translations) { - add(EntryKey(key, target), Candidate(text, source, original)) + selections.add(EntryKey(key, target), Candidate(text, source, context, original)) + } + parent?.add(key, locale, declaration, source, terminology) + } + + internal fun addImported(sourceLocale: MinecraftLocale, translation: ImportedTranslation, terminology: Terminology) { + val key = EntryKey(translation.key, sourceLocale) + require(declarations[terminology]?.containsKey(key) == true) { + "No source declaration for import $key at ${translation.location}" } + val target = key.copy(locale = translation.locale) + require(target != key) { "Imported translation $target at ${translation.location} uses the source locale" } + imports.add(PendingImport(sourceLocale, translation, terminology)) + parent?.addImported(sourceLocale, translation, terminology) + } + + internal fun configureDerivations(terminology: Terminology, modId: String, rules: Collection) { + derivations[terminology] = LocaleDerivationGraph(modId, rules) + parent?.configureDerivations(terminology, modId, rules) } - private fun add(key: EntryKey, candidate: Candidate): Selection { - val selection = selections[key] + private fun Object2ObjectLinkedOpenHashMap.add(key: EntryKey, candidate: Candidate): Selection { + val selection = this[key] if (selection != null) { selection.add(candidate) return selection } - return Selection(candidate).also { selections[key] = it } + return Selection(key, candidate).also { put(key, it) } } - fun resolve(): Map> { + /** 解析各语言文件的条目。提供 [reportImport] 时,同时报告匹配到的外部译文及其当前状态。 */ + @JvmOverloads + fun resolve(reportImport: Consumer? = null): Map> = resolveAll(reportImport).files + + internal fun export(modId: String, sourceLocale: MinecraftLocale): LocalizationDocument { + val resolved = resolveAll(reportWarnings = false) + val entries = Object2ObjectLinkedOpenHashMap() + for (owned in declarations.values) { + owned.object2ObjectEntrySet().fastForEach { (key, candidate) -> + if (key.locale == sourceLocale) entries.computeIfAbsent(key.key) { ExportEntry(candidate) } + } + } + + forEachSelection(resolved.imported) { key, selection -> + if (key.locale != sourceLocale) { + selection.forEachWinner { candidate -> + if (candidate.source.kind != Kind.IMPORTED) { + val exported = entries.getValue(key.key) + exported.translations.add(candidate.translation(key.locale, exported.sourceRevision)) + } + } + } + } + resolved.glossary.object2ObjectEntrySet().fastForEach { (key, selection) -> + if (key.locale != sourceLocale) { + selection.forEachWinner { candidate -> + val exported = entries.getValue(key.key) + exported.translations.add(candidate.translation(key.locale, exported.sourceRevision)) + } + } + } + resolved.variants.object2ObjectEntrySet().fastForEach { (key, selection) -> + if (key.locale != sourceLocale) { + selection.forEachWinner { candidate -> + val exported = entries.getValue(key.key) + exported.translations.add(candidate.translation(key.locale, exported.sourceRevision)) + } + } + } + for (pending in imports) { + val key = EntryKey(pending.translation.key, pending.sourceLocale) + val source = declarations[pending.terminology]!!.getValue(key) + val revision = importRevisions.getValue(source) + val translation = pending.translation.forRevision(revision) + entries.getValue(translation.key).translations.add( + LocalizationDocument.Translation( + translation.locale, + translation.text, + TranslationSource(Kind.IMPORTED, translation.location), + translation.sourceRevision.value, + translation.status.name.lowercase(), + translation.locked, + ), + ) + } + + val result = ObjectArrayList(entries.size) + entries.object2ObjectEntrySet().fastForEach { (key, exported) -> + val declaration = exported.candidate.declaration + val localization = declaration.localization + val glossaryIds = ObjectOpenHashSet(localization.glossary.size + localization.glossaryIds.size + 1) + for (term in localization.glossary) glossaryIds.add(term.id) + glossaryIds.addAll(localization.glossaryIds) + val unitIds = ObjectOpenHashSet(localization.unitIds) + resolved.glossaryTerms[declaration]?.let { term -> + glossaryIds.add(term.id) + unitIds.addAll(term.unitIds) + } + val domains = ObjectArrayList(localization.domains.size) + for (domain in localization.domains) domains.add(domain.id) + domains.sort() + val sortedGlossaryIds = ObjectArrayList(glossaryIds) + sortedGlossaryIds.sort() + val sortedUnitIds = ObjectArrayList(unitIds) + sortedUnitIds.sort() + exported.translations.sortWith(compareBy({ it.locale.code() }, { it.source.kind.name }, { it.source.location }, { it.text })) + result.add( + LocalizationDocument.Entry( + key, + localization.source, + exported.sourceRevision, + domains, + localization.type?.id, + sortedGlossaryIds, + sortedUnitIds, + MinecraftTextFormat.signature(localization.source), + exported.translations, + ), + ) + } + result.sortWith(compareBy({ it.key.namespace }, { it.key.value })) + return LocalizationDocument(modId, sourceLocale, result) + } + + private fun Candidate.translation(locale: MinecraftLocale, sourceRevision: String): LocalizationDocument.Translation = LocalizationDocument.Translation( + locale, + text, + source, + sourceRevision, + null, + false, + ) + + private fun resolveAll(reportImport: Consumer? = null, reportWarnings: Boolean = true): Resolved { + val imported = resolveImports(reportImport, reportWarnings) val files = Object2ObjectLinkedOpenHashMap>() - val entries = selections.object2ObjectEntrySet() - var iterator = entries.fastIterator() - while (iterator.hasNext()) { - val entry = iterator.next() - val key = entry.key - val selection = entry.value - selection.verifyText(key) - - val winner = selection.winner - val variantKey = if (key.locale == EN_US) key.copy(locale = EN_UD) else null - val invert = variantKey != null && !selections.containsKey(variantKey) - val parsed = try { - MinecraftTextFormat.parse(winner.text, invert) - } catch (error: IllegalArgumentException) { - throw IllegalArgumentException("Invalid Minecraft placeholder for $key at ${winner.source.location}", error) + forEachSelection(imported) { key, selection -> collectLanguageText(key, selection, files) } + + val glossaryTerms = Reference2ObjectOpenHashMap() + val glossary = collectGlossary(imported, glossaryTerms, reportWarnings) + glossary.object2ObjectEntrySet().fastForEach { collectLanguageText(it.key, it.value, files) } + val variants = collectDerivations(imported, glossary, glossaryTerms) + variants.object2ObjectEntrySet().fastForEach { collectLanguageText(it.key, it.value, files) } + return Resolved(imported, glossary, glossaryTerms, variants, files) + } + + private fun resolveImports(reportImport: Consumer?, reportWarnings: Boolean): Object2ObjectMap { + if (imports.isEmpty) return Object2ObjectMaps.emptyMap() + + val selected = Object2ObjectLinkedOpenHashMap() + val logger = if (reportWarnings) datagen() else null + for (pending in imports) { + val key = EntryKey(pending.translation.key, pending.sourceLocale) + val declarationCandidate = declarations[pending.terminology]!![key]!! + val original = selections.getValue(key) + val declaration = declarationCandidate.declaration + val revision = importRevisions.getOrPut(declarationCandidate) { SourceRevision.of(declaration.localization.source) } + val translation = pending.translation.forRevision(revision) + reportImport?.accept(translation) + + val target = key.copy(locale = translation.locale) + if (translation.status == STALE) { + logger?.warn("Stale translation for {} at {} (reviewed revision {}, current revision {})", target, translation.location, translation.sourceRevision.value, revision.value) + if (!translation.locked) continue + } + val existing = selections[target] + if (existing != null && existing.winner.source.kind.priority > Kind.IMPORTED.priority) continue + val source = TranslationSource(Kind.IMPORTED, translation.location) + selected.add(target, Candidate(translation.text, source, declaration, original, translation.status.priority(translation.locked))) + } + return selected + } + + private inline fun forEachSelection(imported: Object2ObjectMap, action: (EntryKey, Selection) -> Unit) { + val entries = selections.object2ObjectEntrySet().fastIterator() + while (entries.hasNext()) { + val entry = entries.next() + action(entry.key, imported[entry.key] ?: entry.value) + } + val translations = Object2ObjectMaps.fastIterator(imported) + while (translations.hasNext()) { + val entry = translations.next() + if (!selections.containsKey(entry.key)) action(entry.key, entry.value) + } + } + + private fun collectGlossary( + imported: Object2ObjectMap, + terms: MutableMap, + reportWarnings: Boolean, + ): Object2ObjectLinkedOpenHashMap { + val glossary = Object2ObjectLinkedOpenHashMap() + forEachSelection(imported) { key, selection -> + selection.forEachWinner { candidate -> + if (candidate.original != null) return@forEachWinner + val declaration = candidate.declaration + val term = declaration.terminology.resolveTerm(key.key, declaration.localization, candidate.source) ?: return@forEachWinner + terms[declaration] = term + for (synonym in declaration.terminology.synonyms(term)) { + val source = TranslationSource(Kind.GLOSSARY, "${candidate.source.location} (glossary ${synonym.id})") + for ((locale, text) in synonym.preferredTranslations) { + if (locale == key.locale) continue + val target = key.copy(locale = locale) + val explicit = imported[target] ?: selections[target] + if (explicit == null) { + glossary.add(target, Candidate(text, source, declaration, selection)) + } else { + checkGlossaryText(target, synonym, text, explicit.winner, reportWarnings) + } + } + } + } + } + return glossary + } + + private fun collectDerivations( + imported: Object2ObjectMap, + glossary: Object2ObjectLinkedOpenHashMap, + terms: Map, + ): Object2ObjectLinkedOpenHashMap { + val variants = Object2ObjectLinkedOpenHashMap() + + fun expand(key: EntryKey, candidate: Candidate, original: Selection, graph: LocaleDerivationGraph, symbols: Collection) { + for (rule in graph.from(key.locale)) { + val target = key.copy(locale = rule.output) + if (selections.containsKey(target) || imported.containsKey(target) || glossary.containsKey(target)) continue + val kind = if (candidate.source.kind == Kind.FALLBACK) Kind.FALLBACK else rule.kind + val source = TranslationSource(kind, "${candidate.source.location} (${key.locale.code()} -> ${target.locale.code()})") + val declaration = candidate.declaration + val converted = rule.derive(candidate.text, symbols, key.key, declaration.localization) + val variant = Candidate(converted, source, declaration, original) + variants.add(target, variant) + expand(target, variant, original, graph, symbols) } - selection.signature = parsed.signature - files.computeIfAbsent(LanguageFile(key.key.namespace, key.locale)) { TreeMap() }[key.key.value] = winner.text - if (variantKey != null && parsed.variant != null) { - files.computeIfAbsent(LanguageFile(key.key.namespace, EN_UD)) { TreeMap() }[key.key.value] = parsed.variant + } + + fun expandFrom(key: EntryKey, selection: Selection) { + selection.forEachWinner { candidate -> + val declaration = candidate.declaration + val graph = derivations[declaration.terminology] ?: LocaleDerivationGraph.DEFAULT + if (graph.from(key.locale).isEmpty()) return@forEachWinner + val symbols = unitSymbols(declaration, terms[declaration]) + expand(key, candidate, selection, graph, symbols) } } + forEachSelection(imported, ::expandFrom) + glossary.object2ObjectEntrySet().fastForEach { expandFrom(it.key, it.value) } + return variants + } - iterator = entries.fastIterator() - while (iterator.hasNext()) { - val entry = iterator.next() - entry.value.verifyPlaceholders(entry.key) + private fun unitSymbols(declaration: Declaration, term: GlossaryTerm?): Collection { + val ids = declaration.localization.unitIds + val termIds = term?.unitIds.orEmpty() + if (ids.isEmpty() && termIds.isEmpty()) return emptyList() + val unitSymbols = ObjectOpenHashSet(ids.size + termIds.size) + for (id in ids) unitSymbols.add(declaration.terminology.unitSymbol(id)) + for (id in termIds) unitSymbols.add(declaration.terminology.unitSymbol(id)) + return unitSymbols + } + + private fun checkGlossaryText(key: EntryKey, term: GlossaryTerm, preferred: String, candidate: Candidate, reportWarnings: Boolean) { + val text = candidate.text + val forbidden = term.forbiddenTranslations[key.locale]?.any { it.equals(text, ignoreCase = true) } == true + val accepted = preferred.equals(text, ignoreCase = true) || term.acceptedTranslations[key.locale]?.any { it.equals(text, ignoreCase = true) } == true + if (reportWarnings && (forbidden || !accepted)) { + datagen().warn("Glossary term {} for {} at {} prefers '{}', found '{}'", term.id, key, candidate.source.location, preferred, text) } - return files + } + + private fun collectLanguageText(key: EntryKey, selection: Selection, files: MutableMap>) { + selection.verifyText() + selection.verifyPlaceholders() + files.computeIfAbsent(LanguageFile(key.key.namespace, key.locale)) { TreeMap() }[key.key.value] = selection.winner.text } } diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt b/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt index 65bbb5c..63155f7 100644 --- a/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt +++ b/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt @@ -1,19 +1,29 @@ package com.modularmc.registrate.localization.terminology -/** Built-in fields used to associate terms and localization declarations. */ -enum class Domain(private val id: String) { - CHEMISTRY("chemistry"), - PHYSICS("physics"), - ENERGY("energy"), - ASTRONOMY("astronomy"), - GEOGRAPHY("geography"), - GEOLOGY("geology"), - ENGINEERING("engineering"), - MATERIALS("materials"), - COMPUTING("computing"), - MAGIC("magic"), - ADVENTURE("adventure"), - ; - - fun id(): String = id +/** 通过稳定标识关联术语和本地化声明。模组可以定义自己的领域。 */ +@JvmRecord +data class Domain(val id: String) { + companion object { + @JvmField val CHEMISTRY = Domain("chemistry") + + @JvmField val PHYSICS = Domain("physics") + + @JvmField val ENERGY = Domain("energy") + + @JvmField val ASTRONOMY = Domain("astronomy") + + @JvmField val GEOGRAPHY = Domain("geography") + + @JvmField val GEOLOGY = Domain("geology") + + @JvmField val ENGINEERING = Domain("engineering") + + @JvmField val MATERIALS = Domain("materials") + + @JvmField val COMPUTING = Domain("computing") + + @JvmField val MAGIC = Domain("magic") + + @JvmField val ADVENTURE = Domain("adventure") + } } diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt b/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt new file mode 100644 index 0000000..27c051e --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt @@ -0,0 +1,37 @@ +package com.modularmc.registrate.localization.terminology + +import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTerm +import com.modularmc.registrate.localization.terminology.Terminology.TermRelation + +/** + * 向模组的 [Terminology] 提供术语查询,可由不同形式的存储实现。 + * 在模组初始化时注册,数据生成期间应保持查询结果稳定。 + * 同一模组的各词汇表共用术语标识,一个标识只能对应一条定义。 + */ +interface Glossary { + /** + * 按稳定标识查询术语。 + * + * @param id 查询的术语标识 + * @return 对应的术语,当前词汇表没有该术语时返回 `null` + */ + fun find(id: String): GlossaryTerm? + + /** + * 按完整的源语言词条或别名查询,保留不同领域和文本类型下的各个词义。 + * + * @param normalizedSource 按与语言区域无关的规则转为小写的查询词 + * @return 匹配的术语,没有匹配项时返回空集合 + */ + fun findBySource(normalizedSource: String): Iterable + + /** + * 查询指定关系直接关联的术语。查询同义关系时同时返回正向和反向关联。 + * 关系数据由实现类提供,数据生成期间应保持查询结果稳定。 + * + * @param id 待查询的术语标识 + * @param relation 要匹配的关系类型 + * @return 与该术语直接关联的术语 + */ + fun findRelated(id: String, relation: TermRelation): Iterable +} diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/IndexedGlossary.kt b/src/main/java/com/modularmc/registrate/localization/terminology/IndexedGlossary.kt new file mode 100644 index 0000000..c9ab229 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/terminology/IndexedGlossary.kt @@ -0,0 +1,89 @@ +package com.modularmc.registrate.localization.terminology + +import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTerm +import com.modularmc.registrate.localization.terminology.Terminology.TermRelation + +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap +import it.unimi.dsi.fastutil.objects.ObjectArrayList +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet + +internal class IndexedGlossary : Glossary { + private data class RelationKey(val id: String, val relation: TermRelation) + private data class RelationEdge(val key: RelationKey, val targetId: String) + + private val terms = Object2ObjectOpenHashMap() + private val termsBySource = Object2ObjectOpenHashMap>() + private val relatedIds = Object2ObjectOpenHashMap>() + private val relationCounts = Object2ObjectOpenHashMap>() + private val relationEdges = Object2ObjectOpenHashMap>() + + fun isEmpty(): Boolean = terms.isEmpty() + + fun register(term: GlossaryTerm) { + val previous = terms[term.id] + if (previous != null) { + forEachForm(previous) { source -> + val oldTerms = termsBySource.getValue(source) + oldTerms.remove(previous) + if (oldTerms.isEmpty) termsBySource.remove(source) + } + relationEdges.remove(term.id)?.forEach(::removeRelation) + } + terms[term.id] = term + forEachForm(term) { source -> + termsBySource.computeIfAbsent(source) { ObjectArrayList(1) }.add(term) + } + val edges = ObjectArrayList() + for ((relation, ids) in term.relations) { + for (relatedId in ids) { + addRelation(RelationKey(term.id, relation), relatedId, edges) + if (relation == TermRelation.SYNONYM) { + addRelation(RelationKey(relatedId, relation), term.id, edges) + } + } + } + relationEdges[term.id] = edges + } + + override fun find(id: String): GlossaryTerm? = terms[id] + + override fun findBySource(normalizedSource: String): Iterable = termsBySource[normalizedSource] ?: emptyList() + + override fun findRelated(id: String, relation: TermRelation): Iterable { + val ids = relatedIds[RelationKey(id, relation)] ?: return emptyList() + val related = ObjectArrayList(ids.size) + for (relatedId in ids) terms[relatedId]?.let(related::add) + return related + } + + private fun addRelation(key: RelationKey, targetId: String, edges: ObjectArrayList) { + relationCounts.computeIfAbsent(key) { Object2IntOpenHashMap() }.addTo(targetId, 1) + relatedIds.computeIfAbsent(key) { ObjectLinkedOpenHashSet() }.add(targetId) + edges.add(RelationEdge(key, targetId)) + } + + private fun removeRelation(edge: RelationEdge) { + val counts = relationCounts.getValue(edge.key) + if (counts.addTo(edge.targetId, -1) == 1) { + counts.removeInt(edge.targetId) + if (counts.isEmpty()) relationCounts.remove(edge.key) + val ids = relatedIds.getValue(edge.key) + ids.remove(edge.targetId) + if (ids.isEmpty()) relatedIds.remove(edge.key) + } + } + + private inline fun forEachForm(term: GlossaryTerm, action: (String) -> Unit) { + val source = term.source.lowercase() + if (term.aliases.isEmpty()) { + action(source) + return + } + val forms = ObjectOpenHashSet(term.aliases.size + 1) + forms.add(source) + for (alias in term.aliases) forms.add(alias.lowercase()) + forms.forEach(action) + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/LocalizationCatalog.kt b/src/main/java/com/modularmc/registrate/localization/terminology/LocalizationCatalog.kt deleted file mode 100644 index 1205661..0000000 --- a/src/main/java/com/modularmc/registrate/localization/terminology/LocalizationCatalog.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.modularmc.registrate.localization.terminology - -import com.modularmc.registrate.localization.MinecraftLocale - -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap - -import java.util.EnumSet -import java.util.Optional - -/** Terminology defined by one mod. Register it during mod setup and query it alongside declarations. */ -class LocalizationCatalog { - @JvmRecord - data class GlossaryTerm(val id: String, val source: String, val domains: List, val preferredTranslations: Map) - - @JvmRecord - data class Unit(val id: String, val symbol: String, val names: Map) - - private val domains = EnumSet.noneOf(Domain::class.java) - private val terms = Object2ObjectOpenHashMap() - private val units = Object2ObjectOpenHashMap() - - fun register(domain: Domain) { - domains.add(domain) - } - - fun register(term: GlossaryTerm) { - terms[term.id] = term - } - - fun register(unit: Unit) { - units[unit.id] = unit - } - - fun hasDomain(domain: Domain): Boolean = domains.contains(domain) - - fun glossary(id: String): Optional = Optional.ofNullable(terms[id]) - - fun unit(id: String): Optional = Optional.ofNullable(units[id]) -} diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt b/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt new file mode 100644 index 0000000..cabcce9 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt @@ -0,0 +1,169 @@ +package com.modularmc.registrate.localization.terminology + +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.TextType +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap +import it.unimi.dsi.fastutil.objects.ObjectArrayList +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet + +import java.util.Optional + +/** 保存单个模组定义的术语。模组初始化时注册,解析本地化声明时查询。 */ +class Terminology { + /** 带有独立标识的一个术语义项。领域和文本类型用于消除歧义,译文、别名和关系供查询与数据生成使用。 */ + @JvmRecord + data class GlossaryTerm @JvmOverloads constructor( + val id: String, + val source: String, + val domains: List, + val preferredTranslations: Map, + val textTypes: Set = emptySet(), + val acceptedTranslations: Map> = emptyMap(), + val forbiddenTranslations: Map> = emptyMap(), + val aliases: Set = emptySet(), + val relations: Map> = emptyMap(), + val unitIds: Set = emptySet(), + ) { + internal fun matches(sourceText: String): Boolean = source.equals(sourceText, ignoreCase = true) || aliases.any { it.equals(sourceText, ignoreCase = true) } + } + + /** 定义术语之间的同义、上下位、组成部分和一般关联。 */ + enum class TermRelation { + SYNONYM, + BROADER, + NARROWER, + PART_OF, + HAS_PART, + RELATED, + } + + /** 记录一个单位的稳定标识、显示符号及分语言的名称和格式。 */ + @JvmRecord + data class MeasurementUnit @JvmOverloads constructor(val id: String, val symbol: String, val names: Map, val formats: Map = emptyMap()) { + /** 按目标语言的注册格式显示数值和单位。缺少该语言的格式时,用一个空格连接数值与符号。 */ + fun format(value: Number, locale: MinecraftLocale): String = formats[locale]?.format(value, symbol) ?: "$value $symbol" + } + + private val domains = ObjectOpenHashSet() + private val indexedGlossary = IndexedGlossary() + private val glossaries = ObjectArrayList(1).apply { add(indexedGlossary) } + private val units = Object2ObjectOpenHashMap() + + /** 登记供本地化声明引用的领域。 */ + fun register(domain: Domain) { + domains.add(domain) + } + + /** 将术语存入模组自带的词汇表。已有同标识术语时,同时替换旧的词形和关系索引。 */ + fun register(term: GlossaryTerm) { + indexedGlossary.register(term) + } + + /** 挂接外部词汇表。数据生成期间会用它查询术语、别名和关系。 */ + fun register(glossary: Glossary) { + glossaries.add(glossary) + } + + /** 按稳定标识登记单位。同一标识再次登记时采用新定义。 */ + fun register(unit: MeasurementUnit) { + units[unit.id] = unit + } + + /** 检查领域是否已在当前模组登记。 */ + fun hasDomain(domain: Domain): Boolean = domains.contains(domain) + + internal fun synonyms(term: GlossaryTerm): ObjectArrayList { + val discovered = ObjectOpenHashSet() + val pending = ObjectArrayList(4) + val result = ObjectArrayList(4) + discovered.add(term.id) + pending.add(term) + result.add(term) + var index = 0 + while (index < pending.size) { + val current = pending[index++] + for (glossary in glossaries) { + for (related in glossary.findRelated(current.id, TermRelation.SYNONYM)) { + if (discovered.add(related.id)) { + pending.add(related) + result.add(related) + } + } + } + } + return result + } + + /** 按稳定标识查询术语,没有匹配的定义时返回空值。 */ + fun glossary(id: String): Optional = Optional.ofNullable(findTerm(id)) + + /** 按稳定标识查找显示单位,没有匹配的定义时返回空值。 */ + fun unit(id: String): Optional = Optional.ofNullable(units[id]) + + internal fun unitSymbol(id: String): String = units.getValue(id).symbol + + internal fun resolveTerm(key: TranslationKey, declaration: LocalizationDeclaration, source: TranslationSource): GlossaryTerm? { + if (declaration.glossary.isNotEmpty() || declaration.glossaryIds.isNotEmpty()) { + resolveExplicitTerm(key, declaration, source)?.let { return it } + } + if (glossaries.size == 1 && indexedGlossary.isEmpty()) return null + + val label = declaration.source.lowercase() + val type = declaration.type + val domains = declaration.domains + var best: GlossaryTerm? = null + var other: GlossaryTerm? = null + var bestScore = -1 + for (glossary in glossaries) { + for (term in glossary.findBySource(label)) { + val domainMatches = term.domains.any { it in domains } + if (domains.isNotEmpty() && term.domains.isNotEmpty() && !domainMatches) continue + val typeMatches = type != null && type in term.textTypes + if (type != null && term.textTypes.isNotEmpty() && !typeMatches) continue + + val score = (if (domainMatches) 1 else 0) + (if (typeMatches) 1 else 0) + if (score > bestScore) { + bestScore = score + best = term + other = null + } else if (score == bestScore && term.id != best?.id) { + other = term + } + } + } + val selected = best ?: return null + if (other != null) ambiguousTerm(key, source, selected, other) + return selected + } + + private fun resolveExplicitTerm(key: TranslationKey, declaration: LocalizationDeclaration, source: TranslationSource): GlossaryTerm? { + var selected: GlossaryTerm? = null + + fun consider(term: GlossaryTerm) { + if (!term.matches(declaration.source)) return + val previous = selected + if (previous != null && previous.id != term.id) ambiguousTerm(key, source, previous, term) + selected = term + } + + for (term in declaration.glossary) consider(term) + for (id in declaration.glossaryIds) { + val term = requireNotNull(findTerm(id)) { "Unknown glossary term '$id' for $key at ${source.location}" } + consider(term) + } + return selected + } + + private fun findTerm(id: String): GlossaryTerm? = glossaries.firstNotNullOfOrNull { it.find(id) } + + private fun ambiguousTerm(key: TranslationKey, source: TranslationSource, first: GlossaryTerm, second: GlossaryTerm): Nothing = + throw IllegalArgumentException("Ambiguous glossary term for $key at ${source.location}: ${first.id} or ${second.id}") + + internal companion object { + val EMPTY = Terminology() + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/UnitFormat.kt b/src/main/java/com/modularmc/registrate/localization/terminology/UnitFormat.kt new file mode 100644 index 0000000..535681a --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/terminology/UnitFormat.kt @@ -0,0 +1,15 @@ +package com.modularmc.registrate.localization.terminology + +import java.text.DecimalFormat +import java.text.DecimalFormatSymbols +import java.util.Locale + +/** 按 `DecimalFormat` 格式化数值,并在数值后拼接已登记的单位符号。 */ +@JvmRecord +data class UnitFormat(val numberPattern: String, val decimalSeparator: Char, val spacing: String) { + /** 使用当前小数分隔符和数字格式生成数值,再拼接设置的间距及 [symbol]。 */ + fun format(value: Number, symbol: String): String { + val symbols = DecimalFormatSymbols.getInstance(Locale.ROOT).apply { decimalSeparator = this@UnitFormat.decimalSeparator } + return DecimalFormat(numberPattern, symbols).format(value) + spacing + symbol + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/text/ComponentUtils.kt b/src/main/java/com/modularmc/registrate/localization/text/ComponentUtils.kt new file mode 100644 index 0000000..6f4e7d5 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/text/ComponentUtils.kt @@ -0,0 +1,224 @@ +package com.modularmc.registrate.localization.text + +import com.modularmc.mmclutils.utils.ColorUtils +import com.modularmc.mmclutils.utils.NumberUtils + +import net.minecraft.ChatFormatting +import net.minecraft.Util +import net.minecraft.network.chat.Component +import net.minecraft.network.chat.MutableComponent +import net.minecraft.network.chat.Style +import net.minecraft.network.chat.contents.PlainTextContents +import net.minecraft.world.level.block.state.properties.Property + +import it.unimi.dsi.fastutil.objects.ObjectArrayList + +import java.util.function.UnaryOperator +import java.util.stream.Collector +import java.util.stream.Collectors + +/** 构造和组合原版文本组件,保留子组件的翻译键和样式。 */ +object ComponentUtils { + /** + * 将方块状态属性名与序列化后的值组成一行。布尔值为真时用绿色,为假时用红色。 + * + * @param property 要显示的方块状态属性 + * @param value 该属性的值 + * @return 包含属性名和属性值的组件 + */ + @JvmStatic + fun propertyText(property: Property<*>, value: Comparable<*>): MutableComponent { + val name = Component.literal(Util.getPropertyName(property, value)) + if (value is Boolean) name.withStyle(if (value) ChatFormatting.GREEN else ChatFormatting.RED) + return Component.literal(property.name).append(": ").append(name) + } + + /** 将长整数按紧凑数值格式封装为字面组件。 */ + @JvmStatic + fun numberText(value: Long): MutableComponent = Component.literal(NumberUtils.format(value)) + + /** 将浮点数按紧凑数值格式封装为字面组件,保留非有限值的标准文本。 */ + @JvmStatic + fun numberText(value: Double): MutableComponent = Component.literal(NumberUtils.format(value)) + + /** + * 用翻译键显示百分数,数值最多保留两位小数,百分号由译文提供。 + * + * @param translationKey 用于显示百分数的翻译键 + * @param percent 已按百分数表示的数值 + * @return 以格式化数值为参数的翻译组件 + */ + @JvmStatic + fun percentText(translationKey: String, percent: Double): MutableComponent = Component.translatable(translationKey, NumberUtils.formatTwoDecimals(percent)) + + /** 创建一个可继续追加的列表,首行为给定的字面文本。 */ + @JvmStatic + fun literalLine(text: String): MutableList = ObjectArrayList(1).apply { add(Component.literal(text)) } + + /** 将长整数的十进制文本放入单行可修改列表。 */ + @JvmStatic + fun literalLine(value: Long): MutableList = literalLine(value.toString()) + + /** 将浮点数的标准文本放入单行可修改列表。 */ + @JvmStatic + fun literalLine(value: Double): MutableList = literalLine(value.toString()) + + /** 按当前语言解析各行,用换行符拼接为纯文本。 */ + @JvmStatic + fun plainText(lines: Iterable): String = lines.joinToString("\n") { it.string } + + /** + * 从单行文本读取整数。空列表视为零。 + * + * @throws NumberFormatException 含多行、文本无法解析为整数或数值超出整数范围 + */ + @JvmStatic + fun parseInt(lines: List): Int = if (lines.isEmpty()) 0 else singleLineText(lines).toInt() + + /** + * 从单行文本读取浮点数。空列表视为零。 + * + * @throws NumberFormatException 含多行或文本无法解析为浮点数 + */ + @JvmStatic + fun parseDouble(lines: List): Double = if (lines.isEmpty()) 0.0 else singleLineText(lines).toDouble() + + private fun singleLineText(lines: List): String { + if (lines.size != 1) throw NumberFormatException("Expected a single numeric line") + return lines.first().string + } + + /** + * 将首行接到目标的末行,其余各行作为新行加入。目标为空时先创建首行。 + * + * @param target 就地更新的目标列表 + * @param lines 来自独立列表的待追加行 + */ + @JvmStatic + fun appendLines(target: MutableList, lines: List) { + val iterator = lines.iterator() + if (!iterator.hasNext()) return + + val lastLine = target.lastOrNull() ?: Component.empty().also { target.add(it) } + lastLine.append(iterator.next()) + while (iterator.hasNext()) target.add(Component.empty().append(iterator.next())) + } + + /** + * 将追加项接到目标组件上。两者都有自身内容或子组件时,在中间插入分隔符。 + * 追加项为空时直接返回目标组件。 + */ + @JvmStatic + fun appendSeparated(target: MutableComponent, addition: Component, separator: Component): MutableComponent { + if (!addition.hasContent()) return target + if (target.hasContent()) target.append(separator) + return target.append(addition) + } + + private fun Component.hasContent(): Boolean = contents !== PlainTextContents.EMPTY || siblings.isNotEmpty() + + /** 给列表条目加引号后生成预览。超过五项时保留首尾各两项,中间显示省略号。 */ + @JvmStatic + fun previewList(entries: List, entryStyle: Style): MutableComponent { + val preview = ObjectArrayList(minOf(entries.size, 5)) + if (entries.size <= 5) { + entries.mapTo(preview) { quoted(it, entryStyle) } + } else { + preview.add(quoted(entries.first(), entryStyle)) + preview.add(quoted(entries[1], entryStyle)) + preview.add(Component.literal("…")) + preview.add(quoted(entries[entries.lastIndex - 1], entryStyle)) + preview.add(quoted(entries.last(), entryStyle)) + } + return Component.literal("[").append(join(preview, Component.literal(", "))).append("]") + } + + private fun quoted(text: String, style: Style): MutableComponent = Component.literal("\"$text\"").setStyle(style) + + /** 按遍历顺序拼接组件,在相邻项之间插入分隔符,并保留各子组件的翻译键和样式。 */ + @JvmStatic + fun join(components: Iterable, separator: Component): MutableComponent { + val result = Component.empty() + val iterator = components.iterator() + if (iterator.hasNext()) result.append(iterator.next()) + while (iterator.hasNext()) result.append(separator).append(iterator.next()) + return result + } + + /** 创建与 [join] 一致的流收集器,按流的遍历顺序拼接组件。 */ + @JvmStatic + fun joining(separator: Component): Collector { + val parts = Collectors.toCollection { ObjectArrayList() } + return Collectors.collectingAndThen(parts) { join(it, separator) } + } + + /** + * 按游戏刻从色板中循环选色,返回只修改文本颜色的样式变换。 + * + * @param tick 调用方提供的当前游戏刻 + * @param ticksPerColor 每种颜色持续的游戏刻数,至少为一 + * @param colors 按使用顺序排列的色板,至少包含一种颜色 + */ + @JvmStatic + fun cyclingColor(tick: Long, ticksPerColor: Int, vararg colors: Int): UnaryOperator